如果你需要實現(xiàn)自動測試,Android 的 monkeyrunner 工具可以幫助你實現(xiàn)自動測試,它提供了一組 API 可以用來控制 Android 設備或模擬器,使用 monkeyrunner,你可以編寫 Python 程序來安裝 Android 應用或是測試包,運行應用或測試,發(fā)送按鍵消息,并可以截屏,然后保存在計算機中。monkeyrunner 主要目的是用來在應用程序或框架層次來測試應用程序或運行單元測試包,但你也可以用作其它目的。
monkeyrunner 工具包不同于 UI/Application Exerciser Monkey(也稱為 Money),money 通過 adb shell 來運行,可以模擬“猴子”隨機按鍵或是發(fā)送系統(tǒng)消息給指定的應用來實現(xiàn) Stress 測試。
monkeyrunner API 主要通過下面三個包:
下面為一個 Python 寫的 monkeyrunner 應用, 因為涉及到 Python 語言,這里不詳細說明了
# Imports the monkeyrunner modules used by this program
from com.android.monkeyrunner import MonkeyRunner, MonkeyDevice
# Connects to the current device, returning a MonkeyDevice object
device = MonkeyRunner.waitForConnection()
# Installs the Android package. Notice that this method returns a boolean,
# so you can test to see if the installation worked.
device.installPackage('myproject/bin/MyApplication.apk')
# sets a variable with the package's internal name
package = 'com.example.android.myapplication'
# sets a variable with the name of an Activity in the package
activity = 'com.example.android.myapplication.MainActivity'
# sets the name of the component to start
runComponent = package + '/' + activity
# Runs the component
device.startActivity(component=runComponent)
# Presses the Menu button
device.press('KEYCODE_MENU','DOWN_AND_UP')
# Takes a screenshot
result = device.takeSnapshot()
# Writes the screenshot to a file
result.writeToFile('myproject/shot1.png','png')
詳細的 API 說明請參考 Android 文檔 ,如果你需要實現(xiàn)自動測試,編寫測試代碼,可以使用 Python 通過 monkeyrunner API 來實現(xiàn)。