MonkeyDevice API 教程

来源:互联网 发布:有关人工智能爱情电影 编辑:程序博客网 时间:2024/06/11 10:48


monkeyrunner类代表运行monkeyrunner的工作站可以访问到的设备或模拟器。 这个类用于控制一个Android设备或模拟器。这个方法可以发送UI事件,检索信息,安装和删除应用程序,以及运行应用程序。 你通常不需要创建一个MonkeyDevice实例。取而代之的做法,是使用MonkeyRunner.waitForConnection()连接到设备或模拟器来创建一个新的对象。如,不是用:

newdevice = MonkeyDevice()

而是用

newdevice = MonkeyRunner.waitForConnection()

概要

常量stringDOWN作为press()或touch()的类型变量发送DOWN事件stringUP作为press()或touch()的类型变量发送DOWN事件stringDOWN_AND_UP作为press()或touch()的类型变量发送DOWN事件后紧跟UP事件方法voidbroadcastIntent (string uri, string action, string data, string mimetype, iterable categories dictionary extras, component component, iterable flags)

向设备广播一个Intent,如发自某应用程序的Intent。

voiddrag (tuple start, tuple end, float duration, integer steps)

模拟设备屏幕的拖拽手势(触摸,手持,移动)

objectgetProperty (string key)

给定的系统环境变量名称,返回本设备上这个变量的值。可用的变量名都列于该方法的详细描述中。

objectgetSystemProperty (string key)

adb shell getprop <key>的API等价物。供平台开发人员使用。

voidinstallPackage (string path)

将Android应用程序或测试包中的packageFile安装到设备上。如果应用程序或测试包已安装,则其会被替换。

dictionaryinstrument (string className, dictionary args)

在Android instrument运行指定的组件,并将结果返回到dictionary中。该dictionary的格式由运行的组件所定义,该组件必须在设备上客观存在。

voidpress (string name, dictionary type)

将由type指定的键盘事件发送到由键码指定的键。

voidreboot (string into)

重启本设备,引导至由bootloadType指定的bootloader。

voidremovePackage (string package)

从设备删除指定的包,包括清除其数据和缓存。

objectshell (string cmd)

执行adbshell命令并返回结果(若有的话)。

voidstartActivity (string uri, string action, string data, string mimetype, iterable categories

dictionary extras, component component, flags) 发送一个由提供的参数构建的Intent,在设备上启动一个Activity。

MonkeyImagetakeSnapshot()

捕获装置整个屏幕的缓存,生成一个包含当前显示截屏的MonkeyImage对象。

voidtouch (integer x, integer y, integer type)

将由type指定的触摸事件发送到由x和y指定的屏幕位置。

voidtype (string message)

向设备发送字符消息,如同在装置上的有这些键盘输入。这相当于利用键盘事件类型DOWN_AND_UPmessage里包含的各个

键码[keycoad]调用press()。

voidwake ()

激活设备屏幕.

常量

string DOWN

press()touch()值。向设备发送DOWN事件类型,用以响应按下某键或触摸屏幕。


string UP

press()touch()值。向设备发送UP事件类型,用以响应释放某键或离开屏幕。


string DOWN_AND_UP

press()touch()type()值。DOWN事件后紧跟UP事件应向设备发送的事件类型,对应敲击某键或点击屏幕。

public方法

void broadcastIntent ( string uri, string action, string data, string mimetype, iterable categories dictionary extras, component component, iterable flags)

向设备广播一条Intent, 如发自应用的Intent.更多详情参见Intent.
变量
uri Intent的URI. (参见Intent.setData()).
action Intent的动作 (参见Intent.setAction()).
data Intent的data URI (参见Intent.setData()).
mimetype Intent的MIME类型 (参见I:ntent.setType()).
categories 可迭代的数据结构,包含对Intent种类有定义的字符串 (参见Intent.addCategory()).
extras Intent附加数据的dictionary (用例参见java.lang.String) Intent.putExtra()).dictionary各条目的键必须为字符串型. 而各条目的值可以使简单数据类型,也可以是复杂数据类型.
component Intent的组件 (参见ComponentName). 本变量的使用会将Intent指向特定Android包的特定类.
flags 可迭代的数据结构,包含控制Intent如何处理的标记 (参见Intent.setFlags()).


void drag ( tuple start, tuple end, float duration, integer steps)

模拟设备屏幕上发生的拖拽手势 (触摸, 保持, 移动)
变量
start 拖拽手势的起始点, 格式为tuple (x,y),其中x与y均为整数.
end 拖拽手势的结束点, 格式为tuple (x,y),其中x与y均为整数.
duration 拖拽手势的持续时间,以秒为单位. 默认为1.0秒.
steps 对点进行插值所进行的步数.默认值为10.


object getProperty (string key)

给定系统环境变量的名称, 返回设备上的值.
变量
key 系统环境变量的名称. 可用变量名列在本文末尾的表1.
返回值

变量的值. 数据格式根据变量需求会有所改变.

示例:

[python] view plaincopy
  1. displayWidth =targetDevice.getProperty ('display.width')  
  2. printdisplayWidth.encode('utf-8')  
  3.    

object getSystemProperty (string key)

示例:

[python] view plaincopy
  1. displayWidth = targetDevice.getSystemProperty ('service.adb.tcp.port')  
  2. print displayWidth.encode('utf-8')

void installPackage (string path)

在设备上安装Android应用或文件包中包含的测试包.若应用或测试包已安装过,那么其将被替换.
变量

path 要安装的.apk文件的完整路径及文件名.

示例:(注意此方法为Obsolete,返回值是Boolean)

[python] view plaincopy
  1. if True == targetDevice.installPackage('D:\\Projects\\Workspace\\PythonMonkeyRunnerDemo\\apps\\MPortal.apk'):  
  2.    print "Installationfinished successfully"  
  3. else:  
  4.     print "Failedto install the apk"  

dictionary instrument ( string className, dictionary args)

运行Android instrumentation指定的组件, 并在dictionary返回结果,此dictionary的格式由正在运行的组件所指定. 该组件必须在设备上客观存在.
用此方法启动测试,该测试案例调用了Android's测试案例的类. 欲了解Android测试框架的更多详情,参见[Testing Fundamentals].
变量
className 设备上已安装的Android组件名称, 标准格式为packagename/classname,packagename指设备上.apk文件的Android包名,classname指该文件里Android组件(Activity, ContentProvider, Service, or BroadcastReceiver)的类名.packagename和classname都必须为完整路径.更多详情参阅ComponentName.
args 包含标记以及其值的dictionary. 在组件启动时这些值就会被传过去. 若标记不带有值,那么将dictionary值设为空字符串.
返回值
包含组件输出的dictionary.dictionary的内容由组件自身定义.
若将InstrumentationTestRunner作为componentName变量的类名, 结果dictionary就会包含单个键"stream"."stream"的值为包含测试输出的字符串,如同InstrumentationTestRunner在命令行下运行一样. 输出的格式在Testing in Other IDEs描述.

示例:

[python] view plaincopy
  1. dict = targetDevice.instrument('com.example.android.notepad.tryout/android.test.InstrumentationTestRunner')  
  2. print dict  

指定只跑其中的一个Case:

[python] view plaincopy
  1. dict = dict = targetDevice.instrument('com.example.android.notepad.tryout/android.test.InstrumentationTestRunner',  
  2.                                       {'class':'com.example.android.notepad.tryout.TCCreateNote'})  
  3. print dict  



void press (string name, integer type)

将由type指定的键盘事件发送到由键码指定的按键.
变量
name 待发送的键码名称. 参阅KeyEvent,可得到键码名称的列表. 切记使用键码名称而非其数值.

type 待发送的键盘事件类型. 可用的值有DOWN, UP, 和DOWN_AND_UP.


void reboot (string bootloadType) 重启设备,将其引导到由bootloadType指定的bootloader.

变量
into 重启用到的bootloader类型. 可用的值有"bootloader", "recovery",和"None".


void removePackage (string package)

在设备上删除特定的包, 清除数据及缓存.Obsolete,返回值是Boolean
变量

package 设备上.apk文件的Android包名.

示例:

[python] view plaincopy
  1. if True == targetDevice.removePackage('com.majcit.portal'):  
  2.    print "Succeed toremove the package"  
  3. else:  
  4.     print "Failedto remove teh package"  

object shell (string cmd) 执行adb shell命令并返回结果(若有的话).

变量
cmd adb shell中待执行的命令行. 命令行格式在议题Android Debug Bridge中描述.
返回值
命令行的结果(若有的话). 结果的格式由命令行定义.

示例:

[python] view plaincopy
  1. res = targetDevice.shell('ls /data/local/tmp|grep note')  
  2. print res  

void startActivity( string uri, string action, string data, string mimetype, iterable categories dictionary extras, component component, iterable flags) 发送一个由提供的参数构建的Intent,在设备上启动一个Activity

变量
uri Intent的URI. (参见Intent.setData()).
action Intent的动作 (参见Intent.setAction()).
data Intent的data URI (参见Intent.setData()).
mimetype Intent的MIME类型 (参见I:ntent.setType()).
categories 可迭代的数据结构,包含对Intent种类有定义的字符串 (参见Intent.addCategory()).
extras Intent附加数据的dictionary (用例参见java.lang.String) Intent.putExtra()).
dictionary各条目的键必须为字符串型. 而各条目的值可以使简单数据类型,也可以是复杂数据类型.
component Intent的组件 (详参ComponentName). 本变量的使用会将Intent指向特定的Android包中的特定类.

flags' 一个可迭代的数据结构,包含控制Intent如何处理的标记(参见Intent.setFlags()).

示例:

使用Action和mimetype来启动一个Activity:
[python] view plaincopy
  1. targetDevice.startActivity(action='android.intent.action.VIEW',  
  2.                           mimetype='vnd.android.cursor.dir/vnd.google.note')  

使用component来启动一个Activity:
[python] view plaincopy
  1. targetDevice.startActivity(component="com.example.android.notepad/com.example.android.notepad.NotesList")  

使用action,mimetype和指定extras参数来启动一个Activity:
[python] view plaincopy
  1. targetDevice.startActivity(action='android.intent.action.INSERT',  
  2.                            mimetype='vnd.android.cursor.dir/contact',  
  3.                            extras = {'name':'user1501488''phone':'123-15489'})  

MonkeyImage takeSnapshot ()

捕获设备的全屏缓存, 生成当前显示的屏幕截图.
返回值
包含当前显示截图的MonkeyImage对象.

void touch ( integer x, integer y, string type)

将由type指定的触摸事件发送至由x与y指定的屏幕位置.
变量
x 发生触摸手势的水平位置,以实际设备像素为单位, 从屏幕左边为起始,以当前朝向为准.
y 发生触摸手势的垂直位置,以实际设备像素为单位, 从屏幕左边为起始,以当前朝向为准.
type 所要发送的按键事件. 可用的值有DOWN, UP, 和DOWN_AND_UP.


void type (string message)

向设备发送包含字符的消息, 如同其在设备键盘输入的情况. 等效于为消息中包含的每个键码调用press(),使用键盘事件类型DOWN_AND_UP.
变量
message 包含所要发送的字符的字符串.

void wake ()

唤醒设备屏幕.


MonkeyDevice API 验证代码

#!/user/bin/env monkeyrunner#coding=utf-8from com.android.monkeyrunner import MonkeyRunner,MonkeyDevicefrom com.android.monkeyrunner.easy import EasyMonkeyDevicefrom com.android.monkeyrunner.easy import Byfrom com.android.chimpchat.hierarchyviewer import HierarchyViewerfrom com.android.hierarchyviewerlib.models import ViewNodeimport sysfrom datetime import datetimeMDAU=MonkeyDevice.DOWN_AND_UPmms_id="com.android.mms/com.android.mms.ui.ConversationList"contact_id="com.android.contacts/com.android.contacts.activities.PeopleActivity"device=MonkeyRunner.waitForConnection()device.press('KEYCODE_POWER',MDAU)#press()MonkeyRunner.sleep(1)#sleep()device.drag((550,1850),(550,1000),0.5,50)#drag()MonkeyRunner.alert("sure to install apk","install","OK")#alert()device.installPackage("E:/apk/fqrouterv2.12.7.apk")#installPackage(),安装路径不要有中文device.press("KEYCODE_POWER",MonkeyDevice.DOWN)#press()MonkeyRunner.sleep(4)#sleep()device.press("KEYCODE_POWER",MonkeyDevice.UP)device.touch(550,850,MDAU)#touch()MonkeyRunner.sleep(2)device.touch(870,1080,MDAU)device.reboot()#roboot()device.removePackage("com.ss.android.essay.joke")#removePackage()d=device.shell("pm list packages -3")#shell()print d.encode('utf-8')device.startActivity(contact_id)#startActivity()device.touch(870,155,MDAU)device.type('guo')device.startActivity(contact_id)#startActivity()MonkeyRunner.sleep(2)device.touch(870,155,MDAU)MonkeyRunner.sleep(1)device.type('guo')#type()device.wake()

附录

附:MonkeyDevice 官方API参考文档  http://www.android-doc.com/tools/help/MonkeyDevice.html

表1.getProperty()和getSystemProperty()用到的属性变量名。

属性组属性描述备注buildbuild设备的主板名称详参buildbrand定制系统的运营商或提供者。device设备名称fingerprint当前正在运行的build的唯一标识host
ID变更表的序列号或标签model设备在终端显示的名字product整个产品的名字。tags以逗号分隔的标签,用以描述build,如“unsigned”和“debug”。typebuild类型,如“user”或“eng”。user
CPU_ABI原生代码信息集的名称,格式为CPU类型加ABI协议manufacturer产品/硬件制造商version.incremental资源控制系统用来标识软件版本的内部使用代码。version.release展示给用户的软件名称version.sdk改操作系统所用的SDK版本version.codename当前开发产品的代号,若正式发布了可以叫“REL”displaywidth设备的显示屏宽度,像素级。详参

DisplayMetrics

height设备的显示屏高度,像素级density显示屏的逻辑密度。这是将DIP(密度独立像素)单位缩放至匹配设备分辨率的因数。调整DIP,使其在160像素每寸的显示屏中,1DIP相当于一个像素。比如,一个160-dpi的屏幕,密度为1.0;而120-dpi的屏幕,密度为.75。

这个值并不完全匹配真实屏幕大小,但显示屏DIP变动很大的情况下会有所调整。详参densit。

am.currentpackageAndroid当前正在运行的包的名字。当前正在运行的activity所相关的am.current关键字信息。action当前activity的动作。与包manifest的action元素的name属性的格式相同。comp.class启动当前activity的组件的类名。详参comp.packagecomp.package启动当前activity的组件的包名。组件由包名与类名所指定data启动当前activity的Intent包含的数据(若存在的话)categories类别,由启动当前activity的Intent指定。clockrealtime设备重启开始计时,以毫秒为单位,包括深度睡眠时间。详参

系统时钟

uptime设备重启开始计时,以毫秒为单位,不包括深度睡眠时间。millis以Unix时间戳为起点的当前时间,以毫秒为单位。
0 0
原创粉丝点击