老李推荐:第6章6节《MonkeyRunner源码剖析》Monkey原理分析-事件源-事件源概览-命令队列
事件源在获得字串命令并把它翻译成对应的MonkeyEvent事件后,会把这些事件排队放入一个由事件源维护的队列,然后其他地方如Monkey类的runMonkeyCycles方法就可以去把队列里面的事件取出来进一步进行处理了。那么这里我们先看下属于MonkeySourceNetwork内部类的命令队列的类图:
图6-6-1 命令队列类图
整个继承关系非常清晰简洁,CommandQueue接口定义了一个enqueueEvent方法来往对队列里面追加事件;实现类CommandQueueImpl实现了该方法并且额外提供了一个getNextEvent方法来从其维护的事件队列queuedEvents中获取事件。
因为这个内部接口和内部类的代码量并不多,所以我们以下列出来一并分析:
481 public static interface CommandQueue {
482 /**
483 * Enqueue an event to be returned later. This allows a
484 * command to return multiple events. Commands using the
485 * command queue still have to return a valid event from their
486 * translateCommand method. The returned command will be
487 * executed before anything put into the queue.
488 *
489 * @param e the event to be enqueued.
490 */
491 public void enqueueEvent(MonkeyEvent e);
492 };
493
494 // Queue of Events to be processed. This allows commands to push
495 // multiple events into the queue to be processed.
496 private static class CommandQueueImpl implements CommandQueue{
497 private final Queue<MonkeyEvent> queuedEvents = new LinkedList<MonkeyEvent>();
498
499 public void enqueueEvent(MonkeyEvent e) {
500 queuedEvents.offer(e);
501 }
502
503 /**
504 * Get the next queued event to excecute.
505 *
506 * @return the next event, or null if there aren't any more.
507 */
508 public MonkeyEvent getNextQueuedEvent() {
509 return queuedEvents.poll();
510 }
511 };
代码6-6-1 CommandQueue和CommandQueueImpl
- 497行: 实例化了一个由MonkeyEvent组成的事件队列queuedEvents
- 499-501: 调用队列Queue的offer方法往事件队列增加一个事件
- 508-510: 调用队列Queue的poll方法从事件队列中取出一个事件并返回