转自http://blog.csdn.net/zjujoe/article/details/5659253

尝试Android Scripting Environment之二


作者:宋立新

Email:zjujoe@yahoo.com

前言

前文<<尝试ASE>>中我们写了一个脚本,可以通过ADB在PC端控制ASE Python脚本的执行。这里,我们就通过该脚本,研究一下ASE自带的例子,从而知道ASE的能力,为我们或许编写自己的测试脚本做准备。

简介

ASE通过Android Façade封装了很多方法,这些方法调用了Android的API来实现功能。我们正是通过这些方法来实现我们的功能。

从:http://code.google.com/p/android-scripting/wiki/AndroidFacadeAPI

可知,这些方法都有相同的返回值:

All ASE API calls return an object with three fields:

  • id: a strictly increasing, numeric id associated with the API call.
  • result: the return value of the API call, or null if there is no return value.
  • error: a description of any error that occurred or null if no error occurred.

从:http://code.google.com/p/android-scripting/wiki/ApiReference

可以查到所有的API

当然,具体看示例代码时会发现,除了Android FacadeAPI对应的android package外,还用到很多其他package,由于本人对python不熟(语法还是大体知道的,但是那么多package就基本不懂了),所以研究的过程中需要不时Google一下那些包的使用,一并记录在此。

Python的参考可以用:http://docs.python.org/release/2.5/lib/lib.html

当然,ASE带的python似乎还添加了一些非标准包,比如Google doc service.

hello_world.py

1 import android

这里导入android包

2 droid = android.Android()

获得android对象

3 droid.makeToast('Hello, Android!')

调用android方法:makeToast

对Android API熟悉的话应该知道Toast就是一个提示对话框。

test.py各种测试

比较直白的部分我们就不分析了。。。

import部分

1 import sys

2 import types

3

4 # Test imports.

5 import android

6 import BeautifulSoup

From:http://hi.baidu.com/javalang/blog/item/84bac4bf731fb80f18d81fe1.html

Beautiful Soup是用Python写的一个HTML/XML的解析器,它可以很好的处理不规范标记并生成剖析树(parse tree)。它提供简单又常用的导航(navigating),搜索以及修改剖析树的操作。它可以大大节省你的编程时间。对于Ruby,使用Rubyful Soup。

7 import gdata.docs.service

From:http://code.google.com/p/gdata-python-client/

The Google Data APIs (Google Data) provide a simple protocol for reading and writing data on the web. Though it is possible to use these services with a simple HTTP client, this library provides helpful tools to streamline your code and keep up with server-side changes.

8 import sqlite3

From:http://docs.python.org/release/2.5/lib/module-sqlite3.html

SQLite is a C library that provides a lightweight disk-based database that doesn't require a separate server process and allows accessing the database using a nonstandard variant of the SQL query language. Some applications can use SQLite for internal data storage. It's also possible to prototype an application using SQLite and then port the code to a larger database such as PostgreSQL or Oracle.

9 import termios

From:http://docs.python.org/release/2.5/lib/module-termios.html

This module provides an interface to the POSIX calls for tty I/O control. For a complete description of these calls, see the POSIX or Unix manual pages. It is only available for those Unix versions that support POSIX termios style tty I/O control (and then only if configured at installation time).

10 import time

From:http://docs.python.org/release/2.5/lib/module-time.html

This module provides various time-related functions. It is always available, but not all functions are available on all platforms. Most of the functions defined in this module call platform C library functions with the same name. It may sometimes be helpful to consult the platform documentation, because the semantics of these functions varies among platforms.

11 import xmpp

From:http://xmpppy.sourceforge.net/

xmpppy is a Python library that is targeted to provide easy scripting with Jabber. Similar projects are Twisted Wordsand jabber.py.

12

13 droid = android.Android()

14

15

event_loop

Helper函数

16 def event_loop():

17for i in range(10):

18e = droid.receiveEvent()

Receives the most recent event (i.e. location or sensor update, etc.)

19if e.result is not None:

20return True

21time.sleep(2)

22return False

尝试接收一个event, retry 10次。

test_clipboard:

尝试系统剪切板能否工作

25 def test_clipboard():

26previous = droid.getClipboard().result

27msg = 'Hello, world!'

28droid.setClipboard(msg)

29echo = droid.getClipboard().result

30droid.setClipboard(previous)

31return echo == msg

test_gdata

尝试连接Google doc service

34 def test_gdata():

35# Create a client class which will make HTTP requests with Google Docs server.

36client = gdata.docs.service.DocsService()

37

38# Authenticate using your Google Docs email address and password.

39username = droid.getInput('Username').result

40password = droid.getPassword('Password', 'For ' + username).result

41try:

42client.ClientLogin(username, password)

43except:

44return False

45

46# Query the server for an Atom feed containing a list of your documents.

47documents_feed = client.GetDocumentListFeed()

48# Loop through the feed and extract each document entry.

49return bool(list(documents_feed.entry))

test_gps

52 def test_gps():

53droid.startLocating()

54try:

55return event_loop()

56finally:

57droid.stopLocating()

test_sensors(运行失败)

60 def test_sensors():

61droid.startSensing()

62try:

63return event_loop()

64finally:

65droid.stopSensing()

test_speak (pass但是听不到声音)

68 def test_speak():

69result = droid.speak('Hello, world!')

Speaks the provided message via TTS.

70return result.error is None

test_phone_state跟踪phone状态

73 def test_phone_state():

74droid.startTrackingPhoneState()

75try:

76return event_loop()

77finally:

78droid.stopTrackingPhoneState()

test_ringer_silent打开、关闭静音模式

81 def test_ringer_silent():

82result1 = droid.toggleRingerSilentMode()

83result2 = droid.toggleRingerSilentMode()

84return result1.error is None and result2.error is None

test_ringer_volume设置音量

87 def test_ringer_volume():

88get_result = droid.getRingerVolume()

89if get_result.error is not None:

90return False

91droid.setRingerVolume(0)

92set_result = droid.setRingerVolume(get_result.result)

93if set_result.error is not None:

94return False

95return True

test_get_last_known_location

98 def test_get_last_known_location():

99result = droid.getLastKnownLocation()

100return result.error is None

test_geocode

103 def test_geocode():

104result = droid.geocode(0.0, 0.0, 1)

105return result.error is None

test_wifi打开、关闭Wifi

108 def test_wifi():

109result1 = droid.toggleWifiState()

110result2 = droid.toggleWifiState()

111return result1.error is None and result2.error is None

test_make_toast

114 def test_make_toast():

115result = droid.makeToast('Hello, world!')

116return result.error is None

test_vibrate

119 def test_vibrate():

120result = droid.vibrate()

121return result.error is None

test_notify

124 def test_notify():

125result = droid.notify('Hello, world!')

126return result.error is None

test_get_running_packages

129 def test_get_running_packages():

130result = droid.getRunningPackages()

131return result.error is None

test_alert_dialog

134 def test_alert_dialog():

135title = 'User Interface'

136message = 'Welcome to the ASE integration test.'

137droid.dialogCreateAlert(title, message)

138droid.dialogSetPositiveButtonText('Continue')

139droid.dialogShow()

140response = droid.dialogGetResponse().result

141return response['which'] == 'positive'

test_alert_dialog_with_buttons

144 def test_alert_dialog_with_buttons():

145title = 'Alert'

146message = ('This alert box has 3 buttons and '

147'will wait for you to press one.')

148droid.dialogCreateAlert(title, message)

149droid.dialogSetPositiveButtonText('Yes')

150droid.dialogSetNegativeButtonText('No')

151droid.dialogSetNeutralButtonText('Cancel')

152droid.dialogShow()

153response = droid.dialogGetResponse().result

154return response['which'] in ('positive', 'negative', 'neutral')

test_spinner_progress旋转进度条

157 def test_spinner_progress():

158title = 'Spinner'

159message = 'This is simple spinner progress.'

160droid.dialogCreateSpinnerProgress(title, message)

161droid.dialogShow()

162time.sleep(2)

163droid.dialogDismiss()

164return True

test_horizontal_progress水平进度条

167 def test_horizontal_progress():

168title = 'Horizontal'

169message = 'This is simple horizontal progress.'

170droid.dialogCreateHorizontalProgress(title, message, 50)

171droid.dialogShow()

172for x in range(0, 50):

173time.sleep(0.1)

174droid.dialogSetCurrentProgress(x)

175droid.dialogDismiss()

176return True

test_alert_dialog_with_list列表对话框

179 def test_alert_dialog_with_list():

180title = 'Alert'

181droid.dialogCreateAlert(title)

182droid.dialogSetItems(['foo', 'bar', 'baz'])

183droid.dialogShow()

184response = droid.dialogGetResponse().result

185return True

test_alert_dialog_with_single_choice_list

188 def test_alert_dialog_with_single_choice_list():

189title = 'Alert'

190droid.dialogCreateAlert(title)

191droid.dialogSetSingleChoiceItems(['foo', 'bar', 'baz'])

192droid.dialogSetPositiveButtonText('Yay!')

193droid.dialogShow()

194response = droid.dialogGetResponse().result

195return True

test_alert_dialog_with_multi_choice_lis

198 def test_alert_dialog_with_multi_choice_list():

199title = 'Alert'

200droid.dialogCreateAlert(title)

201droid.dialogSetMultiChoiceItems(['foo', 'bar', 'baz'], [])

202droid.dialogSetPositiveButtonText('Yay!')

203droid.dialogShow()

204response = droid.dialogGetResponse().result

205return True

Test engine

208 if __name__ == '__main__':

209for name, value in globals().items():

210if name.startswith('test_') and isinstance(value, types.FunctionType):

211print 'Running %s...' % name,

212sys.stdout.flush()

213if value():

214print ' PASS'

215else:

216print ' FAIL'

bluetooth_chat.py蓝牙聊天

1 import android

2 import time

3

4 droid = android.Android()

5 droid.toggleBluetoothState(True)

6 droid.dialogCreateAlert('Be a server?')

7 droid.dialogSetPositiveButtonText('Yes')

8 droid.dialogSetNegativeButtonText('No')

9 droid.dialogShow()

10 result = droid.dialogGetResponse()

11 is_server = result.result['which'] == 'positive'

12 if is_server:

13droid.bluetoothMakeDiscoverable()

14droid.bluetoothAccept()

15 else:

16droid.bluetoothConnect()

17

18 if is_server:

19result = droid.getInput('Chat', 'Enter a message').result

20if result is None:

21droid.exit()

22droid.bluetoothWrite(result + '/n')

23

24 while True:

25message = droid.bluetoothReadLine().result

26droid.dialogCreateAlert('Chat Received', message)

27droid.dialogSetPositiveButtonText('Ok')

28droid.dialogShow()

29droid.dialogGetResponse()

30result = droid.getInput('Chat', 'Enter a message').result

31if result is None:

32break

33droid.bluetoothWrite(result + '/n')

34

35 droid.exit()

say_chat.py聊天

1 """Say chat messages aloud as they are received."""

2

3 __author__ = 'Damon Kohler <damonkohler@gmail.com>'

4 __copyright__ = 'Copyright (c) 2009, Google Inc.'

5 __license__ = 'Apache License, Version 2.0'

6

7 import android

8 import xmpp

9

10 _SERVER = 'talk.google.com', 5223

11

12 def log(droid, message):

13print message

14self.droid.speak(message)

15

16

17 class SayChat(object):

18

19def __init__(self):

20self.droid = android.Android()

21username = self.droid.getInput('Username').result

22password = self.droid.getInput('Password').result

23jid = xmpp.protocol.JID(username)

24self.client = xmpp.Client(jid.getDomain(), debug=[])

25self.client.connect(server=_SERVER)

26self.client.RegisterHandler('message', self.message_cb)

27if not self.client:

28log('Connection failed!')

29return

30auth = self.client.auth(jid.getNode(), password, 'botty')

31if not auth:

32log('Authentication failed!')

33return

34self.client.sendInitPresence()

35

36def message_cb(self, session, message):

37jid = xmpp.protocol.JID(message.getFrom())

38username = jid.getNode()

39text = message.getBody()

40self.droid.speak('%s says %s' % (username, text))

41

42def run(self):

43try:

44while True:

45self.client.Process(1)

46except KeyboardInterrupt:

47pass

take_picture.py拍照

1 import android

2

3 droid = android.Android()

4 droid.cameraTakePicture('/sdcard/foo.jpg')

Weather.py

1 """Retrieve the weather report for the current location."""

2

3 __author__ = 'T.V. Raman <raman@google.com>'

4 __copyright__ = 'Copyright (c) 2009, Google Inc.'

5 __license__ = 'Apache License, Version 2.0'

6

7

8 import string

9 import urllib

10 import urllib2

11 from xml.dom import minidom

12

13 WEATHER_URL = 'http://www.google.com/ig/api?weather=%s&hl=%s'

14

15

16 def extract_value(dom, parent, child):

17"""Convenience function to dig out weather values."""

18return dom.getElementsByTagName(parent)[0].getElementsByTagName(child)[0].getAttribute('data')

19

20

21 def fetch_weather(location, hl=''):

22"""Fetches weather report from Google

23

24Args:

25location: a zip code (94041); city name, state (weather=Mountain View,CA);...

26hl: the language parameter (language code)

27

28Returns:

29a dict of weather data.

30

31"""

32url = WEATHER_URL % (urllib.quote(location), hl)

33handler = urllib2.urlopen(url)

34data = handler.read()

35dom = minidom.parseString(data)

36handler.close()

37

38data = {}

39weather_dom = dom.getElementsByTagName('weather')[0]

40data['city'] = extract_value(weather_dom, 'forecast_information','city')

41data['temperature'] = extract_value(weather_dom, 'current_conditions','temp_f')

42data['conditions'] = extract_value(weather_dom, 'current_conditions', 'condition')

43dom.unlink()

44return data

notify_weather.py

getLastKnownLocation

1 """Display the weather report in a notification."""

2

3 __author__ = 'Damon Kohler <damonkohler@gmail.com>'

4 __copyright__ = 'Copyright (c) 2009, Google Inc.'

5 __license__ = 'Apache License, Version 2.0'

6

7 import android

8 import weather

9

10

11 def notify_weather(droid):

12"""Display the weather at the current location in a notification."""

13print 'Finding ZIP code.'

14location = droid.getLastKnownLocation().result

15addresses = droid.geocode(location['latitude'], location['longitude'])

16zip = addresses.result[0]['postal_code']

17if zip is None:

18msg = 'Failed to find location.'

19else:

20print 'Fetching weather report.'

21result = weather.fetch_weather(zip)

22msg = '%(temperature)s degrees and %(conditions)s, in %(city)s.' % result

23droid.notify(msg, 'Weather Report', msg)

24droid.exit()

25

26

27 if __name__ == '__main__':

28droid = android.Android()

29notify_weather(droid)

say_weather.py

1 """Speak the weather."""

2

3 __author__ = 'T.V. Raman <raman@google.com>'

4 __copyright__ = 'Copyright (c) 2009, Google Inc.'

5 __license__ = 'Apache License, Version 2.0'

6

7 import android

8 import weather

9

10

11 def say_weather(droid):

12"""Speak the weather at the current location."""

13print 'Finding ZIP code.'

14location = droid.getLastKnownLocation().result

15addresses = droid.geocode(location['latitude'], location['longitude'])

16zip = addresses.result[0]['postal_code']

17if zip is None:

18msg = 'Failed to find location.'

19else:

20print 'Fetching weather report.'

21result = weather.fetch_weather(zip)

22# Format the result for speech.

23msg = '%(temperature)s degrees and %(conditions)s, in %(city)s.' % result

24droid.speak(msg)

25

26

27 if __name__ == '__main__':

28droid = android.Android()

29say_weather(droid)

更多相关文章

  1. Android(安卓)RecycleView(二)——添加分割线
  2. Android之Service自启动流程
  3. Android疑问1——Handler的removeCallbacks方法无效?(已经明白了)
  4. 直播平台软件开发Android(安卓)Activity横竖屏切换生命周期详解
  5. 运行时动态注销在AndroidManifest.xml声明的BroadcastReceiver,En
  6. uni-app之APP和小程序微信授权方法
  7. android adb root方法
  8. android webview中使用Java调用JavaScript方法并获取返回值
  9. Android更新UI的四种方法详解

随机推荐

  1. ViewDragHelper_v4的滑动视图帮助类_解释
  2. android时间控件TimePicker使用实例
  3. Glide 使用 +圆形图+圆角图
  4. 反射得到全局Context
  5. Android(安卓)获取当前连接的WiFi信息
  6. Android工程方法数超过65535
  7. make update-api 提示。
  8. androidx.lifecycle.Transformations函数
  9. AndroidStudio 3.4.1 DrawerLayout 侧滑
  10. Android(安卓)Dialog背景全透明 无边框