Monkey源码分析之事件源

本文详细解读了Monkey事件源处理流程,包括事件队列维护、事件翻译、事件源获取及事件执行的关键步骤,提供了从命令到事件执行的全面理解。

上一篇文章《Monkey源码分析之运行流程》给出了monkey运行的整个流程,让我们有一个概貌,那么往后的文章我们会尝试进一步的阐述相关的一些知识点。

这里先把整个monkey类的结构图给出来供大家参考,该图源自网上(我自己的backbook pro上没有安装OmniGraffle工具,55美金,不舍得,所以直接贴网上的)



图中有几点需要注意下的:

  • MonkeyEventScript应该是MonkeySourceScript
  • MonkeyEventRandom应该是MonkeySourceRandom
  • 这里没有列出其他源,比如我们今天描述的重点MonkeySourceNetwork,因为它不是由MonkeyEventQueque这个类维护的,但其维护的事件队列和MonkeyEventQueque一样都是继承于LinkedList的,所以大同小异

本文我们重点是以处理来来自网络sokcet也就是monkeyrunner的命令为例子来阐述事件源是怎么处理的,其他的源大同小异。

1. 事件队列维护者CommandQueque

在开始之前我们需要先去了解几个基础类,这样子我们才方便分析。

我们在获取了事件源之后,会把这些事件排队放入一个队列,然后其他地方就可以去把队列里面的事件取出来进一步进行处理了。那么这里我们先看下维护这个事件队列的相应代码:

[java]  view plain copy
  1. public static interface CommandQueue {  
  2.     /** 
  3.      * Enqueue an event to be returned later.  This allows a 
  4.      * command to return multiple events.  Commands using the 
  5.      * command queue still have to return a valid event from their 
  6.      * translateCommand method.  The returned command will be 
  7.      * executed before anything put into the queue. 
  8.      * 
  9.      * @param e the event to be enqueued. 
  10.      */  
  11.     public void enqueueEvent(MonkeyEvent e);  
  12. };  
  13.   
  14. // Queue of Events to be processed.  This allows commands to push  
  15. // multiple events into the queue to be processed.  
  16. private static class CommandQueueImpl implements CommandQueue{  
  17.     private final Queue<MonkeyEvent> queuedEvents = new LinkedList<MonkeyEvent>();  
  18.   
  19.     public void enqueueEvent(MonkeyEvent e) {  
  20.         queuedEvents.offer(e);  
  21.     }  
  22.   
  23.     /** 
  24.      * Get the next queued event to excecute. 
  25.      * 
  26.      * @return the next event, or null if there aren't any more. 
  27.      */  
  28.     public MonkeyEvent getNextQueuedEvent() {  
  29.         return queuedEvents.poll();  
  30.     }  
  31. };  

接口CommandQueue只定义个了一个方法enqueueEvent,由实现类CommandQueueImpl来实现,而实现类维护了一个MonkeyEvent类型的由LinkedList实现的队列quequeEvents,然后实现了两个方法来分别往这个队列里面放和取事件。挺简单的实现,这里主要是要提醒大家queueEvents这个队列的重要性。这里要注意的是MonkeyEventScript和monkeyEventRandom这两个事件源维护队列的类稍微有些不一样,用的是MonkeyEventQueue这个类,但是其实这个类也是继承自上面描述的LinkedList的,所以原理是一样的。

最后创建和维护一个CommandQueueImple这个实现类的一个实例commandQueque来转被对里面的quequeEvents进行管理。

[java]  view plain copy
  1. private final CommandQueueImpl commandQueue = new CommandQueueImpl();  


2. 事件翻译员MonkeyCommand

下一个我们需要了解的基础内部类就是MonkeCommand。从数据源过来的命令都是一串字符串,我们需要把它转换成对应的monkey事件并存入到我们上面提到的由CommandQueque维护的事件队列quequeEvents里面。首先我们看下MonkeyCommand这个接口:

[java]  view plain copy
  1. /** 
  2.  * Interface that MonkeyCommands must implement. 
  3.  */  
  4. public interface MonkeyCommand {  
  5.     /** 
  6.      * Translate the command line into a sequence of MonkeyEvents. 
  7.      * 
  8.      * @param command the command line. 
  9.      * @param queue the command queue. 
  10.      * @return MonkeyCommandReturn indicating what happened. 
  11.      */  
  12.     MonkeyCommandReturn translateCommand(List<String> command, CommandQueue queue);  
  13. }  

它只定义了一个实现类需要实现的方法translateCommand,从它的描述和接受的的参数可以知道,这个方法要做的事情就是把从事件源接受到的字符串命令转换成上面说的CommandQueue类型维护的那个eventQueues。以monkeyrunner发过来的press这个命令为例子,传过来给monkey的字串是"press KEY_COKDE"(请查看《MonkeyRunner源码分析之与Android设备通讯方式》)

针对每一个命令都会有一个对应的MonkeyCommand的实现类来做真正的字串到事件的翻译工作,以刚才提到的press这个命令为例子,我们看下它的实现代码:

[java]  view plain copy
  1. /** 
  2.  * Command to "press" a buttons (Sends an up and down key event.) 
  3.  */  
  4. private static class PressCommand implements MonkeyCommand {  
  5.     // press keycode  
  6.     public MonkeyCommandReturn translateCommand(List<String> command,  
  7.                                                 CommandQueue queue) {  
  8.         if (command.size() == 2) {  
  9.             int keyCode = getKeyCode(command.get(1));  
  10.             if (keyCode < 0) {  
  11.                 // Ok, you gave us something bad.  
  12.                 Log.e(TAG, "Can't find keyname: " + command.get(1));  
  13.                 return EARG;  
  14.             }  
  15.   
  16.             queue.enqueueEvent(new MonkeyKeyEvent(KeyEvent.ACTION_DOWN, keyCode));  
  17.             queue.enqueueEvent(new MonkeyKeyEvent(KeyEvent.ACTION_UP, keyCode));  
  18.             return OK;  
  19.   
  20.         }  
  21.         return EARG;  
  22.     }  
  23. }  
以monkeyrunner过来的'press KEY_CODE'为例分析这段代码:

  • 从字串中得到第1个参数,也就是key_code
  • 判断key_code是否有效
  • 建立按下按键的MonkeyKeyEvent事件并存入到CommandQueque维护的quequeEvents
  • 建立弹起按键的MonkeyKeyEvent事件并存入到CommandQueque维护的quequeEvents(press这个动作会出发按下和弹起按键两个动作)
命令字串和对应的MonkeyCommand实现类的对应关系会由MonkeySourceNetwork类的COMMAND_MAP这个私有静态成员来维护,这里只是分析了"press"这个命令,其他的大家有兴趣就自行分析,原理是一致的。

[java]  view plain copy
  1. private static final Map<String, MonkeyCommand> COMMAND_MAP = new HashMap<String, MonkeyCommand>();  
  2.   
  3.     static {  
  4.         // Add in all the commands we support  
  5.         COMMAND_MAP.put("flip"new FlipCommand());  
  6.         COMMAND_MAP.put("touch"new TouchCommand());  
  7.         COMMAND_MAP.put("trackball"new TrackballCommand());  
  8.         COMMAND_MAP.put("key"new KeyCommand());  
  9.         COMMAND_MAP.put("sleep"new SleepCommand());  
  10.         COMMAND_MAP.put("wake"new WakeCommand());  
  11.         COMMAND_MAP.put("tap"new TapCommand());  
  12.         COMMAND_MAP.put("press"new PressCommand());  
  13.         COMMAND_MAP.put("type"new TypeCommand());  
  14.         COMMAND_MAP.put("listvar"new MonkeySourceNetworkVars.ListVarCommand());  
  15.         COMMAND_MAP.put("getvar"new MonkeySourceNetworkVars.GetVarCommand());  
  16.         COMMAND_MAP.put("listviews"new MonkeySourceNetworkViews.ListViewsCommand());  
  17.         COMMAND_MAP.put("queryview"new MonkeySourceNetworkViews.QueryViewCommand());  
  18.         COMMAND_MAP.put("getrootview"new MonkeySourceNetworkViews.GetRootViewCommand());  
  19.         COMMAND_MAP.put("getviewswithtext",  
  20.                         new MonkeySourceNetworkViews.GetViewsWithTextCommand());  
  21.         COMMAND_MAP.put("deferreturn"new DeferReturnCommand());  
  22.     }  

3. 事件源获取者之getNextEvent

终于到了如何获取事件的分析了,我们继续以MonkeySourceNetwork这个处理monkeyrunner过来的网络命令为例子,看下它是如何处理monkeyrunner过来的命令的。我们先看下它实现的接口类MonkeyEventSource

[java]  view plain copy
  1. /** 
  2.  * event source interface 
  3.  */  
  4. public interface MonkeyEventSource {  
  5.     /** 
  6.      * @return the next monkey event from the source 
  7.      */  
  8.     public MonkeyEvent getNextEvent();  
  9.   
  10.     /** 
  11.      * set verbose to allow different level of log 
  12.      * 
  13.      * @param verbose output mode? 1= verbose, 2=very verbose 
  14.      */  
  15.     public void setVerbose(int verbose);  
  16.   
  17.     /** 
  18.      * check whether precondition is satisfied 
  19.      * 
  20.      * @return false if something fails, e.g. factor failure in random source or 
  21.      *         file can not open from script source etc 
  22.      */  
  23.     public boolean validate();  
  24. }  

这里我最关心的就是getNextEvent这个接口,因为就是它来从socket获得我们monkeyrunner过来的命令,然后通过上面描述的MonkeyCommand的实现类来把命令翻译成最上面的CommandQueque维护的quequeEvents队列的。往下我们会看它是怎么做到的,这里我们先看下接口实现类MonkeySourceNetwork的构造函数:

[java]  view plain copy
  1. public MonkeySourceNetwork(int port) throws IOException {  
  2.     // Only bind this to local host.  This means that you can only  
  3.     // talk to the monkey locally, or though adb port forwarding.  
  4.     serverSocket = new ServerSocket(port,  
  5.                                     0// default backlog  
  6.                                     InetAddress.getLocalHost());  
  7. }  
所做的事情就是通过指定的端口实例化一个ServerSocket,这里要注意它绑定的只是本地主机地址,意思是说只有本地的socket连接或者通过端口转发连过来的adb端口(也就是我们这篇文章关注的monkeyrunner启动的那个adb)才会被接受。

这里只是实例化了一个socket,现在为止还没有真正启动起来的,也就是说还没有开始真正的启动对指定端口的监听的。真正开始监听是startServer这个方法触发的:

[java]  view plain copy
  1. /** 
  2.  * Start a network server listening on the specified port.  The 
  3.  * network protocol is a line oriented protocol, where each line 
  4.  * is a different command that can be run. 
  5.  * 
  6.  * @param port the port to listen on 
  7.  */  
  8. private void startServer() throws IOException {  
  9.     clientSocket = serverSocket.accept();  
  10.     // At this point, we have a client connected.  
  11.     // Attach the accessibility listeners so that we can start receiving  
  12.     // view events. Do this before wake so we can catch the wake event  
  13.     // if possible.  
  14.     MonkeySourceNetworkViews.setup();  
  15.     // Wake the device up in preparation for doing some commands.  
  16.     wake();  
  17.   
  18.     input = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));  
  19.     // auto-flush  
  20.     output = new PrintWriter(clientSocket.getOutputStream(), true);  
  21. }  
这里除了开始监听端口之外,还如monkeyrunner对端口读写的情况一样,维护和实例化了input和output这两个成员变量来专门对端口数据进行操作。
那么这个startServer开始监听数据的方法又是由谁调用的呢?这里终于就来到了我们这一章节,也是本文的核心getNextEvent了
[java]  view plain copy
  1. public MonkeyEvent getNextEvent() {  
  2.     if (!started) {  
  3.         try {  
  4.             startServer();  
  5.         } catch (IOException e) {  
  6.             Log.e(TAG, "Got IOException from server", e);  
  7.             return null;  
  8.         }  
  9.         started = true;  
  10.     }  
  11.   
  12.     // Now, get the next command.  This call may block, but that's OK  
  13.     try {  
  14.         while (true) {  
  15.             // Check to see if we have any events queued up.  If  
  16.             // we do, use those until we have no more.  Then get  
  17.             // more input from the user.  
  18.             MonkeyEvent queuedEvent = commandQueue.getNextQueuedEvent();  
  19.             if (queuedEvent != null) {  
  20.                 // dispatch the event  
  21.                 return queuedEvent;  
  22.             }  
  23.   
  24.             // Check to see if we have any returns that have been deferred. If so, now that  
  25.             // we've run the queued commands, wait for the given event to happen (or the timeout  
  26.             // to be reached), and handle the deferred MonkeyCommandReturn.  
  27.             if (deferredReturn != null) {  
  28.                 Log.d(TAG, "Waiting for event");  
  29.                 MonkeyCommandReturn ret = deferredReturn.waitForEvent();  
  30.                 deferredReturn = null;  
  31.                 handleReturn(ret);  
  32.             }  
  33.   
  34.             String command = input.readLine();  
  35.             if (command == null) {  
  36.                 Log.d(TAG, "Connection dropped.");  
  37.                 // Treat this exactly the same as if the user had  
  38.                 // ended the session cleanly with a done commant.  
  39.                 command = DONE;  
  40.             }  
  41.   
  42.             if (DONE.equals(command)) {  
  43.                 // stop the server so it can accept new connections  
  44.                 try {  
  45.                     stopServer();  
  46.                 } catch (IOException e) {  
  47.                     Log.e(TAG, "Got IOException shutting down!", e);  
  48.                     return null;  
  49.                 }  
  50.                 // return a noop event so we keep executing the main  
  51.                 // loop  
  52.                 return new MonkeyNoopEvent();  
  53.             }  
  54.   
  55.             // Do quit checking here  
  56.             if (QUIT.equals(command)) {  
  57.                 // then we're done  
  58.                 Log.d(TAG, "Quit requested");  
  59.                 // let the host know the command ran OK  
  60.                 returnOk();  
  61.                 return null;  
  62.             }  
  63.   
  64.             // Do comment checking here.  Comments aren't a  
  65.             // command, so we don't echo anything back to the  
  66.             // user.  
  67.             if (command.startsWith("#")) {  
  68.                 // keep going  
  69.                 continue;  
  70.             }  
  71.   
  72.             // Translate the command line.  This will handle returning error/ok to the user  
  73.             translateCommand(command);  
  74.         }  
  75.     } catch (IOException e) {  
  76.         Log.e(TAG, "Exception: ", e);  
  77.         return null;  
  78.     }  
  79. }  
有了以上介绍的那些背景知识,这段代码的理解就不会太费力了,我这里大概描述下:

  • 启动socket端口监听monkeyrunner过来的连接和数据
  • 进入无限循环
    • 调用最上面描述的commandQueque这个事件队列维护者实例来尝试来从队列获得一个事件
    • 如果队列由事件的话就立刻返回给上一篇文章《MonkeyRunner源码分析之启动》描述的runMonkeyCles那个方法取调用执行
    • 如果队列没有事件的话,调用上面描述的socket读写变量input来获得socket中monkeyrunner发过来的一行数据(也就是一个命令字串)
    • 调用translateCommand这个私有方法来针对不同的命令调用不同的MonkeyCommand实现类接口的translateCommand把字串命令翻译成对应的事件并放到命令队列里面(这个命令上面还没有描述,往下我会分析下)
    • 如果确实没有命令了或者收到信号要退出了等情况下就跳出循环,否则回到循环开始继续以上步骤
好,我们还是看看刚才那个translateCommand的私有方法究竟是怎么调用到不同命令的translateCommand接口的:
[java]  view plain copy
  1. /** 
  2.  * Translate the given command line into a MonkeyEvent. 
  3.  * 
  4.  * @param commandLine the full command line given. 
  5.  */  
  6. private void translateCommand(String commandLine) {  
  7.     Log.d(TAG, "translateCommand: " + commandLine);  
  8.     List<String> parts = commandLineSplit(commandLine);  
  9.     if (parts.size() > 0) {  
  10.         MonkeyCommand command = COMMAND_MAP.get(parts.get(0));  
  11.         if (command != null) {  
  12.             MonkeyCommandReturn ret = command.translateCommand(parts, commandQueue);  
  13.             handleReturn(ret);  
  14.         }  
  15.     }  
  16. }  
很简单,就是获取monkeyunner进来的命令字串列表的的第一个值,然后通过上面的COMMAND_MAP把字串转换成对应的MonkeyCommand实现类,然后调用其tranlsateCommand把该字串命令翻译成对应的MonkeyEvent并存储到事件队列。
比如monkeyrunner过来的字串转换成队列是[‘press','KEY_CODE'],获得第一个列表成员是press,那么COMMAND_MAP对应于"press"字串这个key的MonkeyCommand就是:
[java]  view plain copy
  1. COMMAND_MAP.put("press"new PressCommand());  
所以调用的就是PressCommand这个MonkeyCommand接口实现类的translateCommand方法来把press这个命令转换成对应的MonkeyKeyEvent了。

4.总结

最后我们结合上一章《 Monkey源码分析之运行流程》把整个获取事件源然后执行该事件的过程整理下:
  • Monkey启动开始调用run方法
  • ran方法根据输入的参数实例化指定的事件源,比如我们这里的MonkeySourceNetwork
  • Monkey类中的runMonkeyCyles这个方法开始循环取事件执行
    • 调用Monkey类维护的mEventSource的getNextEvent方法来获取一条事件,在本文实例中就是上面表述的MonkeySourceNetwork实例的getNextEvent方法
      • getNextEvent方法从CommandQueueImpl实例commandQueque所维护的quequeEvents里面读取一条事件
      • 如果事件存在则返回
      • getNextEvent方法启动事件源读取监听,本文实例中就是上面的startServer方法来监听monkeyrunner过来的socket连接和命令数据
      • getNextEvent方法从事件源读取一个命令
      • getNextEvent方法通过调用对应的的MonkeyCommand接口实现类的translateCommand方法把字串命令翻译成对应的monkey事件然后保存到commandQueque维护的quequeEvents队列
    • 执行返回event的injectEvent方法
好,事件源的分析就到此为止了,下一篇文章准备描述Monkey的Event,看它是如何执行这些事件的。

评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值