天天看点

第5章7节《MonkeyRunner源码剖析》Monkey原理分析-启动运行: 循环获取并执行事件

老李推荐:第5章7节《MonkeyRunner源码剖析》Monkey原理分析-启动运行: 循环获取并执行事件 - runMonkeyCycles

Monkey启动之后需要在整个MonkeyRunner的测试生命周期中提供服务,也就是说,一旦我们调用monkeyrunner命令来执行指定的测试脚本的时候,只要monkeyrunner还没有退出,那么Monkey就会一直提供服务,一直监听获取并处理从MonkeyRunner测试脚本发送过来的相应的命令。那么要实现这种一直监听的处理我们很自然就想到需要用一个循环来处理了。其实Monkey也不例外,我们往下会分析它是怎么通过一个循环来从事件源获取一个命令事件,然后调用该事件的注入方法进行事件注入的。当然,因为我们现在还没有分析学习到事件和事件源,所以本小节你只会看到Monkey是怎么通过它们提供的接口方法来获取事件和注入事件的,在下一章你就会看到整个事件究竟是怎么处理的了。

下面我们继续分析Monkey的run方法调用的最后一个重要方法,runMonkeyCycles。

代码5-7-1 Monkey - run调用runMonkeyCycles
    /**
      * 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) {         mCount = 1000;
    ... //省略初始化事件源等代码         try {             crashedAtCycle = runMonkeyCycles();         }
    ...
}           

当事件源初始化好后run方法就会去调用runMonkeyCycles方法不断的从命令队列中读取事件来执行。

代码5-7-2 Monkey - runMonkeyCycles
    /**
      * Run mCount cycles and see if we hit any crashers.
      * <p>
      * TODO: Meta state on keys
      *
      * @return Returns the last cycle which executed. If the value == mCount, no
      *         errors detected.
      */     private int runMonkeyCycles() {         int eventCounter = 0;         int cycleCounter = 0;
        ...         // TO DO : The count should apply to each of the script file.         while (!systemCrashed && cycleCounter < mCount) {
            ...             MonkeyEvent ev = mEventSource.getNextEvent();             if (ev != null) {                 int injectCode = ev.injectEvent(mWm, 
                                        mAm, mVerbose);
            ...                 // Don't count throttling as an event.                 if (!(ev instanceof MonkeyThrottleEvent)) {                     eventCounter++;                     if (mCountEvents) {                         cycleCounter++;                     }                 }
             }
    ...
}           

这段代码做的主要事情就是通过931行的一个while循环去不停调用事件源提供的方法getNextEvent来获得一个事件,然后调用事件的injectEvent方法来注入事件,比如注入按键事件来模拟用户按下某个按键。往下我们对这段代码做相应的分析:

  • 第931行: 这里是一个while循环用来不停的从事件队列中读取事件。如果执行的事件没有导致系统崩溃,且当前循环次数少于mCount这个变量的话,整个循环都会继续。这里需要注意mCount这个成员变量,如果用户在执行monkey命令的时候没有指定”COUNT”这个运行次数的话,将会默认在Monkey的run这个方法中初始化成1000,请看” 代码5-9-1 Monkey - run调用runMonkeyCycles方法”第440行:” 440 this.mCount = 1000;”。