APP客戶端窗口接受事件后分發(fā)

1.Java層事件分發(fā)

1.1在 "APP客戶端注冊觸膜/鍵盤事件監(jiān)聽"這篇講了事件注冊的整體流程,但具體接收到事件后APP是怎么處理的?接下來我們重點(diǎn)分析
a.13行addToDisplay調(diào)用到WMS
b.WMS創(chuàng)建好Socketpair后,把他的一端返回到app既mInputChannel
c.app馬上就創(chuàng)建WindowInputEventReceiver來監(jiān)聽mInputChannel既23行
d.如果有Event就會回調(diào)34行onInputEvent函數(shù)
e.經(jīng)過一系列內(nèi)部發(fā)方法最后85行調(diào)用deliverInputEvent,這里面會有責(zé)任鏈模式把所有stage鏈?zhǔn)秸{(diào)度一遍
f.最后調(diào)用到了processPointerEvent函數(shù)的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發(fā)起B(yǎng)inder調(diào)用,wms端肯定也會有對應(yīng)函數(shù)響應(yīng)
            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++接受事件轉(zhuǎn)到j(luò)ava處理

2.1InputEventReceiver 構(gòu)造函數(shù)調(diào)用了nativeInit函數(shù)進(jìn)入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里面創(chuàng)建了與Java層InputEventReceiver對象相對應(yīng)的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關(guān)鍵代碼addFd(fd, 0, events, this, NULL);這一步是把InputChannel(socket)的文件描述符fd添加的主線程的事件處理Looper中做監(jiān)聽,只要有事件就會調(diào)用回調(diào)即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就會回調(diào)到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行會調(diào)用到2.1 11 到15行dispatchInputEvent

b.dispatchInputEvent會調(diào)用到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;
        }
        ...
       //關(guān)鍵代碼回調(diào)到Java層,InputEventReceiver.java的dispatchInputEvent方法中
        env->CallVoidMethod(receiverObj.get(),
                gInputEventReceiverClassInfo.dispatchInputEvent, seq, inputEventObj,
                displayId);
       ...
    }
}

2.總結(jié)

1.App添加窗口時會向wms請求,wms會創(chuàng)建一個socketpair的倆端一個端發(fā)給返回app,一端注冊到InputManagerService中,當(dāng)InputManagerService收到事件的時候就會通過socket夸進(jìn)程通信,傳回app端對應(yīng)窗口

2.APP端會把得到socket文件描述符添加Looper中監(jiān)聽,當(dāng)有事件時候會從c++層反射回調(diào)Java 層 的InputEventReceiver的dispatchInputEvent方法中

3.InputEventReceiver是ViewRoot的內(nèi)部類,DecorView是ViewRoot 的成員變量。dispatchInputEvent經(jīng)過一系列調(diào)用最終取到DecorView,調(diào)用DecorView的dispatchTouchEvent把事件分發(fā)


最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容