一、简介
上一节课:Monkey测试初识:https://blog.youkuaiyun.com/xianyu9264/article/details/107077823
monkey是Android系统提供的一个shell命令(可以说是一个命令行工具)
monkey源码地址
或
二、com.android.commands.monkey包结构
三、monkey启动及运行流程图
从PC启动monkey的流程
monkey的运行过程(源码解析)
四、源码解析
如上面介绍的从PC启动monkey的流程图中所示,当我们在控制台输入adb shell monkey,实际是执行手机中存储在/system/bin目录下的monkey这个脚本,脚本具体内容如下:
# Script to start "monkey" on the device, which has a very rudimentary
# shell.
#
base=/system
export CLASSPATH=$base/framework/monkey.jar
trap "" HUP
exec app_process $base/bin com.android.commands.monkey.Monkey $*
从上面的脚本我们看到,monkey是通过/system/bin/app_process运行/system/framework/monkey.jar执行具体类中的代码,exec 会运行起monkey.jar中的main函数。下面我们来看一下com.android.commands.monkey.Monkey这个类中到底讲了什么:
我们先来看一下Monkey.java类中的main()函数:
/**
* Command-line entry point.
*
* @param args The command-line arguments
*/
public static void main(String[] args) {
// Set the process name showing in "ps" or "top"
Process.setArgV0("com.android.commands.monkey");
Logger.err.println("args: " + Arrays.toString(args));
int resultCode = (new Monkey()).run(args);
System.exit(resultCode);
}
从上面我们可以看到两个信息
1.设置monkey进程,名称为“com.android.commands.monkey”
2.(new Monkey()).run(args),这句话创建一个新的monkey类,并执行run()函数
我们再来看一下run()函数:
/**
* Run the command!
*
* @param args The command-line arguments
* @return Returns a posix-style result code. 0 for no error.
*/
private int run(String[] args) {
// Super-early debugger wait
for (String s : args) {
if ("--wait-dbg".equals(s)) {
Debug.waitForDebugger();
}
}
// Default values for some command-line options
mVerbose = 0;
mCount = 1000;
mSeed = 0;
mThrottle = 0;
// prepare for command-line processing
mArgs = args;
for (String a: args) {
Logger.err.println(" arg: \"" + a + "\"");
}
mNextArg = 0;
// set a positive value, indicating none of the factors is provided yet
for (int i = 0; i < MonkeySourceRandom.FACTORZ_COUNT; i++) {
mFactors[i] = 1.0f;
}
if (!processOptions()) {
return -1;
}
if (!loadPackageLists()) {
return -1;
}
// now set up additional data in preparation for launch
if (mMainCategories.size() == 0) {
mMainCategories.add(Intent.CATEGORY_LAUNCHER);
mMainCategories.add(Intent.CATEGORY_MONKEY);
}
if (mSeed == 0) {
mSeed = System.currentTimeMillis() + System.identityHashCode(this);
}
if (mVerbose > 0) {
Logger.out.println(":Monkey: seed=" + mSeed + " count=" + mCount);
MonkeyUtils.getPackageFilter().dump();
if (mMainCategories.size() != 0) {
Iterator<String> it = mMainCategories.iterator();
while (it.