APP客户端窗口接受事件后分发

1.Java层事件分发

1.1在 "APP客户端注册触膜/键盘事件监听"这篇讲了事件注册的整体流程,但具体接收到事件后APP是怎么处理的?接下来我们重点分析
a.13行addToDisplay调用到WMS
b.WMS创建好Socketpair后,把他的一端返回到app既mInputChannel
c.app马上就创建WindowInputEventReceiver来监听mInputChannel既23行
d.如果有Event就会回调34行onInputEvent函数
e.经过一系列内部发方法最后85行调用deliverInputEvent,这里面会有责任链模式把所有stage链式调度一遍
f.最后调用到了processPointerEvent函数的77行,既Docerview的dispatchPointerEvent

ViewRootImpl.java 
public final class ViewRootImpl implements ViewParent,
        View.AttachInfo.Callbacks, ThreadedRenderer.DrawCallbacks {
      public void setView(View view, WindowManager.LayoutParams attrs, View panelParentView) {
            ...
            requestLayout();
            if ((mWindowAttributes.inputFeatures
                    & WindowManager.LayoutParams.INPUT_FEATURE_NO_INPUT_CHANNEL) == 0) {
                mInputChannel = new InputChannel();
            }
            ...
              //addToDisplay发起Binder调用,wms端肯定也会有对应函数响应
            res = mWindowSession.addToDisplay(mWindow, mSeq, mWindowAttributes,
                    getHostVisibility(), mDisplay.getDisplayId(),
                    mAttachInfo.mContentInsets, mAttachInfo.mStableInsets,
                    mAttachInfo.mOutsets, mInputChannel);
            ...
            if (mInputChannel != null) {
                if (mInputQueueCallback != null) {
                    mInputQueue = new InputQueue();
                    mInputQueueCallback.onInputQueueCreated(mInputQueue);
                }
                mInputEventReceiver = new WindowInputEventReceiver(mInputChannel,
                        Looper.myLooper());
            }
           ...
   }
   final class WindowInputEventReceiver extends InputEventReceiver {
        public WindowInputEventReceiver(InputChannel inputChannel, Looper looper) {
            super(inputChannel, looper);
        }
        @Override
        public void onInputEvent(InputEvent event, int displayId) {
            enqueueInputEvent(event, this, 0, true);
        }
     ...
    }
          
   void enqueueInputEvent(InputEvent event,
            InputEventReceiver receiver, int flags, boolean processImmediately) {
                        ...
            doProcessInputEvents();
    }
          
     void doProcessInputEvents() {
          ...
          deliverInputEvent(q);
      }
    }
          
    private void deliverInputEvent(QueuedInputEvent q) {
          ...
            stage.deliver(q);
          ...
     }
          
     abstract class InputStage {
         ...
          public final void deliver(QueuedInputEvent q) {
               ...
               apply(q, onProcess(q));
          }
       ...
     }

        final class ViewPostImeInputStage extends InputStage {
      protected int onProcess(QueuedInputEvent q) {
             ...
             return processPointerEvent(q);
             ...  
      }
      private int processPointerEvent(QueuedInputEvent q) {
                  final MotionEvent event = (MotionEvent)q.mEvent;
                  mAttachInfo.mUnbufferedDispatchRequested = false;
                  mAttachInfo.mHandlingPointerEvent = true;
                 //看到了曙光mView就是Docerview
                  boolean handled = mView.dispatchPointerEvent(event);
                  maybeUpdatePointerIcon(event);
                  maybeUpdateTooltip(event);
                  mAttachInfo.mHandlingPointerEvent = false;
                  if (mAttachInfo.mUnbufferedDispatchRequested && !mUnbufferedInputDispatch) {
                      mUnbufferedInputDispatch = true;
                      if (mConsumeBatchedInputScheduled) {
                          scheduleConsumeBatchedInputImmediately();
                      }
                  }
                  return handled ? FINISH_HANDLED : FORWARD;
              }
        }
}
View.java
public class View implements Drawable.Callback, KeyEvent.Callback,AccessibilityEventSource{
      ...
      public final boolean dispatchPointerEvent(MotionEvent event) {
          if (event.isTouchEvent()) {
             //终于到了dispatchTouchEvent
              return dispatchTouchEvent(event);
          } else {
              return dispatchGenericMotionEvent(event);
          }
      }
     
     public boolean dispatchTouchEvent(MotionEvent event) {
       ...
        if (onFilterTouchEventForSecurity(event)) {
            ...
            if (!result && onTouchEvent(event)) {
                result = true;
            }
        }
      ...
        return result;
    }
}

2.C++接受事件转到java处理

2.1InputEventReceiver 构造函数调用了nativeInit函数进入native层

InputEventReceiver.java
public abstract class InputEventReceiver {
 ...
  public InputEventReceiver(InputChannel inputChannel, Looper looper) {
      mInputChannel = inputChannel;
      mMessageQueue = looper.getQueue();
      mReceiverPtr = nativeInit(new WeakReference<InputEventReceiver>(this),
              inputChannel, mMessageQueue);
  }
  
  private void dispatchInputEvent(int seq, InputEvent event, int displayId) {
        mSeqMap.put(event.getSequenceNumber(), seq);
        onInputEvent(event, displayId);
    }
  ...
}

2.2Native里面创建了与Java层InputEventReceiver对象相对应的NativeInputEventReceiver,这是Android一惯的的套路

android_view_InputEventReceiver.cpp
static jlong nativeInit(JNIEnv* env, jclass clazz, jobject receiverWeak,
        jobject inputChannelObj, jobject messageQueueObj) {
    sp<InputChannel> inputChannel = android_view_InputChannel_getInputChannel(env,
            inputChannelObj);
    ...
    sp<MessageQueue> messageQueue = android_os_MessageQueue_getMessageQueue(env, messageQueueObj);
    ...
    sp<NativeInputEventReceiver> receiver = new NativeInputEventReceiver(env,
            receiverWeak, inputChannel, messageQueue);
    status_t status = receiver->initialize();
    ...
}

2.3关键代码addFd(fd, 0, events, this, NULL);这一步是把InputChannel(socket)的文件描述符fd添加的主线程的事件处理Looper中做监听,只要有事件就会调用回调即this,

android_view_InputEventReceiver.cpp
NativeInputEventReceiver::NativeInputEventReceiver(JNIEnv* env,
        jobject receiverWeak, const sp<InputChannel>& inputChannel,
        const sp<MessageQueue>& messageQueue) :
        mReceiverWeakGlobal(env->NewGlobalRef(receiverWeak)),
        mInputConsumer(inputChannel), mMessageQueue(messageQueue),
        mBatchedInputEventPending(false), mFdEvents(0) {
}
status_t NativeInputEventReceiver::initialize() {
    setFdEvents(ALOOPER_EVENT_INPUT);
    return OK;
}
void NativeInputEventReceiver::setFdEvents(int events) {
    if (mFdEvents != events) {
        mFdEvents = events;
        int fd = mInputConsumer.getChannel()->getFd();
        if (events) {
          //这里的this就会回调到1.6的consumeEvents
            mMessageQueue->getLooper()->addFd(fd, 0, events, this, NULL);
        } else {
            mMessageQueue->getLooper()->removeFd(fd);
        }
    }
}
int NativeInputEventReceiver::handleEvent(int receiveFd, int events, void* data) {
   ...
    if (events & ALOOPER_EVENT_INPUT) {
        JNIEnv* env = AndroidRuntime::getJNIEnv();
        status_t status = consumeEvents(env, false /*consumeBatches*/, -1, NULL);
        mMessageQueue->raiseAndClearException(env, "handleReceiveCallback");
        return status == OK || status == NO_MEMORY ? 1 : 0;
    }
   ...
}

2.4读取事件并回到Java

a.第37行会调用到2.1 11 到15行dispatchInputEvent

b.dispatchInputEvent会调用到1.1 31到35行onInputEvent回到了1.1流程直到view的dispatchPointerEvent

status_t NativeInputEventReceiver::consumeEvents(JNIEnv* env,
        bool consumeBatches, nsecs_t frameTime, bool* outConsumedBatch) {
    ...
    for (;;) {
        uint32_t seq;
        InputEvent* inputEvent;
        int32_t displayId;
        //从文件描述符读取事件赋值给inputEvent
        status_t status = mInputConsumer.consume(&mInputEventFactory,
                consumeBatches, frameTime, &seq, &inputEvent, &displayId);
        ...
        jobject inputEventObj;
        switch (inputEvent->getType()) {
        case AINPUT_EVENT_TYPE_KEY:
        ...
            inputEventObj = android_view_KeyEvent_fromNative(env,
                    static_cast<KeyEvent*>(inputEvent));
            break;

        case AINPUT_EVENT_TYPE_MOTION: {
         ...
           //下面只是拷贝一份事件无他
            MotionEvent* motionEvent = static_cast<MotionEvent*>(inputEvent);
            if ((motionEvent->getAction() & AMOTION_EVENT_ACTION_MOVE) && outConsumedBatch) {
                *outConsumedBatch = true;
            }
            inputEventObj = android_view_MotionEvent_obtainAsCopy(env, motionEvent);
            break;
        }

        default:
            assert(false); // InputConsumer should prevent this from ever happening
            inputEventObj = NULL;
        }
        ...
       //关键代码回调到Java层,InputEventReceiver.java的dispatchInputEvent方法中
        env->CallVoidMethod(receiverObj.get(),
                gInputEventReceiverClassInfo.dispatchInputEvent, seq, inputEventObj,
                displayId);
       ...
    }
}

2.总结

1.App添加窗口时会向wms请求,wms会创建一个socketpair的俩端一个端发给返回app,一端注册到InputManagerService中,当InputManagerService收到事件的时候就会通过socket夸进程通信,传回app端对应窗口

2.APP端会把得到socket文件描述符添加Looper中监听,当有事件时候会从c++层反射回调Java 层 的InputEventReceiver的dispatchInputEvent方法中

3.InputEventReceiver是ViewRoot的内部类,DecorView是ViewRoot 的成员变量。dispatchInputEvent经过一系列调用最终取到DecorView,调用DecorView的dispatchTouchEvent把事件分发


最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 217,509评论 6 504
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 92,806评论 3 394
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 163,875评论 0 354
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 58,441评论 1 293
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 67,488评论 6 392
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 51,365评论 1 302
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 40,190评论 3 418
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 39,062评论 0 276
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 45,500评论 1 314
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 37,706评论 3 335
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 39,834评论 1 347
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 35,559评论 5 345
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 41,167评论 3 328
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 31,779评论 0 22
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 32,912评论 1 269
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 47,958评论 2 370
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 44,779评论 2 354

推荐阅读更多精彩内容