在Android上使用monkeyrunner截图

时间:2011-04-19 10:38:14

标签: android screenshot monkeyrunner

我正在使用以下脚本截取屏幕截图:

def snap():
    from com.android.monkeyrunner import MonkeyRunner, MonkeyDevice
    print "Waiting for device.."
    device = MonkeyRunner.waitForConnection()
    print "Device found.."
    result = device.takeSnapshot()
    print "Clicked.."
    now = datetime.datetime.now()
    file = "C:\\Workspace\\"+now.strftime("%d%m%Y-%H%M%S")+".png"
    result.writeToFile(file,'png')
    print file

我把它放在一个while循环中,它适用于一个屏幕截图。但是在那个截图之后,输出就像这样无情地挂起了:

C:\Program Files\Android\android-sdk\tools>monkeyrunner C:\Workspace\snap.py
Click (y/n)?y
User said: y
Calling function..
Waiting for device..
Device found..
Clicked..
C:\Workspace\19042011-155124.png
Click (y/n)?y
User said: y
Calling function..
Waiting for device..

如何防止代码阻塞并继续截屏?这是设备内存问题吗?

3 个答案:

答案 0 :(得分:2)

device = MonkeyRunner.waitForConnection()移出循环,并保持与设备的连接打开。

答案 1 :(得分:0)

要强制断开连接,您可能会终止此过程。不优雅,但没有办法从monkeyrunner关闭连接。

...
pid = int(filter(lambda p: len(p) == 9 and p[8] == 'com.android.commands.monkey', map(lambda l: l.split(), device.shell('ps').splitlines()))[0][1])
print "killing %s" % pid
device.shell("kill %d" % pid)
device = None
...

答案 2 :(得分:0)

我宁愿在monkeyrunner脚本中使用shell中的adb pull命令,如此

 
os.system('adb pull /dev/graphics/fb0 image')
subprocess.call('ffmpeg -vframes 1 -vcodec rawvideo -loglevel quiet -f  rawvideo -pix_fmt rgba -s 480x854 -i image -f image2 -vcodec png image.png')

注意:它使用ffmpeg将原始数据转换为png文件。 FFMPEG应该在路径中 这样做是因为通常takenapshot()API运行异常 480x854是设备分辨率,根据您的设备进行更改 通过这种方法,我可以拍摄一系列快照。

如果你对device.takesnapshot()感兴趣,请尝试在两者之间添加time.sleep(),这可能有所帮助。