MonkeyRunner的使用<二>

MonkeyRunner可以用来做自动化测试,在Android中做动态分析的时候也可以使用它来做行为触发。

不过感觉使用MonkeyRunner来做行为触发还是很局限的。就比如我想实现外界向模拟器拨打电话,或者是发送短信就很难。

如果有好的方法,希望您能告诉我。


在Android的管网上介绍了可以使用MonkeyRunner来启动APK ,但是前提是必须是你要知道要启动的APK的包名和Activity名。

想要启动任何未知的Activity怎么办呢。就比如说,你要在模拟器上安装一个你不知到的APK ,怎么来启动它。

这里用到了Apktool.

1.使用Apktool来反编译我们的目标文件

将APK反编译之后,可以在得到的文件夹下找到AndroidManifest.xml文件

这个时候使用Python来提取出包名和类名,保存在两个文件夹里面。

为什么要怎么做,因为启动MonkeyRunner 的命令是MonkeyRunner -v ALL xxxx.py

我们要想办法传入未知的包名和Activity怎么做,只有通过使用文件的读写操作来达到互动。

2.获取任意程序的包名和Activity的名字。

 

#

# @author  : grace

# @date    : 2013-5-26

# filename : parseManifest.py

# run      : python parseManifest.py



import os

import sys

from xml.dom import minidom



if __name__ == "__main__":

    

   opts, args = getopt.getopt(sys.argv[1:], "d:h", "directory = help")

   

   for op, value in opts:

       if op in ("-d","--directory"):

          _directory = value



xmldoc =minidom.parse(_directory + '/AndroidManifest.xml')



manifest = xmldoc.getElementsByTagName('manifest')[0]



package = manifest.getAttribute('package')



getActivity = xmldoc.getElementsByTagName('activity')[0]



activity = getActivity.getAttribute('android:name')



output = open(_directory + 'package.txt','w')

output.write(package)

output.close()



output = open(_directory + 'activity.txt','w')

output.write(activity)

output.close()

 

 

上面这个程序的代码是用来解析AndroidManifest.xml的,通过这个程序来获得包名和Activity 的名字,将他们分别存储在package.txt  和activity.txt 文件中

这里我们只保存了一个 ,因为只下需要一个Activity就可以启动我们的APK。


3.接下来就是通过MonkeyRunner 来做行为触发

 

#

# @author   : grace

# @date     : 2013-5-25

# filename  : behaviorTrigger.py

# run       : monkeyrunner -v ALL behaviorTrigger.py

#



from com.android.monkeyrunner import MonkeyRunner, MonkeyDevice, MonkeyImage



package = ''



activity = ''



fp = open("package.txt")

package = fp.readline()

fp.close()



fa = open("activity.txt")

activity=fa.readline()

fa.close()



device =MonkeyRunner.waitForConnection()



MonkeyRunner.sleep(1)



runComponent = package + '/' + activity



action = 'android.intent.action.MAIN'



device.startActivity(action = action, component = runComponent)



MonkeyRunner.sleep(2)



res=device.takeSnapshot()



res.writeToFile(  '/shot1.png','png')



device.touch(160,194,MonkeyDevice.DOWN_AND_UP)



res=device.takeSnapshot()



res.writeToFile( '/shot2.png','png')



device.touch(160,374,MonkeyDevice.DOWN_AND_UP)



device.touch(160,194,MonkeyDevice.DOWN_AND_UP)



res=device.takeSnapshot()



res.writeToFile('/shot3.png','png')



device.touch(60,200,MonkeyDevice.DOWN_AND_UP)



MonkeyRunner.sleep(1)



device.press('KEYCODE_HOME',MonkeyDevice.DOWN_AND_UP)


注意文件存放的位置应该是你用apktool 反编译之后的文件夹下面

 

apktool d XXXX.APK  文件夹名称


 

你可能感兴趣的:(MonkeyRunner)