EasyMonkeyDevice

EasyMonkeyDevice 其实就是在前几章描述的 MonkeyDevice 和 HierarchyViewer 的基础上加了一层 Wrapper,把原来的通过接受坐标点或者 ViewNode 来操作控件的思想统一成通过控件 ID 来操作,其实最终它们都会转换成坐标点或 ViewNode 进行操作
ps:写个教程,方便大家学习之外,到时候做内部培训也可以用

EaysyMonkeyDevice API

连接设备

#EasyMonkeyDevice(MonkeyDevice device)
device = MonkeyRunner.waitForConnection()
eDevice=EasyMonkeyDevice(device)

触摸点击

#touch(By selector,TouchPressType type)
eDevice.touch(By.id('id/text1'),MonkeyDevice.DOWN_AND_UP)

设置文本信息

#type(By selector, String text)
eDevice.type(By.id(noteId), 'New')

元素是否存在

#exists(By selector)
noteId = 'id/note'
if True == eDevice.exists(By.id(noteId)):
    print 'Note exist'
else:
    print 'Note not found!'
    exit(2)

元素是否可见

#visible(By selector)
if True == eDevice.visible(By.id(noteId)):

    print 'Note is visible'

else:

    print 'Note is invisible'

    exit(3)

获取元素的文本

#getText(By selector)
text = eDevice.getText(By.id(noteId))

获取窗口的 id

#getFocusedWindowId()
winId = eDevice.getFocusedWindowId()

获取当前元素的坐标

#locate(By selector)
locate = eDevice.locate(By.id(noteId))
print 'Location(x,y,w,h) is:',locate

一个 demo

from com.android.monkeyrunner import MonkeyRunner,MonkeyDevice,MonkeyImage
from com.android.monkeyrunner.easy import EasyMonkeyDevice,By
from com.android.chimpchat.hierarchyviewer import HierarchyViewer
from com.android.hierarchyviewerlib.models import ViewNode, Window
from java.awt import Point

#from com.android.hierarchyviewerlib.device import 

#Connect to the target device

device = MonkeyRunner.waitForConnection()

eDevice=EasyMonkeyDevice(device) 
device.startActivity(component="com.example.android.notepad/com.example.android.notepad.NotesList")

#Step 1: try touching on the first note
eDevice.touch(By.id('id/text1'),
              MonkeyDevice.DOWN_AND_UP)

#Step 2: Get the window ID 
winId = 'com.example.android.notepad/\
    com.example.android.notepad.NoteEditor'
#Need to sleep a while till ready
MonkeyRunner.sleep(3)
winId = eDevice.getFocusedWindowId() 
if(winId == winId):
    print "Edit Note WinId is:",\
        winId.encode('utf-8')
else:
    print "Failed"
    exit(1)

#Step3: is note EditText exist?
noteId = 'id/note'
if True == eDevice.exists(By.id(noteId)):
    print 'Note exist'
else:
    print 'Note not found!'
    exit(2)

#Step4: is note EditText visible?
if True == eDevice.visible(By.id(noteId)):
    print 'Note is visible'
else:
    print 'Note is invisible'
    exit(3)

#Step 4: getText
text = eDevice.getText(By.id(noteId))
print 'Note text:',text.encode('utf-8')

#Step 5: setText
eDevice.type(By.id(noteId), 'New')

#Step 6: locate
locate = eDevice.locate(By.id(noteId))
print 'Location(x,y,w,h) is:',locate


↙↙↙阅读原文可查看相关链接,并与作者交流