Android事件处理流程分析

本文主要基于Android4.4源码的事件处理流程进行了分析。并参照了如下文章并引用了部分资源。

http://blog.csdn.net/windskier/article/details/6966264

http://www.eoeandroid.com/home.php?mod=space&uid=10407&do=blog&id=5070

http://blog.sina.com.cn/s/blog_89f592f50101394l.html

http://blog.csdn.net/luoshengyang/article/details/6882903


事件处理流程
1)InputManager负责读取事件并把事件送到frameworks的java层
2)WindowManagerService里会有一个InputMonitor类来监听事件变化并做相应的分发处理。
3)在WindowManagerService会有一个WindowManagerPolicy来做消息拦截处理。
4)WindowManagerService会把消息发给最上面运行的窗口接收

1. Input子系统的初始化过程

系统开机的时候,SystemServer会启动InputManagerSercice和WindowManagerService。

SystemServer.java

[html]  view plain copy 在CODE上查看代码片 派生到我的代码片
  1. Slog.i(TAG, "Input Manager");  
  2. inputManager = new InputManagerService(context, wmHandler);  
  3.   
  4. Slog.i(TAG, "Window Manager");  
  5. wm = WindowManagerService.main(context, power, display, inputManager,  
  6.         wmHandler, factoryTest != SystemServer.FACTORY_TEST_LOW_LEVEL,  
  7.         !firstBoot, onlyCore);  
  8. ServiceManager.addService(Context.WINDOW_SERVICE, wm);  
  9. ServiceManager.addService(Context.INPUT_SERVICE, inputManager);  
  10.   
  11. ActivityManagerService.self().setWindowManager(wm);  
  12.   
  13. inputManager.setWindowManagerCallbacks(wm.getInputMonitor());  
  14. inputManager.start();  
上述过程主要做了如下事情:

(1)创建了InputManagerSercice和WindowManagerService的实例

(2)将InputManagerServcie的引用传递给WindowManagerService

(3)在InputManagerSercice中设定了WindowManagerService的回调函数

          —— 将WindowManagerService的成员InputMonitor赋值给InputManagerSercice的成员InputManagerSercice的成员mWindowManagerCallbacks

(4)启动InputManagerSercice

1.1 创建InputManagerSercice

创建InputManagerSercice时传递的参数有一个wmHander,这个handler是运行在以下Thread中的

[html]  view plain copy 在CODE上查看代码片 派生到我的代码片
  1. // Create a handler thread just for the window manager to enjoy.  
  2. HandlerThread wmHandlerThread = new HandlerThread("WindowManager");  
  3. wmHandlerThread.start();  

创建InputManagerSercice的主要代码如下:

[html]  view plain copy 在CODE上查看代码片 派生到我的代码片
  1. public InputManagerService(Context context, Handler handler) {  
  2.     this.mContext = context;  
  3.     this.mHandler = new InputManagerHandler(handler.getLooper());  
  4.   
  5.     mUseDevInputEventForAudioJack =  
  6.             context.getResources().getBoolean(R.bool.config_useDevInputEventForAudioJack);  
  7.     Slog.i(TAG, "Initializing input manager, mUseDevInputEventForAudioJack="  
  8.             + mUseDevInputEventForAudioJack);  
  9.     mPtr = nativeInit(this, mContext, mHandler.getLooper().getQueue());  
  10.   
  11.     mAppRSMouseMode = MOUSE_MODE_DEFAULT;  
  12.     mAppStylusFingerOnlyMode = true;  
  13.     mCurrentStylusFingerOnlyMode = true;  
  14.     mCurrentTouchLocked = false;  
  15.   
  16.     mUserSetup = false;  
  17. }  

InputManagerService也有一个成员mHander,它与wmHandler运行在同一个Looper中。

最重要的是nativeInit,实现如下:

com_android_server_Input_InputManagerService.cpp

[html]  view plain copy 在CODE上查看代码片 派生到我的代码片
  1. static jint nativeInit(JNIEnv* env, jclass clazz,  
  2.         jobject serviceObj, jobject contextObj, jobject messageQueueObj) {  
  3.     sp<MessageQueue> messageQueue = android_os_MessageQueue_getMessageQueue(env, messageQueueObj);  
  4.     if (messageQueue == NULL) {  
  5.         jniThrowRuntimeException(env, "MessageQueue is not initialized.");  
  6.         return 0;  
  7.     }  
  8.   
  9.     NativeInputManager* im = new NativeInputManager(contextObj, serviceObj,  
  10.             messageQueue->getLooper());  
  11.     im->incStrong(0);  
  12.     return reinterpret_cast<jint>(im);  
  13. }  

这里的MessageQueue和Looper都是wmHandler运行的Thread中的。

在native创建了NativeInputManager,并把指针返回给Java层。

NativeInputManager构造的时候,会创建了一个EventHub实例,并且把这个EventHub作为参数来创建InputManager对象。注意,这里的InputManager类是定义在C++层的,和前面在Java层的InputManager不一样,不过它们是对应关系。EventHub类是真正执行监控键盘事件操作的地方。

[html]  view plain copy 在CODE上查看代码片 派生到我的代码片
  1. NativeInputManager::NativeInputManager(jobject contextObj,  
  2.         jobject serviceObj, const sp<Looper>& looper) :  
  3.         mLooper(looper) {  
  4.     JNIEnv* env = jniEnv();  
  5.   
  6.     mContextObj = env->NewGlobalRef(contextObj);  
  7.     mServiceObj = env->NewGlobalRef(serviceObj);  
  8.   
  9.     {  
  10.         AutoMutex _l(mLock);  
  11.         mLocked.systemUiVisibility = ASYSTEM_UI_VISIBILITY_STATUS_BAR_VISIBLE;  
  12.         mLocked.pointerSpeed = 0;  
  13.         mLocked.mouseMode = 0;  
  14.         mLocked.useRSMouse = false;  
  15.         mLocked.pointerGesturesEnabled = true;  
  16.         mLocked.showTouches = false;  
  17.         mLocked.showStylus = false;  
  18.         mLocked.showEraser = false;  
  19.         mLocked.penToTouchDelayMs = -1;  
  20.         mLocked.lockTouch = false;  
  21.         mLocked.fingerOnlyMode = true;  
  22.         mLocked.stylusLockOnEdge = false;  
  23.         mLocked.leftHandedMode = false;  
  24.     }  
  25.   
  26.     sp<EventHub> eventHub = new EventHub();  
  27.     mInputManager = new InputManager(eventHub, this, this);  

InputManager实例的创建过程,会InputManager类的构造函数里面执行一些初始化操作。

InputManager.cpp

[html]  view plain copy 在CODE上查看代码片 派生到我的代码片
  1. InputManager::InputManager(  
  2.         const sp<EventHubInterface>& eventHub,  
  3.         const sp<InputReaderPolicyInterface>& readerPolicy,  
  4.         const sp<InputDispatcherPolicyInterface>& dispatcherPolicy) {  
  5.     mDispatcher = new InputDispatcher(dispatcherPolicy);  
  6.     mReader = new InputReader(eventHub, readerPolicy, mDispatcher);  
  7.     initialize();  
  8. }  

这里主要是创建了一个InputDispatcher对象和一个InputReader对象,并且分别保存在成员变量mDispatcher和mReader中。InputDispatcher类是负责把事件消息向上层传递,而InputReader类则是通过EventHub类来实现读取事件的。

InputDispatcher在构造的时候,会创建一个Looper对象,Looper的核心其实是一个消息队列,通过不停的处理Looper消息队列中的消息来完成线程间的通信。这个Looper对象以后会用到。

创建了这两个对象后,还要调用initialize函数来执行其它的初始化操作。

[html]  view plain copy 在CODE上查看代码片 派生到我的代码片
  1. void InputManager::initialize() {  
  2.     mReaderThread = new InputReaderThread(mReader);  
  3.     mDispatcherThread = new InputDispatcherThread(mDispatcher);  
  4. }  

这个函数创建了一个InputReaderThread线程实例和一个InputDispatcherThread线程实例,并且分别保存在成员变量mReaderThread和mDispatcherThread中。这里的InputReader实列mReader就是通过这里的InputReaderThread线程实例mReaderThread来读取事件的,而InputDispatcher实例mDispatcher则是通过这里的InputDispatcherThread线程实例mDisptacherThread来分发事件的。

至此,InputManagerService的创建工作就完成了。也生成了InputManager相关的一系列对象。下一步的主要工作就是启动InputManager了。

1.2 启动InputManagerService

InputManagerService的start函数主要是调用了nativeStart, 并把之前保存的NativeInputManager的指针mPtr传递下去。

com_android_server_Input_InputManagerService.cpp

[html]  view plain copy 在CODE上查看代码片 派生到我的代码片
  1. static void nativeStart(JNIEnv* env, jclass clazz, jint ptr) {  
  2.     NativeInputManager* im = reinterpret_cast<NativeInputManager*>(ptr);  
  3.   
  4.     status_t result = im->getInputManager()->start();  
  5.     if (result) {  
  6.         jniThrowRuntimeException(env, "Input manager could not be started.");  
  7.     }  
  8. }  

这里的 im->getInputManager()->start()实际上调用的就是InputManager的start方法。

InputManager.cpp

[html]  view plain copy 在CODE上查看代码片 派生到我的代码片
  1. status_t InputManager::start() {  
  2.     status_t result = mDispatcherThread->run("InputDispatcher", PRIORITY_URGENT_DISPLAY);  
  3.     if (result) {  
  4.         ALOGE("Could not start InputDispatcher thread due to error %d.", result);  
  5.         return result;  
  6.     }  
  7.   
  8.     result = mReaderThread->run("InputReader", PRIORITY_URGENT_DISPLAY);  
  9.     if (result) {  
  10.         ALOGE("Could not start InputReader thread due to error %d.", result);  
  11.   
  12.         mDispatcherThread->requestExit();  
  13.         return result;  
  14.     }  
  15.   
  16.     return OK;  
  17. }  
这里启动之前创建的两个线程,用于读取和分发。然后就进入他们的线程函数threadLoop中。

到这里,Input子系统的初始化过程就完毕了。

2. 应用程序UI与Input子系统关系的建立——创建Channel

当接收到事件后,需要把事件传递给对应的窗口,就需要建立起一个通道,用于它们之间的通信。

在Activity启动的时候,会通过windowmanager的addView方法将窗口加入到WMS中,并创建了ViewRoot,然后会调用ViewRoot的setView方法。

[html]  view plain copy 在CODE上查看代码片 派生到我的代码片
  1. public void setView(View view, WindowManager.LayoutParams attrs, View panelParentView) {  
  2.     synchronized (this) {  
  3.         if (mView == null) {                  
  4.           ......  
  5.   
  6.             // Schedule the first layout -before- adding to the window  
  7.             // manager, to make sure we do the relayout before receiving  
  8.             // any other events from the system.  
  9.             requestLayout();  
  10.             if ((mWindowAttributes.inputFeatures  
  11.                     & WindowManager.LayoutParams.INPUT_FEATURE_NO_INPUT_CHANNEL) == 0) {  
  12.                 mInputChannel = new InputChannel();  
  13.             }  
  14.             try {  
  15.                 mOrigWindowType = mWindowAttributes.type;  
  16.                 mAttachInfo.mRecomputeGlobalAttributes = true;  
  17.                 collectViewAttributes();  
  18.                 res = mWindowSession.addToDisplay(mWindow, mSeq, mWindowAttributes,  
  19.                         getHostVisibility(), mDisplay.getDisplayId(),  
  20.                         mAttachInfo.mContentInsets, mInputChannel);  
  21.             } catch (RemoteException e) {  
  22.                 mAdded = false;  
  23.                 mView = null;  
  24.                 mAttachInfo.mRootView = null;  
  25.                 mInputChannel = null;  
  26.                 mFallbackEventHandler.setView(null);  
  27.                 unscheduleTraversals();  
  28.                 setAccessibilityFocus(null, null);  
  29.                 throw new RuntimeException("Adding window failed", e);  
  30.             } finally {  
  31.                 if (restore) {  
  32.                     attrs.restore();  
  33.                 }  
  34.             }  
  35.   
  36.             ......  
  37.   
  38.             if (view instanceof RootViewSurfaceTaker) {  
  39.                 mInputQueueCallback =  
  40.                     ((RootViewSurfaceTaker)view).willYouTakeTheInputQueue();  
  41.             }  
  42.             if (mInputChannel != null) {  
  43.                 if (mInputQueueCallback != null) {  
  44.                     mInputQueue = new InputQueue();  
  45.                     mInputQueueCallback.onInputQueueCreated(mInputQueue);  
  46.                 }  
  47.                 mInputEventReceiver = new WindowInputEventReceiver(mInputChannel,  
  48.                         Looper.myLooper());  
  49.   
  50.                 try {  
  51.                     Activity activity = (Activity)view.getContext();  
  52.                     ActivityInfo ai = activity.getPackageManager().getActivityInfo(  
  53.                         activity.getComponentName(), PackageManager.GET_META_DATA);  
  54.                     mInputEventReceiver.mConsumeBatchesImmediately =  
  55.                         ai.metaData.getBoolean("com.nvidia.immediateInput");  
  56.                 } catch(Exception e) {  
  57.                 }  
  58.             }  
  59.   
  60.             ......  
  61.         }  
  62.     }  
  63.   }   

以上函数中与通道建立相关的地方有三处:

(1)requestLayout。

         requestLayout函数来通知InputManager,这个Activity窗口是当前被激活的窗口。也就是更新激活窗口

(2)mWindowSession.addToDisplay

        负责把事件接收通道的一端注册在InputManager中,也就是WMS注册InputChannel

(3)

[html]  view plain copy 在CODE上查看代码片 派生到我的代码片
  1. if (view instanceof RootViewSurfaceTaker) {  
  2.     mInputQueueCallback =  
  3.         ((RootViewSurfaceTaker)view).willYouTakeTheInputQueue();  
  4. }  
  5. if (mInputChannel != null) {  
  6.     if (mInputQueueCallback != null) {  
  7.         mInputQueue = new InputQueue();  
  8.         mInputQueueCallback.onInputQueueCreated(mInputQueue);  
  9.     }  
  10.     mInputEventReceiver = new WindowInputEventReceiver(mInputChannel,  
  11.             Looper.myLooper());  

也就是应用程序进程注册InputChannel。

2.1 requestLayout

requestLayout通过handler机制,会执行ViewRoot的relayoutWindow方法,通过AIDL接口最终会调用到WMS的relayoutWindow方法。

需要注意的是:实际上WMS侧的addWindow比relayoutWindow先执行。

在relayoutWindow中调用了以下代码:

[html]  view plain copy 在CODE上查看代码片 派生到我的代码片
  1. mInputMonitor.updateInputWindowsLw(true /*force*/);  

[html]  view plain copy 在CODE上查看代码片 派生到我的代码片
  1. /* Updates the cached window information provided to the input dispatcher. */  
  2. public void updateInputWindowsLw(boolean force) {  
  3.     if (!force && !mUpdateInputWindowsNeeded) {  
  4.         return;  
  5.     }  
  6.     mUpdateInputWindowsNeeded = false;  
  7.   
  8.     if (false) Slog.d(WindowManagerService.TAG, ">>>>>> ENTERED updateInputWindowsLw");  
  9.   
  10.     // Populate the input window list with information about all of the windows that  
  11.     // could potentially receive input.  
  12.     // As an optimization, we could try to prune the list of windows but this turns  
  13.     // out to be difficult because only the native code knows for sure which window  
  14.     // currently has touch focus.  
  15.     final WindowStateAnimator universeBackground = mService.mAnimator.mUniverseBackground;  
  16.     final int aboveUniverseLayer = mService.mAnimator.mAboveUniverseLayer;  
  17.     boolean addedUniverse = false;  
  18.   
  19.     // If there's a drag in flight, provide a pseudowindow to catch drag input  
  20.     final boolean inDrag = (mService.mDragState != null);  
  21.     if (inDrag) {  
  22.         if (WindowManagerService.DEBUG_DRAG) {  
  23.             Log.d(WindowManagerService.TAG, "Inserting drag window");  
  24.         }  
  25.         final InputWindowHandle dragWindowHandle = mService.mDragState.mDragWindowHandle;  
  26.         if (dragWindowHandle != null) {  
  27.             addInputWindowHandleLw(dragWindowHandle);  
  28.         } else {  
  29.             Slog.w(WindowManagerService.TAG, "Drag is in progress but there is no "  
  30.                     + "drag window handle.");  
  31.         }  
  32.     }  
  33.   
  34.     final int NFW = mService.mFakeWindows.size();  
  35.     for (int i = 0; i < NFW; i++) {  
  36.         addInputWindowHandleLw(mService.mFakeWindows.get(i).mWindowHandle);  
  37.     }  
  38.   
  39.     // Add all windows on the default display.  
  40.     final int numDisplays = mService.mDisplayContents.size();  
  41.     for (int displayNdx = 0; displayNdx < numDisplays; ++displayNdx) {  
  42.         WindowList windows = mService.mDisplayContents.valueAt(displayNdx).getWindowList();  
  43.         for (int winNdx = windows.size() - 1; winNdx >= 0; --winNdx) {  
  44.             final WindowState child = windows.get(winNdx);  
  45.             final InputChannel inputChannel = child.mInputChannel;  
  46.             final InputWindowHandle inputWindowHandle = child.mInputWindowHandle;  
  47.             if (inputChannel == null || inputWindowHandle == null || child.mRemoved) {  
  48.                 // Skip this window because it cannot possibly receive input.  
  49.                 continue;  
  50.             }  
  51.   
  52.             final int flags = child.mAttrs.flags;  
  53.             final int privateFlags = child.mAttrs.privateFlags;  
  54.             final int type = child.mAttrs.type;  
  55.   
  56.             final boolean hasFocus = (child == mInputFocus);  
  57.             final boolean isVisible = child.isVisibleLw();  
  58.             final boolean hasWallpaper = (child == mService.mWallpaperTarget)  
  59.                     && (type != WindowManager.LayoutParams.TYPE_KEYGUARD);  
  60.             final boolean onDefaultDisplay = (child.getDisplayId() == Display.DEFAULT_DISPLAY);  
  61.   
  62.             // If there's a drag in progress and 'child' is a potential drop target,  
  63.             // make sure it's been told about the drag  
  64.             if (inDrag && isVisible && onDefaultDisplay) {  
  65.                 mService.mDragState.sendDragStartedIfNeededLw(child);  
  66.             }  
  67.   
  68.             if (universeBackground != null && !addedUniverse  
  69.                     && child.mBaseLayer < aboveUniverseLayer && onDefaultDisplay) {  
  70.                 final WindowState u = universeBackground.mWin;  
  71.                 if (u.mInputChannel != null && u.mInputWindowHandle != null) {  
  72.                     addInputWindowHandleLw(u.mInputWindowHandle, u, u.mAttrs.flags,  
  73.                             u.mAttrs.privateFlags, u.mAttrs.type,  
  74.                             true, u == mInputFocus, false);  
  75.                 }  
  76.                 addedUniverse = true;  
  77.             }  
  78.   
  79.             if (child.mWinAnimator != universeBackground) {  
  80.                 addInputWindowHandleLw(inputWindowHandle, child, flags, privateFlags, type,  
  81.                         isVisible, hasFocus, hasWallpaper);  
  82.             }  
  83.         }  
  84.     }  
  85.   
  86.     // Send windows to native code.  
  87.     mService.mInputManager.setInputWindows(mInputWindowHandles);  
  88.   
  89.     // Clear the list in preparation for the next round.  
  90.     clearInputWindowHandlesLw();  
  91.   
  92.     if (false) Slog.d(WindowManagerService.TAG, "<<<<<<< EXITED updateInputWindowsLw");  
  93. }  

这个函数将当前系统中带有InputChannel的Activity窗口都设置为InputManager的输入窗口。这些窗口保存在mInputWindowHandles数组中。

InputManagerService.java

[html]  view plain copy 在CODE上查看代码片 派生到我的代码片
  1. public void setInputWindows(InputWindowHandle[] windowHandles) {  
  2.     nativeSetInputWindows(mPtr, windowHandles);  
  3. }  

接下来会调用native的setInputWindows方法。

com_android_server_Input_inputManagerService.cpp

[html]  view plain copy 在CODE上查看代码片 派生到我的代码片
  1. static void nativeSetInputWindows(JNIEnv* env, jclass clazz,  
  2.         jint ptr, jobjectArray windowHandleObjArray) {  
  3.     NativeInputManager* im = reinterpret_cast<NativeInputManager*>(ptr);  
  4.   
  5.     im->setInputWindows(env, windowHandleObjArray);  
  6. }  

[html]  view plain copy 在CODE上查看代码片 派生到我的代码片
  1. void NativeInputManager::setInputWindows(JNIEnv* env, jobjectArray windowHandleObjArray) {  
  2.     Vector<sp<InputWindowHandle> > windowHandles;  
  3.   
  4.     if (windowHandleObjArray) {  
  5.         jsize length = env->GetArrayLength(windowHandleObjArray);  
  6.         for (jsize i = 0; i < length; i++) {  
  7.             jobject windowHandleObj = env->GetObjectArrayElement(windowHandleObjArray, i);  
  8.             if (! windowHandleObj) {  
  9.                 break; // found null element indicating end of used portion of the array  
  10.             }  
  11.   
  12.             sp<InputWindowHandle> windowHandle =  
  13.                     android_server_InputWindowHandle_getHandle(env, windowHandleObj);  
  14.             if (windowHandle != NULL) {  
  15.                 windowHandles.push(windowHandle);  
  16.             }  
  17.             env->DeleteLocalRef(windowHandleObj);  
  18.         }  
  19.     }  
  20.   
  21.     mInputManager->getDispatcher()->setInputWindows(windowHandles);  
  22.   
  23.     // Do this after the dispatcher has updated the window handle state.  
  24.     bool newPointerGesturesEnabled = true;  
  25.     size_t numWindows = windowHandles.size();  
  26.     for (size_t i = 0; i < numWindows; i++) {  
  27.         const sp<InputWindowHandle>windowHandle = windowHandles.itemAt(i);  
  28.         const InputWindowInfo* windowInfo = windowHandle->getInfo();  
  29.         if (windowInfo && windowInfo->hasFocus && (windowInfo->inputFeatures  
  30.                 & InputWindowInfo::INPUT_FEATURE_DISABLE_TOUCH_PAD_GESTURES)) {  
  31.             newPointerGesturesEnabled = false;  
  32.         }  
  33.     }  
  34.   
  35.     uint32_t changes = 0;  
  36.     { // acquire lock  
  37.         AutoMutex _l(mLock);  
  38.   
  39.         if (mLocked.pointerGesturesEnabled != newPointerGesturesEnabled) {  
  40.             mLocked.pointerGesturesEnabled = newPointerGesturesEnabled;  
  41.             changes |= InputReaderConfiguration::CHANGE_POINTER_GESTURE_ENABLEMENT;  
  42.         }  
  43.     } // release lock  
  44.   
  45.     if (changes) {  
  46.         mInputManager->getReader()->requestRefreshConfiguration(changes);  
  47.     }  
  48. }  

这个函数首先将Java层的Window转换成C++层的windowHandle,然后放在windowHandles向量中,最后将这些输入窗口设置到InputDispatcher中去。

InputDispatcher.cpp

[html]  view plain copy 在CODE上查看代码片 派生到我的代码片
  1. void InputDispatcher::setInputWindows(const Vector<sp<InputWindowHandle> >& inputWindowHandles) {  
  2. #if DEBUG_FOCUS  
  3.     ALOGD("setInputWindows");  
  4. #endif  
  5.     { // acquire lock  
  6.         AutoMutex _l(mLock);  
  7.   
  8.         Vector<sp<InputWindowHandle> > oldWindowHandles = mWindowHandles;  
  9.         mWindowHandles = inputWindowHandles;  
  10.   
  11.         sp<InputWindowHandle> newFocusedWindowHandle;  
  12.         bool foundHoveredWindow = false;  
  13.         for (size_t i = 0; i < mWindowHandles.size(); i++) {  
  14.             const sp<InputWindowHandle>windowHandle = mWindowHandles.itemAt(i);  
  15.             if (!windowHandle->updateInfo() || windowHandle->getInputChannel() == NULL) {  
  16.                 mWindowHandles.removeAt(i--);  
  17.                 continue;  
  18.             }  
  19.             if (windowHandle->getInfo()->hasFocus) {  
  20.                 newFocusedWindowHandle = windowHandle;  
  21.             }  
  22.             if (windowHandle == mLastHoverWindowHandle) {  
  23.                 foundHoveredWindow = true;  
  24.             }  
  25.         }  
  26.   
  27.         if (!foundHoveredWindow) {  
  28.             mLastHoverWindowHandle = NULL;  
  29.         }  
  30.   
  31.         if (mFocusedWindowHandle != newFocusedWindowHandle) {  
  32.             if (mFocusedWindowHandle != NULL) {  
  33. #if DEBUG_FOCUS  
  34.                 ALOGD("Focus left window: %s",  
  35.                         mFocusedWindowHandle->getName().string());  
  36. #endif  
  37.                 sp<InputChannel> focusedInputChannel = mFocusedWindowHandle->getInputChannel();  
  38.                 if (focusedInputChannel != NULL) {  
  39.                     CancelationOptions options(CancelationOptions::CANCEL_NON_POINTER_EVENTS,  
  40.                             "focus left window");  
  41.                     synthesizeCancelationEventsForInputChannelLocked(  
  42.                             focusedInputChannel, options);  
  43.                 }  
  44.             }  
  45.             if (newFocusedWindowHandle != NULL) {  
  46. #if DEBUG_FOCUS  
  47.                 ALOGD("Focus entered window: %s",  
  48.                         newFocusedWindowHandle->getName().string());  
  49. #endif  
  50.             }  
  51.             mFocusedWindowHandle = newFocusedWindowHandle;  
  52.         }  
  53.   
  54.         for (size_t i = 0; i < mTouchState.windows.size(); i++) {  
  55.             TouchedWindow& touchedWindow = mTouchState.windows.editItemAt(i);  
  56.             if (!hasWindowHandleLocked(touchedWindow.windowHandle)) {  
  57. #if DEBUG_FOCUS  
  58.                 ALOGD("Touched window was removed: %s",  
  59.                         touchedWindow.windowHandle->getName().string());  
  60. #endif  
  61.                 sp<InputChannel> touchedInputChannel =  
  62.                         touchedWindow.windowHandle->getInputChannel();  
  63.                 if (touchedInputChannel != NULL) {  
  64.                     CancelationOptions options(CancelationOptions::CANCEL_POINTER_EVENTS,  
  65.                             "touched window was removed");  
  66.                     synthesizeCancelationEventsForInputChannelLocked(  
  67.                             touchedInputChannel, options);  
  68.                 }  
  69.                 mTouchState.windows.removeAt(i--);  
  70.             }  
  71.         }  
  72.   
  73.         // Release information for windows that are no longer present.  
  74.         // This ensures that unused input channels are released promptly.  
  75.         // Otherwise, they might stick around until the window handle is destroyed  
  76.         // which might not happen until the next GC.  
  77.         for (size_t i = 0; i < oldWindowHandles.size(); i++) {  
  78.             const sp<InputWindowHandle>oldWindowHandle = oldWindowHandles.itemAt(i);  
  79.             if (!hasWindowHandleLocked(oldWindowHandle)) {  
  80. #if DEBUG_FOCUS  
  81.                 ALOGD("Window went away: %s", oldWindowHandle->getName().string());  
  82. #endif  
  83.                 oldWindowHandle->releaseInfo();  
  84.             }  
  85.         }  
  86.     } // release lock  
  87.   
  88.     // Wake up poll loop since it may need to make new input dispatching choices.  
  89.     mLooper->wake();  
  90. }  

这个方法的主要作用就是从传进来的窗口向量中,找到哪一个窗口是获得焦点的,获得焦点的输入窗口即为当前激活的窗口,并把窗口的句柄保存在mFocusedWindowHandle中。它的定义如下:

    // Focus tracking for keys, trackball, etc.
    sp<InputWindowHandle> mFocusedWindowHandle;

2.2 WMS注册InputChannel(mWindowSession.addToDisplay)

这个函数最终回调用到WMS的addWindow方法,和通道建立相关的主要代码如下:

[html]  view plain copy 在CODE上查看代码片 派生到我的代码片
  1. if (outInputChannel != null && (attrs.inputFeatures  
  2.         & WindowManager.LayoutParams.INPUT_FEATURE_NO_INPUT_CHANNEL) == 0) {  
  3.     String name = win.makeInputChannelName();  
  4.     InputChannel[] inputChannels = InputChannel.openInputChannelPair(name);  
  5.     win.setInputChannel(inputChannels[0]);  
  6.     inputChannels[1].transferTo(outInputChannel);  
  7.   
  8.     mInputManager.registerInputChannel(win.mInputChannel, win.mInputWindowHandle);  
  9. }  

这里的outInputChannel是在setView时new并传入到addWindow中的。win是WindowState对象,运行在WMS侧。

通过InputChannel.openInputChannelPair函数来创建一对输入通道,其中一个位于WindowManagerService中,另外一个通过outInputChannel参数返回到应用程序中:

[html]  view plain copy 在CODE上查看代码片 派生到我的代码片
  1. public void transferTo(InputChannel outParameter) {  
  2.     if (outParameter == null) {  
  3.         throw new IllegalArgumentException("outParameter must not be null");  
  4.     }  
  5.       
  6.     nativeTransferTo(outParameter);  
  7. }  

[html]  view plain copy 在CODE上查看代码片 派生到我的代码片
  1. static void android_view_InputChannel_nativeTransferTo(JNIEnv* env, jobject obj,  
  2.         jobject otherObj) {  
  3.     if (android_view_InputChannel_getNativeInputChannel(env, otherObj) != NULL) {  
  4.         jniThrowException(env, "java/lang/IllegalStateException",  
  5.                 "Other object already has a native input channel.");  
  6.         return;  
  7.     }  
  8.   
  9.     NativeInputChannel* nativeInputChannel =  
  10.             android_view_InputChannel_getNativeInputChannel(env, obj);  
  11.     android_view_InputChannel_setNativeInputChannel(env, otherObj, nativeInputChannel);  
  12.     android_view_InputChannel_setNativeInputChannel(env, obj, NULL);  
  13. }  

 接下来我们就看一下InputChannel.openInputChannelPair函数的实现。

[html]  view plain copy 在CODE上查看代码片 派生到我的代码片
  1. public static InputChannel[] openInputChannelPair(String name) {  
  2.     if (name == null) {  
  3.         throw new IllegalArgumentException("name must not be null");  
  4.     }  
  5.   
  6.     if (DEBUG) {  
  7.         Slog.d(TAG, "Opening input channel pair '" + name + "'");  
  8.     }  
  9.     return nativeOpenInputChannelPair(name);  
  10. }  

native实现

[html]  view plain copy 在CODE上查看代码片 派生到我的代码片
  1. static jobjectArray android_view_InputChannel_nativeOpenInputChannelPair(JNIEnv* env,  
  2.         jclass clazz, jstring nameObj) {  
  3.     const char* nameChars = env->GetStringUTFChars(nameObj, NULL);  
  4.     String8 name(nameChars);  
  5.     env->ReleaseStringUTFChars(nameObj, nameChars);  
  6.   
  7.     sp<InputChannel> serverChannel;  
  8.     sp<InputChannel> clientChannel;  
  9.     status_t result = InputChannel::openInputChannelPair(name, serverChannel, clientChannel);  
  10.   
  11.     if (result) {  
  12.         String8 message;  
  13.         message.appendFormat("Could not open input channel pair.  status=%d", result);  
  14.         jniThrowRuntimeException(env, message.string());  
  15.         return NULL;  
  16.     }  
  17.   
  18.     jobjectArray channelPair = env->NewObjectArray(2, gInputChannelClassInfo.clazz, NULL);  
  19.     if (env->ExceptionCheck()) {  
  20.         return NULL;  
  21.     }  
  22.   
  23.     jobject serverChannelObj = android_view_InputChannel_createInputChannel(env,  
  24.             new NativeInputChannel(serverChannel));  
  25.     if (env->ExceptionCheck()) {  
  26.         return NULL;  
  27.     }  
  28.   
  29.     jobject clientChannelObj = android_view_InputChannel_createInputChannel(env,  
  30.             new NativeInputChannel(clientChannel));  
  31.     if (env->ExceptionCheck()) {  
  32.         return NULL;  
  33.     }  
  34.   
  35.     env->SetObjectArrayElement(channelPair, 0, serverChannelObj);  
  36.     env->SetObjectArrayElement(channelPair, 1, clientChannelObj);  
  37.     return channelPair;  
  38. }  

 这个函数根据传进来的参数name在C++层分别创建两个InputChannel,一个作为Server端使用,一个作为Client端使用,这里的Server端即是指InputManager,而Client端即是指应用程序。这两个本地的InputChannel是通过InputChannel::openInputChannelPair函数创建的,创建完成后,再相应地在Java层创建相应的两个InputChannel,然后返回。


openInputChannelPair的实现如下:

[html]  view plain copy 在CODE上查看代码片 派生到我的代码片
  1. status_t InputChannel::openInputChannelPair(const String8& name,  
  2.         sp<InputChannel>& outServerChannel, sp<InputChannel>& outClientChannel) {  
  3.     int sockets[2];  
  4.     if (socketpair(AF_UNIX, SOCK_SEQPACKET, 0, sockets)) {  
  5.         status_t result = -errno;  
  6.         ALOGE("channel '%s' ~ Could not create socket pair.  errno=%d",  
  7.                 name.string(), errno);  
  8.         outServerChannel.clear();  
  9.         outClientChannel.clear();  
  10.         return result;  
  11.     }  
  12.   
  13.     int bufferSize = SOCKET_BUFFER_SIZE;  
  14.     setsockopt(sockets[0], SOL_SOCKET, SO_SNDBUF, &bufferSize, sizeof(bufferSize));  
  15.     setsockopt(sockets[0], SOL_SOCKET, SO_RCVBUF, &bufferSize, sizeof(bufferSize));  
  16.     setsockopt(sockets[1], SOL_SOCKET, SO_SNDBUF, &bufferSize, sizeof(bufferSize));  
  17.     setsockopt(sockets[1], SOL_SOCKET, SO_RCVBUF, &bufferSize, sizeof(bufferSize));  
  18.   
  19.     String8 serverChannelName = name;  
  20.     serverChannelName.append(" (server)");  
  21.     outServerChannel = new InputChannel(serverChannelName, sockets[0]);  
  22.   
  23.     String8 clientChannelName = name;  
  24.     clientChannelName.append(" (client)");  
  25.     outClientChannel = new InputChannel(clientChannelName, sockets[1]);  
  26.     return OK;  
  27. }  

先看一下InputChannel的构造函数

[html]  view plain copy 在CODE上查看代码片 派生到我的代码片
  1. InputChannel::InputChannel(const String8& name, int fd) :  
  2.         mName(name), mFd(fd) {  
  3. #if DEBUG_CHANNEL_LIFECYCLE  
  4.     ALOGD("Input channel constructed: name='%s'fd=%d",  
  5.             mName.string(), fd);  
  6. #endif  
  7.   
  8.     int result = fcntl(mFd, F_SETFL, O_NONBLOCK);  
  9.     LOG_ALWAYS_FATAL_IF(result != 0, "channel '%s' ~ Could not make socket "  
  10.             "non-blocking.  errno=%d", mName.string(), errno);  
  11. }  
每个channel都有一个文件描述符,这个文件描述符就是创建的socket。

通过调用Linux的socketpair()方法建立一对匿名的已经连接的套接字,然后调用setsockopt()方法为其分配内存,然后用其做为参数,创建native环境中的InputChannel对象,分别赋值给outServerChannel、和outClientChannel指针。

创建好两个native层的InputChannel对象后,存在channelPair数组中,然后通过JNI返回到JAVA环境中。

下一步,需要把刚才创建的Server端的输入通道注册到InputManager中:

[html]  view plain copy 在CODE上查看代码片 派生到我的代码片
  1. mInputManager.registerInputChannel(win.mInputChannel, win.mInputWindowHandle);  

[html]  view plain copy 在CODE上查看代码片 派生到我的代码片
  1. public void registerInputChannel(InputChannel inputChannel,  
  2.         InputWindowHandle inputWindowHandle) {  
  3.     if (inputChannel == null) {  
  4.         throw new IllegalArgumentException("inputChannel must not be null.");  
  5.     }  
  6.       
  7.     nativeRegisterInputChannel(mPtr, inputChannel, inputWindowHandle, false);  
  8. }  

native的实现

[html]  view plain copy 在CODE上查看代码片 派生到我的代码片
  1. static void nativeRegisterInputChannel(JNIEnv* env, jclass clazz,  
  2.         jint ptr, jobject inputChannelObj, jobject inputWindowHandleObj, jboolean monitor) {  
  3.     NativeInputManager* im = reinterpret_cast<NativeInputManager*>(ptr);  
  4.   
  5.     sp<InputChannel> inputChannel = android_view_InputChannel_getInputChannel(env,  
  6.             inputChannelObj);  
  7.     if (inputChannel == NULL) {  
  8.         throwInputChannelNotInitialized(env);  
  9.         return;  
  10.     }  
  11.   
  12.     sp<InputWindowHandle> inputWindowHandle =  
  13.             android_server_InputWindowHandle_getHandle(env, inputWindowHandleObj);  
  14.   
  15.     status_t status = im->registerInputChannel(  
  16.             env, inputChannel, inputWindowHandle, monitor);  
  17.     if (status) {  
  18.         String8 message;  
  19.         message.appendFormat("Failed to register input channel.  status=%d", status);  
  20.         jniThrowRuntimeException(env, message.string());  
  21.         return;  
  22.     }  
  23.   
  24.     if (! monitor) {  
  25.         android_view_InputChannel_setDisposeCallback(env, inputChannelObj,  
  26.                 handleInputChannelDisposed, im);  
  27.     }  
  28. }  

[html]  view plain copy 在CODE上查看代码片 派生到我的代码片
  1. status_t NativeInputManager::registerInputChannel(JNIEnv* env,  
  2.         const sp<InputChannel>& inputChannel,  
  3.         const sp<InputWindowHandle>& inputWindowHandle, bool monitor) {  
  4.     return mInputManager->getDispatcher()->registerInputChannel(  
  5.             inputChannel, inputWindowHandle, monitor);  
  6. }  

这个函数主要是调用了InputDispatcher的registerInputChannel来真正执行注册输入通道的操作。

[html]  view plain copy 在CODE上查看代码片 派生到我的代码片
  1. status_t InputDispatcher::registerInputChannel(const sp<InputChannel>& inputChannel,  
  2.         const sp<InputWindowHandle>& inputWindowHandle, bool monitor) {  
  3. #if DEBUG_REGISTRATION  
  4.     ALOGD("channel '%s' ~ registerInputChannel - monitor=%s", inputChannel->getName().string(),  
  5.             toString(monitor));  
  6. #endif  
  7.   
  8.     { // acquire lock  
  9.         AutoMutex _l(mLock);  
  10.   
  11.         if (getConnectionIndexLocked(inputChannel) >= 0) {  
  12.             ALOGW("Attempted to register already registered input channel '%s'",  
  13.                     inputChannel->getName().string());  
  14.             return BAD_VALUE;  
  15.         }  
  16.   
  17.         sp<Connection> connection = new Connection(inputChannel, inputWindowHandle, monitor);  
  18.   
  19.         int fd = inputChannel->getFd();  
  20.         mConnectionsByFd.add(fd, connection);  
  21.   
  22.         if (monitor) {  
  23.             mMonitoringChannels.push(inputChannel);  
  24.         }  
  25.   
  26.         mLooper->addFd(fd, 0, ALOOPER_EVENT_INPUT, handleReceiveCallback, this);  
  27.     } // release lock  
  28.   
  29.     // Wake the looper because some connections have changed.  
  30.     mLooper->wake();  
  31.     return OK;  
  32. }  
这个函数首先会通过getConnectionIndexLocked检查从参数传进来的InputChannel是否已经注册过了,如果已经注册过了,就返回一个BAD_VALUE值了,否则的话,就会创建一个Connection对象来封装即将要注册的inputChannel,并添加到mConnectionsByFd中,如果monitor为true,也把这个inputChannel添加到mMonitoringChannels中。

当需要通过管道发送消息的时候,从该列表中取出Connection对象,该对象与客户端是相对应的,之后调用mLooper->addFd()方法,把InputChannel对应的描述符添加到mLooper内部的描述符列表中。这里完成了wms的InputChannel的注册,即serverChannel。

在Looper类内部,会创建一个管道,然后Looper会睡眠在这个管道的读端,等待另外一个线程来往这个管道的写端写入新的内容,从而唤醒等待在这个管道读端的线程,除此之外,Looper还可以同时睡眠等待在其它的文件描述符上,因为它是通过Linux系统的epoll机制来批量等待指定的文件有新的内容可读的。这些其它的文件描述符就是通过Looper类的addFd成函数添加进去的了,在添加的时候,还可以指定回调函数,即当这个文件描述符所指向的文件有新的内容可读时,Looper就会调用这个hanldeReceiveCallback函数。

至此,Server端的InputChannel就注册完成了。

2.3 应用程序进程注册InputChannel

[html]  view plain copy 在CODE上查看代码片 派生到我的代码片
  1. if (view instanceof RootViewSurfaceTaker) {  
  2.     mInputQueueCallback =  
  3.         ((RootViewSurfaceTaker)view).willYouTakeTheInputQueue();  
  4. }  
  5. if (mInputChannel != null) {  
  6.     if (mInputQueueCallback != null) {  
  7.         mInputQueue = new InputQueue();  
  8.         mInputQueueCallback.onInputQueueCreated(mInputQueue);  
  9.     }  
  10.     mInputEventReceiver = new WindowInputEventReceiver(mInputChannel,  
  11.             Looper.myLooper());  
这里一般会执行最后的

[html]  view plain copy 在CODE上查看代码片 派生到我的代码片
  1. mInputEventReceiver = new WindowInputEventReceiver(mInputChannel,  
  2.            Looper.myLooper());  
接着,执行构造函数

[html]  view plain copy 在CODE上查看代码片 派生到我的代码片
  1.  final class WindowInputEventReceiver extends InputEventReceiver {  
  2.         public WindowInputEventReceiver(InputChannel inputChannel, Looper looper) {  
  3.             super(inputChannel, looper);  
  4.         }  
  5.   
  6.         @Override  
  7.         public void onInputEvent(InputEvent event) {  
  8.             enqueueInputEvent(event, this, 0, true);  
  9.         }  
  10.   
  11.    ......  

接着调用父类的构造函数

[html]  view plain copy 在CODE上查看代码片 派生到我的代码片
  1. public InputEventReceiver(InputChannel inputChannel, Looper looper) {  
  2.     if (inputChannel == null) {  
  3.         throw new IllegalArgumentException("inputChannel must not be null");  
  4.     }  
  5.     if (looper == null) {  
  6.         throw new IllegalArgumentException("looper must not be null");  
  7.     }  
  8.   
  9.     mInputChannel = inputChannel;  
  10.     mMessageQueue = looper.getQueue();  
  11.     mReceiverPtr = nativeInit(new WeakReference<InputEventReceiver>(this),  
  12.             inputChannel, mMessageQueue);  
  13.   
  14.     mCloseGuard.open("dispose");  
  15. }  

JNI层

[html]  view plain copy 在CODE上查看代码片 派生到我的代码片
  1. static jint nativeInit(JNIEnv* env, jclass clazz, jobject receiverWeak,  
  2.         jobject inputChannelObj, jobject messageQueueObj) {  
  3.     sp<InputChannel> inputChannel = android_view_InputChannel_getInputChannel(env,  
  4.             inputChannelObj);  
  5.     if (inputChannel == NULL) {  
  6.         jniThrowRuntimeException(env, "InputChannel is not initialized.");  
  7.         return 0;  
  8.     }  
  9.   
  10.     sp<MessageQueue> messageQueue = android_os_MessageQueue_getMessageQueue(env, messageQueueObj);  
  11.     if (messageQueue == NULL) {  
  12.         jniThrowRuntimeException(env, "MessageQueue is not initialized.");  
  13.         return 0;  
  14.     }  
  15.   
  16.     sp<NativeInputEventReceiver> receiver = new NativeInputEventReceiver(env,  
  17.             receiverWeak, inputChannel, messageQueue);  
  18.     status_t status = receiver->initialize();  
  19.     if (status) {  
  20.         String8 message;  
  21.         message.appendFormat("Failed to initialize input event receiver.  status=%d", status);  
  22.         jniThrowRuntimeException(env, message.string());  
  23.         return 0;  
  24.     }  
  25.   
  26.     receiver->incStrong(gInputEventReceiverClassInfo.clazz); // retain a reference for the object  
  27.     return reinterpret_cast<jint>(receiver.get());  
  28. }  
创建NativeInputEventReceiver

[html]  view plain copy 在CODE上查看代码片 派生到我的代码片
  1. NativeInputEventReceiver::NativeInputEventReceiver(JNIEnv* env,  
  2.         jobject receiverWeak, const sp<InputChannel>& inputChannel,  
  3.         const sp<MessageQueue>& messageQueue) :  
  4.         mReceiverWeakGlobal(env->NewGlobalRef(receiverWeak)),  
  5.         mInputConsumer(inputChannel), mMessageQueue(messageQueue),  
  6.         mBatchedInputEventPending(false), mFdEvents(0) {  
  7. #if DEBUG_DISPATCH_CYCLE  
  8.     ALOGD("channel '%s' ~ Initializing input event receiver.", getInputChannelName());  
  9. #endif  
  10. }  

执行初始化函数

[html]  view plain copy 在CODE上查看代码片 派生到我的代码片
  1. status_t NativeInputEventReceiver::initialize() {  
  2.     setFdEvents(ALOOPER_EVENT_INPUT);  
  3.     return OK;  
  4. }  

[html]  view plain copy 在CODE上查看代码片 派生到我的代码片
  1. void NativeInputEventReceiver::setFdEvents(int events) {  
  2.     if (mFdEvents != events) {  
  3.         mFdEvents = events;  
  4.         int fd = mInputConsumer.getChannel()->getFd();  
  5.         if (events) {  
  6.             mMessageQueue->getLooper()->addFd(fd, 0, events, this, NULL);  
  7.         } else {  
  8.             mMessageQueue->getLooper()->removeFd(fd);  
  9.         }  
  10.     }  
  11. }  
其实,执行的最终过程向Looper中加入文件描述符,只是这里的Looper是应用程序进程的Looper。


服务端和客户端都注册了Channel,最终都向Looper中加入了文件描述符。服务端使用的Channel是InputDispatcher创建的时候生成的,这里没有Java Looper,只有native Looper。

而客户端的Looper有一个Java的Looper和一个native Looper。

JAVA Looper包含一个MessageQueue,MessageQueue对应的Native 实例是一个NativeMessageQueue实例,NativeMessageQueue在创建的时候生成一个Native Looper。

客户端UI主线程循环读取Java Looper的消息以进行下一步的处理。

    其实Native Looper存在的意义就是作为JAVA Looper机制的开关器,

    1. 当消息队列中有消息存入时,唤醒Natvice Looper,至于如何发送向线程消息,这就用到了Handler;

    2. 当消息队列中没有消息时或者消息尚未到处理时间时,Natvice Looper block住整个线程。

    也就是说:创建了JAVA Looper的线程只有在有消息待处理时才处于活跃状态,无消息时block在等待消息写入的状态。Looper相关的内容可以参考  Android消息处理机制(Handler、Looper、MessageQueue与Message)

在以上客户端(ViewRoot)注册的时候,其实没有使用Handler向java的消息队列中push消息,而只是复用了native Looper。具体的过程如下:

UI主线程运行在Looper.loop();

[html]  view plain copy 在CODE上查看代码片 派生到我的代码片
  1. public static void loop() {  
  2.     final Looper me = myLooper();  
  3.     if (me == null) {  
  4.         throw new RuntimeException("No Looper; Looper.prepare() wasn't called on this thread.");  
  5.     }  
  6.     final MessageQueue queue = me.mQueue;  
  7.   
  8.     // Make sure the identity of this thread is that of the local process,  
  9.     // and keep track of what that identity token actually is.  
  10.     Binder.clearCallingIdentity();  
  11.     final long ident = Binder.clearCallingIdentity();  
  12.   
  13.     for (;;) {  
  14.         Message msg = queue.next(); // might block  
  15.         if (msg == null) {  
  16.             // No message indicates that the message queue is quitting.  
  17.             return;  
  18.         }  
  19.   
  20.         // This must be in a local variable, in case a UI event sets the logger  
  21.         Printer logging = me.mLogging;  
  22.         if (logging != null) {  
  23.             logging.println(">>>>> Dispatching to " + msg.target + " " +  
  24.                     msg.callback + ": " + msg.what);  
  25.         }  
  26.   
  27.         msg.target.dispatchMessage(msg);  
  28.   
  29.         if (logging != null) {  
  30.             logging.println("<<<<< Finished to " + msg.target + " " + msg.callback);  
  31.         }  
  32.   
  33.         // Make sure that during the course of dispatching the  
  34.         // identity of the thread wasn't corrupted.  
  35.         final long newIdent = Binder.clearCallingIdentity();  
  36.         if (ident != newIdent) {  
  37.             Log.wtf(TAG, "Thread identity changed from 0x"  
  38.                     + Long.toHexString(ident) + " to 0x"  
  39.                     + Long.toHexString(newIdent) + " while dispatching to "  
  40.                     + msg.target.getClass().getName() + " "  
  41.                     + msg.callback + " what=" + msg.what);  
  42.         }  
  43.   
  44.         msg.recycle();  
  45.     }  
  46. }  

以上通过queue.next()取得消息队列中的内容

[html]  view plain copy 在CODE上查看代码片 派生到我的代码片
  1. Message next() {  
  2.     int pendingIdleHandlerCount = -1; // -1 only during first iteration  
  3.     int nextPollTimeoutMillis = 0;  
  4.   
  5.     for (;;) {  
  6.         if (nextPollTimeoutMillis != 0) {  
  7.             Binder.flushPendingCommands();  
  8.         }  
  9.         nativePollOnce(mPtr, nextPollTimeoutMillis);  
  10.   
  11.         synchronized (this) {  
  12.            ......  
  13.             if (msg != null) {  
  14.                 if (now < msg.when) {  
  15.                     // Next message is not ready.  Set a timeout to wake up when it is ready.  
  16.                     nextPollTimeoutMillis = (int) Math.min(msg.when - now, Integer.MAX_VALUE);  
  17.                 } else {  
  18.                     // Got a message.  
  19.                     mBlocked = false;  
  20.                     if (prevMsg != null) {  
  21.                         prevMsg.next = msg.next;  
  22.                     } else {  
  23.                         mMessages = msg.next;  
  24.                     }  
  25.                     msg.next = null;  
  26.                     if (false) Log.v("MessageQueue", "Returning message: " + msg);  
  27.                     msg.markInUse();  
  28.                     return msg;  
  29.                 }  
  30.             } else {  
  31.                 // No more messages.  
  32.                 nextPollTimeoutMillis = -1;  
  33.             }  
  34.   
  35.     ......  
  36.     }  
  37. }  

接着调用nativePollOnce

[html]  view plain copy 在CODE上查看代码片 派生到我的代码片
  1. static void android_os_MessageQueue_nativePollOnce(JNIEnv* env, jclass clazz,  
  2.         jint ptr, jint timeoutMillis) {  
  3.     NativeMessageQueue* nativeMessageQueue = reinterpret_cast<NativeMessageQueue*>(ptr);  
  4.     nativeMessageQueue->pollOnce(env, timeoutMillis);  
  5. }  

[html]  view plain copy 在CODE上查看代码片 派生到我的代码片
  1. void NativeMessageQueue::pollOnce(JNIEnv* env, int timeoutMillis) {  
  2.     mInCallback = true;  
  3.     mLooper->pollOnce(timeoutMillis);  
  4.     mInCallback = false;  
  5.     if (mExceptionObj) {  
  6.         env->Throw(mExceptionObj);  
  7.         env->DeleteLocalRef(mExceptionObj);  
  8.         mExceptionObj = NULL;  
  9.     }  

[html]  view plain copy 在CODE上查看代码片 派生到我的代码片
  1. int Looper::pollOnce(int timeoutMillis, int* outFd, int* outEvents, void** outData) {  
  2.     int result = 0;  
  3.     for (;;) {  
  4.         while (mResponseIndex < mResponses.size()) {  
  5.             const Response& response = mResponses.itemAt(mResponseIndex++);  
  6.             int ident = response.request.ident;  
  7.             if (ident >= 0) {  
  8.                 int fd = response.request.fd;  
  9.                 int events = response.events;  
  10.                 void* data = response.request.data;  
  11. #if DEBUG_POLL_AND_WAKE  
  12.                 ALOGD("%p ~ pollOnce - returning signalled identifier %d: "  
  13.                         "fd=%d, events=0x%x, data=%p",  
  14.                         this, ident, fd, events, data);  
  15. #endif  
  16.                 if (outFd != NULL) *outFd = fd;  
  17.                 if (outEvents != NULL) *outEvents = events;  
  18.                 if (outData != NULL) *outData = data;  
  19.                 return ident;  
  20.             }  
  21.         }  
  22.   
  23.         if (result != 0) {  
  24. #if DEBUG_POLL_AND_WAKE  
  25.             ALOGD("%p ~ pollOnce - returning result %d", this, result);  
  26. #endif  
  27.             if (outFd != NULL) *outFd = 0;  
  28.             if (outEvents != NULL) *outEvents = 0;  
  29.             if (outData != NULL) *outData = NULL;  
  30.             return result;  
  31.         }  
  32.   
  33.         result = pollInner(timeoutMillis);  
  34.     }  

[html]  view plain copy 在CODE上查看代码片 派生到我的代码片
  1. int Looper::pollInner(int timeoutMillis) {  
  2. #if DEBUG_POLL_AND_WAKE  
  3.     ALOGD("%p ~ pollOnce - waiting: timeoutMillis=%d", this, timeoutMillis);  
  4. #endif  
  5.   
  6.     // Adjust the timeout based on when the next message is due.  
  7.     if (timeoutMillis != 0 && mNextMessageUptime != LLONG_MAX) {  
  8.         nsecs_t now = systemTime(SYSTEM_TIME_MONOTONIC);  
  9.         int messageTimeoutMillis = toMillisecondTimeoutDelay(now, mNextMessageUptime);  
  10.         if (messageTimeoutMillis >= 0  
  11.                 && (timeoutMillis < 0 || messageTimeoutMillis < timeoutMillis)) {  
  12.             timeoutMillis = messageTimeoutMillis;  
  13.         }  
  14. #if DEBUG_POLL_AND_WAKE  
  15.         ALOGD("%p ~ pollOnce - next message in %lldns, adjusted timeout: timeoutMillis=%d",  
  16.                 this, mNextMessageUptime - now, timeoutMillis);  
  17. #endif  
  18.     }  
  19.   
  20.     // Poll.  
  21.     int result = ALOOPER_POLL_WAKE;  
  22.     mResponses.clear();  
  23.     mResponseIndex = 0;  
  24.   
  25.     // We are about to idle.  
  26.     mIdling = true;  
  27.   
  28.     struct epoll_event eventItems[EPOLL_MAX_EVENTS];  
  29.     int eventCount = epoll_wait(mEpollFd, eventItems, EPOLL_MAX_EVENTS, timeoutMillis);  
  30.   
  31.     // No longer idling.  
  32.     mIdling = false;  
  33.   
  34.     // Acquire lock.  
  35.     mLock.lock();  
  36.   
  37.     // Check for poll error.  
  38.     if (eventCount < 0) {  
  39.         if (errno == EINTR) {  
  40.             goto Done;  
  41.         }  
  42.         ALOGW("Poll failed with an unexpected error, errno=%d", errno);  
  43.         result = ALOOPER_POLL_ERROR;  
  44.         goto Done;  
  45.     }  
  46.   
  47.     // Check for poll timeout.  
  48.     if (eventCount == 0) {  
  49. #if DEBUG_POLL_AND_WAKE  
  50.         ALOGD("%p ~ pollOnce - timeout", this);  
  51. #endif  
  52.         result = ALOOPER_POLL_TIMEOUT;  
  53.         goto Done;  
  54.     }  
  55.   
  56.     // Handle all events.  
  57. #if DEBUG_POLL_AND_WAKE  
  58.     ALOGD("%p ~ pollOnce - handling events from %d fds", this, eventCount);  
  59. #endif  
  60.   
  61.     for (int i = 0; i < eventCount; i++) {  
  62.         int fd = eventItems[i].data.fd;  
  63.         uint32_t epollEvents = eventItems[i].events;  
  64.         if (fd == mWakeReadPipeFd) {  
  65.             if (epollEvents & EPOLLIN) {  
  66.                 awoken();  
  67.             } else {  
  68.                 ALOGW("Ignoring unexpected epoll events 0x%x on wake read pipe.", epollEvents);  
  69.             }  
  70.         } else {  
  71.             ssize_t requestIndex = mRequests.indexOfKey(fd);  
  72.             if (requestIndex >= 0) {  
  73.                 int events = 0;  
  74.                 if (epollEvents & EPOLLIN) events |= ALOOPER_EVENT_INPUT;  
  75.                 if (epollEvents & EPOLLOUT) events |= ALOOPER_EVENT_OUTPUT;  
  76.                 if (epollEvents & EPOLLERR) events |= ALOOPER_EVENT_ERROR;  
  77.                 if (epollEvents & EPOLLHUP) events |= ALOOPER_EVENT_HANGUP;  
  78.                 pushResponse(events, mRequests.valueAt(requestIndex));  
  79.             } else {  
  80.                 ALOGW("Ignoring unexpected epoll events 0x%x on fd %d that is "  
  81.                         "no longer registered.", epollEvents, fd);  
  82.             }  
  83.         }  
  84.     }  
  85. Done: ;  
  86.   
  87.     // Invoke pending message callbacks.  
  88.     mNextMessageUptime = LLONG_MAX;  
  89.     while (mMessageEnvelopes.size() != 0) {  
  90.         nsecs_t now = systemTime(SYSTEM_TIME_MONOTONIC);  
  91.         const MessageEnvelope& messageEnvelope = mMessageEnvelopes.itemAt(0);  
  92.         if (messageEnvelope.uptime <= now) {  
  93.             // Remove the envelope from the list.  
  94.             // We keep a strong reference to the handler until the call to handleMessage  
  95.             // finishes.  Then we drop it so that the handler can be deleted *before*  
  96.             // we reacquire our lock.  
  97.             { // obtain handler  
  98.                 sp<MessageHandler> handler = messageEnvelope.handler;  
  99.                 Message message = messageEnvelope.message;  
  100.                 mMessageEnvelopes.removeAt(0);  
  101.                 mSendingMessage = true;  
  102.                 mLock.unlock();  
  103.   
  104. #if DEBUG_POLL_AND_WAKE || DEBUG_CALLBACKS  
  105.                 ALOGD("%p ~ pollOnce - sending message: handler=%p, what=%d",  
  106.                         this, handler.get(), message.what);  
  107. #endif  
  108.                 handler->handleMessage(message);  
  109.             } // release handler  
  110.   
  111.             mLock.lock();  
  112.             mSendingMessage = false;  
  113.             result = ALOOPER_POLL_CALLBACK;  
  114.         } else {  
  115.             // The last message left at the head of the queue determines the next wakeup time.  
  116.             mNextMessageUptime = messageEnvelope.uptime;  
  117.             break;  
  118.         }  
  119.     }  
  120.   
  121.     // Release lock.  
  122.     mLock.unlock();  
  123.   
  124.     // Invoke all response callbacks.  
  125.     for (size_t i = 0; i < mResponses.size(); i++) {  
  126.         Response& response = mResponses.editItemAt(i);  
  127.         if (response.request.ident == ALOOPER_POLL_CALLBACK) {  
  128.             int fd = response.request.fd;  
  129.             int events = response.events;  
  130.             void* data = response.request.data;  
  131. #if DEBUG_POLL_AND_WAKE || DEBUG_CALLBACKS  
  132.             ALOGD("%p ~ pollOnce - invoking fd event callback %p: fd=%d, events=0x%x, data=%p",  
  133.                     this, response.request.callback.get(), fd, events, data);  
  134. #endif  
  135.             int callbackResult = response.request.callback->handleEvent(fd, events, data);  
  136.             if (callbackResult == 0) {  
  137.                 removeFd(fd);  
  138.             }  
  139.             // Clear the callback reference in the response structure promptly because we  
  140.             // will not clear the response vector itself until the next poll.  
  141.             response.request.callback.clear();  
  142.             result = ALOOPER_POLL_CALLBACK;  
  143.         }  
  144.     }  
  145.     return result;  
  146. }  

这里借助Linux系统中的epoll机制了。 Linux系统中的epoll机制为处理大批量句柄而作了改进的poll,是Linux下多路复用IO接口select/poll的增强版本,它能显著减少程序在大量并发连接中只有少量活跃的情况下的系统CPU利用率。epoll机制这里不多介绍了。

这里的int eventCount = epoll_wait(mEpollFd, eventItems, EPOLL_MAX_EVENTS, timeoutMillis);就是等待文件描述符指向的文件的内容发生变化。

这些文件描述符是通过Looper.addFd添加进去的。如果制定了回调函数,这样当这个文件描述符所指向的文件有新的内容可读时,Looper就会调用这个回调函数。

这里再介绍一下Looper.addFd。

[html]  view plain copy 在CODE上查看代码片 派生到我的代码片
  1. int Looper::addFd(int fd, int ident, int events, ALooper_callbackFunc callback, void* data) {  
  2.     return addFd(fd, ident, events, callback ? new SimpleLooperCallback(callback) : NULL, data);  
  3. }  

创建SimpleLooperCallback时,会把这个函数指针赋值给它的成员mCallback,这个类有一个成员函数handleEvent,调用handleEvent就相当于调用注册进来的CallBack。

最后都是通过以下形式把对象作为参数传递给addFd的。WMS注册Channel的场景传递的是CallBack是函数指针,所以需要new一个SimpleLooperCallback.

应用程序进程注册Channel的场景直接传递的就是继承了LooperCallback的NativeInputEventReceiver对象,它实现了handleEvent方法。

[html]  view plain copy 在CODE上查看代码片 派生到我的代码片
  1. int Looper::addFd(int fd, int ident, int events, const sp<LooperCallback>& callback, void* data) {  
  2. #if DEBUG_CALLBACKS  
  3.     ALOGD("%p ~ addFd - fd=%d, ident=%d, events=0x%x, callback=%p, data=%p", this, fd, ident,  
  4.             events, callback.get(), data);  
  5. #endif  
  6.   
  7.     if (!callback.get()) {  
  8.         if (! mAllowNonCallbacks) {  
  9.             ALOGE("Invalid attempt to set NULL callback but not allowed for this looper.");  
  10.             return -1;  
  11.         }  
  12.   
  13.         if (ident < 0) {  
  14.             ALOGE("Invalid attempt to set NULL callback with ident < 0.");  
  15.             return -1;  
  16.         }  
  17.     } else {  
  18.         ident = ALOOPER_POLL_CALLBACK;  
  19.     }  
  20.   
  21.     int epollEvents = 0;  
  22.     if (events & ALOOPER_EVENT_INPUT) epollEvents |= EPOLLIN;  
  23.     if (events & ALOOPER_EVENT_OUTPUT) epollEvents |= EPOLLOUT;  
  24.   
  25.     { // acquire lock  
  26.         AutoMutex _l(mLock);  
  27.   
  28.         Request request;  
  29.         request.fd = fd;  
  30.         request.ident = ident;  
  31.         request.callback = callback;  
  32.         request.data = data;  
  33.   
  34.         struct epoll_event eventItem;  
  35.         memset(& eventItem, 0, sizeof(epoll_event)); // zero out unused members of data field union  
  36.         eventItem.events = epollEvents;  
  37.         eventItem.data.fd = fd;  
  38.   
  39.         ssize_t requestIndex = mRequests.indexOfKey(fd);  
  40.         if (requestIndex < 0) {  
  41.             int epollResult = epoll_ctl(mEpollFd, EPOLL_CTL_ADD, fd, & eventItem);  
  42.             if (epollResult < 0) {  
  43.                 ALOGE("Error adding epoll events for fd %d, errno=%d", fd, errno);  
  44.                 return -1;  
  45.             }  
  46.             mRequests.add(fd, request);  
  47.         } else {  
  48.             int epollResult = epoll_ctl(mEpollFd, EPOLL_CTL_MOD, fd, & eventItem);  
  49.             if (epollResult < 0) {  
  50.                 ALOGE("Error modifying epoll events for fd %d, errno=%d", fd, errno);  
  51.                 return -1;  
  52.             }  
  53.             mRequests.replaceValueAt(requestIndex, request);  
  54.         }  
  55.     } // release lock  
  56.     return 1;  
  57. }  

实际上是把callback赋值给了request.callback,并保存在mRequests中。

在 Looper::pollInner函数中,当有文件描述符指向的文件发生变化时,也就是说,从epoll_wait时,最终会调用response.request.callback->handleEvent(fd, events, data);

对于WMS注册Channel的场景,就会调用之前addFd中的callback,即InputDispatcher::handleReceiveCallback方法。

对于应用程序注册Channel的场景,就会调用NativeInputEventReceiver::handleEvent方法。

关于这两个方法的实现,之后再做介绍。

下一步,先分析Input子系统的事件处理过程。

4. Input子系统的事件处理流程

在Input子系统的初始化过程,启动了两个线程InputReaderThread和InputDispatcherThread,并进入到它们的线程执行函数threadLoop中。当没有事件发生时,InputReader等待底层的事件输入,InputDispatcher等待InputReder的通知,都在睡眠。一旦有事件产生,整个过程就动起来了。下面我们分析这个过程。

分几个部分介绍:

1. InputReader处理

2. InputDispatcher处理

4.1 InputReader处理

先看线程的处理函数

[html]  view plain copy 在CODE上查看代码片 派生到我的代码片
  1. bool InputReaderThread::threadLoop() {  
  2.     mReader->loopOnce();  
  3.     return true;  
  4. }  

[html]  view plain copy 在CODE上查看代码片 派生到我的代码片
  1. void InputReader::loopOnce() {  
  2.     int32_t oldGeneration;  
  3.     int32_t timeoutMillis;  
  4.     bool inputDevicesChanged = false;  
  5.     Vector<InputDeviceInfo> inputDevices;  
  6.     { // acquire lock  
  7.         AutoMutex _l(mLock);  
  8.   
  9.         oldGeneration = mGeneration;  
  10.         timeoutMillis = -1;  
  11.   
  12.         uint32_t changes = mConfigurationChangesToRefresh;  
  13.         if (changes) {  
  14.             mConfigurationChangesToRefresh = 0;  
  15.             timeoutMillis = 0;  
  16.             refreshConfigurationLocked(changes);  
  17.         } else if (mNextTimeout != LLONG_MAX) {  
  18.             nsecs_t now = systemTime(SYSTEM_TIME_MONOTONIC);  
  19.             timeoutMillis = toMillisecondTimeoutDelay(now, mNextTimeout);  
  20.         }  
  21.     } // release lock  
  22.   
  23.     size_t count = mEventHub->getEvents(timeoutMillis, mEventBuffer, EVENT_BUFFER_SIZE);  
  24.   
  25.     { // acquire lock  
  26.         AutoMutex _l(mLock);  
  27.         mReaderIsAliveCondition.broadcast();  
  28.   
  29.         if (count) {  
  30.             processEventsLocked(mEventBuffer, count);  
  31.         }  
  32.   
  33.         if (mNextTimeout != LLONG_MAX) {  
  34.             nsecs_t now = systemTime(SYSTEM_TIME_MONOTONIC);  
  35.             if (now >= mNextTimeout) {  
  36. #if DEBUG_RAW_EVENTS  
  37.                 ALOGD("Timeout expired, latency=%0.3fms", (now - mNextTimeout) * 0.000001f);  
  38. #endif  
  39.                 mNextTimeout = LLONG_MAX;  
  40.                 timeoutExpiredLocked(now);  
  41.             }  
  42.         }  
  43.   
  44.         if (oldGeneration != mGeneration) {  
  45.             inputDevicesChanged = true;  
  46.             getInputDevicesLocked(inputDevices);  
  47.         }  
  48.     } // release lock  
  49.   
  50.     // Send out a message that the describes the changed input devices.  
  51.     if (inputDevicesChanged) {  
  52.         mPolicy->notifyInputDevicesChanged(inputDevices);  
  53.     }  
  54.   
  55.     // Flush queued events out to the listener.  
  56.     // This must happen outside of the lock because the listener could potentially call  
  57.     // back into the InputReader's methods, such as getScanCodeState, or become blocked  
  58.     // on another thread similarly waiting to acquire the InputReader lock thereby  
  59.     // resulting in a deadlock.  This situation is actually quite plausible because the  
  60.     // listener is actually the input dispatcher, which calls into the window manager,  
  61.     // which occasionally calls into the input reader.  
  62.     mQueuedListener->flush();  
  63. }  

nputReaderThread线程会不民地循环调用InputReader.pollOnce函数来读入事件,而实际的事件读入操作是由EventHub.getEvent函数来进行的。如果当前没有事件发生,InputReaderThread线程就会睡眠在EventHub.getEvent函数上,而当事件发生后,就会执行processEventsLocked函数进一步处理。

[html]  view plain copy 在CODE上查看代码片 派生到我的代码片
  1. void InputReader::processEventsLocked(const RawEvent* rawEvents, size_t count) {  
  2.     for (const RawEvent* rawEvent = rawEvents; count;) {  
  3.         int32_t type = rawEvent->type;  
  4.         size_t batchSize = 1;  
  5.         if (type < EventHubInterface::FIRST_SYNTHETIC_EVENT) {  
  6.             int32_t deviceId = rawEvent->deviceId;  
  7.             while (batchSize < count) {  
  8.                 if (rawEvent[batchSize].type >= EventHubInterface::FIRST_SYNTHETIC_EVENT  
  9.                         || rawEvent[batchSize].deviceId != deviceId) {  
  10.                     break;  
  11.                 }  
  12.                 batchSize += 1;  
  13.             }  
  14. #if DEBUG_RAW_EVENTS  
  15.             ALOGD("BatchSize: %d Count: %d", batchSize, count);  
  16. #endif  
  17.             processEventsForDeviceLocked(deviceId, rawEvent, batchSize);  
  18.         } else {  
  19.             switch (rawEvent->type) {  
  20.             case EventHubInterface::DEVICE_ADDED:  
  21.                 addDeviceLocked(rawEvent->when, rawEvent->deviceId);  
  22.                 break;  
  23.             case EventHubInterface::DEVICE_REMOVED:  
  24.                 removeDeviceLocked(rawEvent->when, rawEvent->deviceId);  
  25.                 break;  
  26.             case EventHubInterface::FINISHED_DEVICE_SCAN:  
  27.                 handleConfigurationChangedLocked(rawEvent->when);  
  28.                 break;  
  29.             default:  
  30.                 ALOG_ASSERT(false); // can't happen  
  31.                 break;  
  32.             }  
  33.         }  
  34.         count -batchSize;  
  35.         rawEvent += batchSize;  
  36.     }  
  37. }  

  1.当EventHub尚未打开input系统eventXX设备时,InputReader去向EventHub获取事件时,EventHub会首先去打开所有的设备,并将每个设备信息以RawEvent的形式返给InputReader,也就是processEventsLocked()中处理的EventHubInterface::DEVICE_ADDED类型,该过程会根据每个设备的deviceId去创建InputDevice,并根据设备的classes来创建对应的InputMapper。

2.当所有的设备均被打开之后,InputReader去向EventHub获取事件时,EventHub回去轮询event节点,如果有事件,则会调用processEventsForDeviceLocked进行下一步的处理。

[html]  view plain copy 在CODE上查看代码片 派生到我的代码片
  1. void InputReader::processEventsForDeviceLocked(int32_t deviceId,  
  2.         const RawEvent* rawEvents, size_t count) {  
  3.     ssize_t deviceIndex = mDevices.indexOfKey(deviceId);  
  4.     if (deviceIndex < 0) {  
  5.         ALOGW("Discarding event for unknown deviceId %d.", deviceId);  
  6.         return;  
  7.     }  
  8.   
  9.     InputDevice* device = mDevices.valueAt(deviceIndex);  
  10.     if (device->isIgnored()) {  
  11.         //ALOGD("Discarding event for ignored deviceId %d.", deviceId);  
  12.         return;  
  13.     }  
  14.   
  15.     device->process(rawEvents, count);  
  16. }  

[html]  view plain copy 在CODE上查看代码片 派生到我的代码片
  1. void InputDevice::process(const RawEvent* rawEvents, size_t count) {  
  2.     // Process all of the events in order for each mapper.  
  3.     // We cannot simply ask each mapper to process them in bulk because mappers may  
  4.     // have side-effects that must be interleaved.  For example, joystick movement events and  
  5.     // gamepad button presses are handled by different mappers but they should be dispatched  
  6.     // in the order received.  
  7.     size_t numMappers = mMappers.size();  
  8.     for (const RawEvent* rawEvent = rawEvents; count--; rawEvent++) {  
  9. #if DEBUG_RAW_EVENTS  
  10.         ALOGD("Input event: device=%d type=0x%04x code=0x%04x value=0x%08x when=%lld",  
  11.                 rawEvent->deviceId, rawEvent->type, rawEvent->code, rawEvent->value,  
  12.                 rawEvent->when);  
  13. #endif  
  14.   
  15.         if (mDropUntilNextSync) {  
  16.             if (rawEvent->type == EV_SYN && rawEvent->code == SYN_REPORT) {  
  17.                 mDropUntilNextSync = false;  
  18. #if DEBUG_RAW_EVENTS  
  19.                 ALOGD("Recovered from input event buffer overrun.");  
  20. #endif  
  21.             } else {  
  22. #if DEBUG_RAW_EVENTS  
  23.                 ALOGD("Dropped input event while waiting for next input sync.");  
  24. #endif  
  25.             }  
  26.         } else if (rawEvent->type == EV_SYN && rawEvent->code == SYN_DROPPED) {  
  27.             ALOGI("Detected input event buffer overrun for device %s.", getName().string());  
  28.             mDropUntilNextSync = true;  
  29.             reset(rawEvent->when);  
  30.         } else {  
  31.             for (size_t i = 0; i < numMappers; i++) {  
  32.                 InputMapper* mapper = mMappers[i];  
  33.                 mapper->process(rawEvent);  
  34.             }  
  35.         }  
  36.     }  
  37. }  

这里主要是调用  mapper->process,mapper相关的信息保存在mMappers数组中,InputReader 会利用它 来管理所收到的 input event, 这些mapper   SwitchInputMapper, VibratorInputMapper, KeyboardInputMapper, CursorInputMapper, TouchInputMapper, SingleTouchInputMapper, MultiTouchInputMapper, JoystickInputMapper 等等

这些mapper是什么时候创建并添加到数组中的?主要是在DEVICE_ADDED时添加进去的。调用过程大致如下:

InputReader.cpp

processEventsLocked

    -》addDeviceLocked

        -》createDeviceLocked

            -》 device = new InputDevice

                 device->addMapper

具体过程不做细致的分析了,总之,InputReader维护了mDevices和mMappers,到有事件发生时,InputReader会遍历所有的mapper,并调用对应的process方法。

本文主要讲解hard key(比如power,home,back,menu, volume up down等),对应的mapper是KeyboardInputMapper。所以事件到来时,会调用KeyboardInputMapper的process方法。

[html]  view plain copy 在CODE上查看代码片 派生到我的代码片
  1. void KeyboardInputMapper::process(const RawEvent* rawEvent) {  
  2.     switch (rawEvent->type) {  
  3.     case EV_KEY: {  
  4.         int32_t scanCode = rawEvent->code;  
  5.         int32_t usageCode = mCurrentHidUsage;  
  6.         mCurrentHidUsage = 0;  
  7.   
  8.         if (isKeyboardOrGamepadKey(scanCode)) {  
  9.             int32_t keyCode;  
  10.             uint32_t flags;  
  11.             if (getEventHub()->mapKey(getDeviceId(), scanCode, usageCode, &keyCode, &flags)) {  
  12.                 keyCode = AKEYCODE_UNKNOWN;  
  13.                 flags = 0;  
  14.             }  
  15.             processKey(rawEvent->when, rawEvent->value != 0, keyCode, scanCode, flags);  
  16.         }  
  17.         break;  
  18.     }  
  19.     case EV_MSC: {  
  20.         if (rawEvent->code == MSC_SCAN) {  
  21.             mCurrentHidUsage = rawEvent->value;  
  22.         }  
  23.         break;  
  24.     }  
  25.     case EV_SYN: {  
  26.         if (rawEvent->code == SYN_REPORT) {  
  27.             mCurrentHidUsage = 0;  
  28.         }  
  29.     }  
  30.     }  

这里的主要处理语句是processKey。

[html]  view plain copy 在CODE上查看代码片 派生到我的代码片
  1. void KeyboardInputMapper::processKey(nsecs_t when, bool down, int32_t keyCode,  
  2.         int32_t scanCode, uint32_t policyFlags) {  
  3.   
  4.     if (down) {  
  5.         // Rotate key codes according to orientation if needed.  
  6.         if (mParameters.orientationAware && mParameters.hasAssociatedDisplay) {  
  7.             keyCode = rotateKeyCode(keyCode, mOrientation);  
  8.         }  
  9.   
  10.         // Add key down.  
  11.         ssize_t keyDownIndex = findKeyDown(scanCode);  
  12.         if (keyDownIndex >= 0) {  
  13.             // key repeat, be sure to use same keycode as before in case of rotation  
  14.             keyCode = mKeyDowns.itemAt(keyDownIndex).keyCode;  
  15.         } else {  
  16.             // key down  
  17.             if ((policyFlags & POLICY_FLAG_VIRTUAL)  
  18.                     && mContext->shouldDropVirtualKey(when,  
  19.                             getDevice(), keyCode, scanCode)) {  
  20.                 return;  
  21.             }  
  22.   
  23.             mKeyDowns.push();  
  24.             KeyDown& keyDown = mKeyDowns.editTop();  
  25.             keyDown.keyCode = keyCode;  
  26.             keyDown.scanCode = scanCode;  
  27.         }  
  28.   
  29.         mDownTime = when;  
  30.     } else {  
  31.         // Remove key down.  
  32.         ssize_t keyDownIndex = findKeyDown(scanCode);  
  33.         if (keyDownIndex >= 0) {  
  34.             // key up, be sure to use same keycode as before in case of rotation  
  35.             keyCode = mKeyDowns.itemAt(keyDownIndex).keyCode;  
  36.             mKeyDowns.removeAt(size_t(keyDownIndex));  
  37.         } else {  
  38.             // key was not actually down  
  39.             ALOGI("Dropping key up from device %s because the key was not down.  "  
  40.                     "keyCode=%d, scanCode=%d",  
  41.                     getDeviceName().string(), keyCode, scanCode);  
  42.             return;  
  43.         }  
  44.     }  
  45.   
  46.     int32_t oldMetaState = mMetaState;  
  47.     int32_t newMetaState = updateMetaState(keyCode, down, oldMetaState);  
  48.     bool metaStateChanged = oldMetaState != newMetaState;  
  49.     if (metaStateChanged) {  
  50.         mMetaState = newMetaState;  
  51.         updateLedState(false);  
  52.     }  
  53.   
  54.     nsecs_t downTime = mDownTime;  
  55.   
  56.     // Key down on external an keyboard should wake the device.  
  57.     // We don't do this for internal keyboards to prevent them from waking up in your pocket.  
  58.     // For internal keyboards, the key layout file should specify the policy flags for  
  59.     // each wake key individually.  
  60.     // TODO: Use the input device configuration to control this behavior more finely.  
  61.     if (down && getDevice()->isExternal()  
  62.             && !(policyFlags & (POLICY_FLAG_WAKE | POLICY_FLAG_WAKE_DROPPED))) {  
  63.         policyFlags |= POLICY_FLAG_WAKE_DROPPED;  
  64.     }  
  65.   
  66.     if (metaStateChanged) {  
  67.         getContext()->updateGlobalMetaState();  
  68.     }  
  69.   
  70.     if (down && !isMetaKey(keyCode)) {  
  71.         getContext()->fadePointer();  
  72.     }  
  73.   
  74.     NotifyKeyArgs args(when, getDeviceId(), mSource, policyFlags,  
  75.             down ? AKEY_EVENT_ACTION_DOWN : AKEY_EVENT_ACTION_UP,  
  76.             AKEY_EVENT_FLAG_FROM_SYSTEM, keyCode, scanCode, newMetaState, downTime);  
  77.     getListener()->notifyKey(&args);  
  78. }  

这个函数首先对对按键作一些处理,例如,当某一个DPAD键被按下时,根据当时屏幕方向的不同,它所表示的意义也不同,因此,这里需要根据当时屏幕的方向来调整键盘码,如果这个键是一直按着不放的,不管屏幕的方向如何,必须保证后面的键盘码和前面的一样,如果是第一次按下某个键,还必须把它保存在mLocked.keyDowns里面,就是为了处理上面讲的当这个键盘一直按着不放的时候屏幕方向发生改变的情况。如果是松开键盘上的某个键,就把它从mLocked.keyDowns里面删除。

最后,调用getListener()->notifyKey通知InputDispatcher,有key事件发生了。

getListener()->notifyKey如何通知InputDispatcher?下面分析这一过程。

InputManager在构造的时候会创建InputReader。

[html]  view plain copy 在CODE上查看代码片 派生到我的代码片
  1. mReader = new InputReader(eventHub, readerPolicy, mDispatcher);  

此时,mDispatcher的作为参数传递给Reader

[html]  view plain copy 在CODE上查看代码片 派生到我的代码片
  1. mQueuedListener = new QueuedInputListener(listener);  
mQueuedListener有一个成员mInnerListener指向dispatcher。

再来看一下NotifyArgs,它用来描述输入事件,根据不同的输入事件类型,也存在几个派生的NotifyArgs,比如NotifyKeyArgs,NotifyMotionArgs,NotifySwitchArgs等等,这里使用的是NotifyKeyArgs。

再来看一下getListener的实现。

[html]  view plain copy 在CODE上查看代码片 派生到我的代码片
  1. InputListenerInterface* InputReader::ContextImpl::getListener() {  
  2.     return mReader->mQueuedListener.get();  
  3. }  
由于mQueuedListener是sp,所以使用了get方法,这里不做介绍了,作用就是取得QueuedInputListener实例。

接着调用QueuedInputListener的notifyKey,传入的参数是创建的NotifyKeyArgs的地址。

[html]  view plain copy 在CODE上查看代码片 派生到我的代码片
  1. void QueuedInputListener::notifyKey(const NotifyKeyArgs* args) {  
  2.     mArgsQueue.push(new NotifyKeyArgs(*args));  
  3. }  

这里重新构造了一个NotifyKeyArgs,并push到QueuedInputListener的成员mArgsQueue向量里。

这个过程执行完之后,返回到InputReader::loopOnce的最后一条语句mQueuedListener->flush();

[html]  view plain copy 在CODE上查看代码片 派生到我的代码片
  1. void InputReader::loopOnce() {  
  2.     int32_t oldGeneration;  
  3.     int32_t timeoutMillis;  
  4.     bool inputDevicesChanged = false;  
  5.     Vector<InputDeviceInfo> inputDevices;  
  6.     { // acquire lock  
  7.         AutoMutex _l(mLock);  
  8.   
  9.         oldGeneration = mGeneration;  
  10.         timeoutMillis = -1;  
  11.   
  12.         uint32_t changes = mConfigurationChangesToRefresh;  
  13.         if (changes) {  
  14.             mConfigurationChangesToRefresh = 0;  
  15.             timeoutMillis = 0;  
  16.             refreshConfigurationLocked(changes);  
  17.         } else if (mNextTimeout != LLONG_MAX) {  
  18.             nsecs_t now = systemTime(SYSTEM_TIME_MONOTONIC);  
  19.             timeoutMillis = toMillisecondTimeoutDelay(now, mNextTimeout);  
  20.         }  
  21.     } // release lock  
  22.   
  23.     size_t count = mEventHub->getEvents(timeoutMillis, mEventBuffer, EVENT_BUFFER_SIZE);  
  24.   
  25.     { // acquire lock  
  26.         AutoMutex _l(mLock);  
  27.         mReaderIsAliveCondition.broadcast();  
  28.   
  29.         if (count) {  
  30.             processEventsLocked(mEventBuffer, count);  
  31.         }  
  32.        ......  
  33.   
  34.     // Flush queued events out to the listener.  
  35.     // This must happen outside of the lock because the listener could potentially call  
  36.     // back into the InputReader's methods, such as getScanCodeState, or become blocked  
  37.     // on another thread similarly waiting to acquire the InputReader lock thereby  
  38.     // resulting in a deadlock.  This situation is actually quite plausible because the  
  39.     // listener is actually the input dispatcher, which calls into the window manager,  
  40.     // which occasionally calls into the input reader.  
  41.     mQueuedListener->flush();  
  42. }  

[html]  view plain copy 在CODE上查看代码片 派生到我的代码片
  1. void QueuedInputListener::flush() {  
  2.     size_t count = mArgsQueue.size();  
  3.     for (size_t i = 0; i < count; i++) {  
  4.         NotifyArgs* args = mArgsQueue[i];  
  5.         args->notify(mInnerListener);  
  6.         delete args;  
  7.     }  
  8.     mArgsQueue.clear();  
  9. }  
这里有个循环,用来取得 QueuedInputListener的mArgsQueue里的事件描述参数(这时之前push的),然后逐个调用NotifyArgs各个派生对象的notify方法。注意这里的参数是mInnerListener,其实指向dispatcher。

Key Event会调用NotifyKeyArgs::notify

[html]  view plain copy 在CODE上查看代码片 派生到我的代码片
  1. void NotifyKeyArgs::notify(const sp<InputListenerInterface>& listener) const {  
  2.     listener->notifyKey(this);  
  3. }  

这里就会调用InputDispatcher的notifykey,参数是NotifyKeyArgs。

这样就把事件通知给了dispathcer。

下一步分析dispatcher的处理流程。

4.2 InputDispatcher处理

[html]  view plain copy 在CODE上查看代码片 派生到我的代码片
  1. void InputDispatcher::notifyKey(const NotifyKeyArgs* args) {  
  2. #if DEBUG_INBOUND_EVENT_DETAILS  
  3.     ALOGD("notifyKey - eventTime=%lld, deviceId=%d, source=0x%x, policyFlags=0x%x, action=0x%x, "  
  4.             "flags=0x%x, keyCode=0x%x, scanCode=0x%x, metaState=0x%x, downTime=%lld",  
  5.             args->eventTime, args->deviceId, args->source, args->policyFlags,  
  6.             args->action, args->flags, args->keyCode, args->scanCode,  
  7.             args->metaState, args->downTime);  
  8. #endif  
  9.     if (!validateKeyEvent(args->action)) {  
  10.         return;  
  11.     }  
  12.   
  13.     uint32_t policyFlags = args->policyFlags;  
  14.     int32_t flags = args->flags;  
  15.     int32_t metaState = args->metaState;  
  16.     if ((policyFlags & POLICY_FLAG_VIRTUAL) || (flags & AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY)) {  
  17.         policyFlags |= POLICY_FLAG_VIRTUAL;  
  18.         flags |= AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY;  
  19.     }  
  20.     if (policyFlags & POLICY_FLAG_ALT) {  
  21.         metaState |= AMETA_ALT_ON | AMETA_ALT_LEFT_ON;  
  22.     }  
  23.     if (policyFlags & POLICY_FLAG_ALT_GR) {  
  24.         metaState |= AMETA_ALT_ON | AMETA_ALT_RIGHT_ON;  
  25.     }  
  26.     if (policyFlags & POLICY_FLAG_SHIFT) {  
  27.         metaState |= AMETA_SHIFT_ON | AMETA_SHIFT_LEFT_ON;  
  28.     }  
  29.     if (policyFlags & POLICY_FLAG_CAPS_LOCK) {  
  30.         metaState |= AMETA_CAPS_LOCK_ON;  
  31.     }  
  32.     if (policyFlags & POLICY_FLAG_FUNCTION) {  
  33.         metaState |= AMETA_FUNCTION_ON;  
  34.     }  
  35.   
  36.     policyFlags |= POLICY_FLAG_TRUSTED;  
  37.   
  38.     KeyEvent event;  
  39.     event.initialize(args->deviceId, args->source, args->action,  
  40.             flags, args->keyCode, args->scanCode, metaState, 0,  
  41.             args->downTime, args->eventTime);  
  42.   
  43.     mPolicy->interceptKeyBeforeQueueing(&event, /*byref*/ policyFlags);  
  44.   
  45.     if (policyFlags & POLICY_FLAG_WOKE_HERE) {  
  46.         flags |= AKEY_EVENT_FLAG_WOKE_HERE;  
  47.     }  
  48.   
  49.     bool needWake;  
  50.     { // acquire lock  
  51.         mLock.lock();  
  52.   
  53.         if (shouldSendKeyToInputFilterLocked(args)) {  
  54.             mLock.unlock();  
  55.   
  56.             policyFlags |= POLICY_FLAG_FILTERED;  
  57.             if (!mPolicy->filterInputEvent(&event, policyFlags)) {  
  58.                 return; // event was consumed by the filter  
  59.             }  
  60.   
  61.             mLock.lock();  
  62.         }  
  63.   
  64.         int32_t repeatCount = 0;  
  65.         KeyEntry* newEntry = new KeyEntry(args->eventTime,  
  66.                 args->deviceId, args->source, policyFlags,  
  67.                 args->action, flags, args->keyCode, args->scanCode,  
  68.                 metaState, repeatCount, args->downTime);  
  69.   
  70.         needWake = enqueueInboundEventLocked(newEntry);  
  71.         mLock.unlock();  
  72.     } // release lock  
  73.   
  74.     if (needWake) {  
  75.         mLooper->wake();  
  76.     }  
  77. }  

函数首先是调用validateKeyEvent函数来验证action参数是否正确。正确的action参数的值只能为AKEY_EVENT_ACTION_DOWN(按下)或者AKEY_EVENT_ACTION_UP(松开)。

另外,InputDispatcher会截取这个按键事件,根据当前设备的状况来优先消化这个事件,这个过程当然是在将事件dispatch给ViewRoot之前。最终该过程交由interceptKeyBeforeQueueing()@PhoneWindowManager.java来处理。interceptKeyBeforeQueueing()主要是对一些特殊案件的特殊处理,并判断该按键是够应该传递给ViewRoot。通过设置标志位policyFlags的值来判断是否给ViewRoot,例如policyFlags&POLICY_FLAG_PASS_TO_USER == 1 则应该传递给ViewRoot。

 interceptKeyBeforeQueueing()特殊处理主要是针对在锁屏或者屏幕不亮的情况的下收到特殊的键值,如音量键或者wake键。wake键是指能够点亮屏幕的键时的操作。

下面再分析一下mPolicy->interceptKeyBeforeQueueing(&event, /*byref*/ policyFlags);是如何调用到interceptKeyBeforeQueueing()@PhoneWindowManager.java。
这里的mPolicy实际上是NativeInputManager的引用,是在NativeInputManager构造过程中创建InputManager时作为参数最终传递给InputDispatcher的成员mPolicy的。
所以执行下面的过程:
[html]  view plain copy 在CODE上查看代码片 派生到我的代码片
  1. void NativeInputManager::interceptKeyBeforeQueueing(const KeyEvent* keyEvent,  
  2.         uint32_t& policyFlags) {  
  3.     // Policy:  
  4.     // - Ignore untrusted events and pass them along.  
  5.     // - Ask the window manager what to do with normal events and trusted injected events.  
  6.     // - For normal events wake and brighten the screen if currently off or dim.  
  7.     if ((policyFlags & POLICY_FLAG_TRUSTED)) {  
  8.         nsecs_t when = keyEvent->getEventTime();  
  9.         bool isScreenOn = this->isScreenOn();  
  10.         bool isScreenBright = this->isScreenBright();  
  11.   
  12.         JNIEnv* env = jniEnv();  
  13.         jobject keyEventObj = android_view_KeyEvent_fromNative(env, keyEvent);  
  14.         jint wmActions;  
  15.         if (keyEventObj) {  
  16.             wmActions = env->CallIntMethod(mServiceObj,  
  17.                     gServiceClassInfo.interceptKeyBeforeQueueing,  
  18.                     keyEventObj, policyFlags, isScreenOn);  
  19.             if (checkAndClearExceptionFromCallback(env, "interceptKeyBeforeQueueing")) {  
  20.                 wmActions = 0;  
  21.             }  
  22.             android_view_KeyEvent_recycle(env, keyEventObj);  
  23.             env->DeleteLocalRef(keyEventObj);  
  24.         } else {  
  25.             ALOGE("Failed to obtain key event object for interceptKeyBeforeQueueing.");  
  26.             wmActions = 0;  
  27.         }  
  28.   
  29.         if (!(policyFlags & POLICY_FLAG_INJECTED)) {  
  30.             if (!isScreenOn) {  
  31.                 policyFlags |= POLICY_FLAG_WOKE_HERE;  
  32.             }  
  33.   
  34.             if (!isScreenBright) {  
  35.                 policyFlags |= POLICY_FLAG_BRIGHT_HERE;  
  36.             }  
  37.         }  
  38.   
  39.         handleInterceptActions(wmActions, when, /*byref*/ policyFlags);  
  40.     } else {  
  41.         policyFlags |= POLICY_FLAG_PASS_TO_USER;  
  42.     }  
  43. }  
主要处理是如下代码:
[html]  view plain copy 在CODE上查看代码片 派生到我的代码片
  1. wmActions = env->CallIntMethod(mServiceObj,  
  2.              gServiceClassInfo.interceptKeyBeforeQueueing,  
  3.              keyEventObj, policyFlags, isScreenOn);  
这里的mServiceObj实际上是InputManagerService。调用如下方法。
[html]  view plain copy 在CODE上查看代码片 派生到我的代码片
  1. private int interceptKeyBeforeQueueing(KeyEvent event, int policyFlags, boolean isScreenOn) {  
  2.     return mWindowManagerCallbacks.interceptKeyBeforeQueueing(  
  3.             event, policyFlags, isScreenOn);  
  4. }  

mWindowManagerCallbacks实际是一个InputMonitor对象,是在开机是有SystemServer调用的,
[html]  view plain copy 在CODE上查看代码片 派生到我的代码片
  1. inputManager.setWindowManagerCallbacks(wm.getInputMonitor());  
  2. inputManager.start()  
所以i接着执行InputMonitor的nterceptKeyBeforeQueueing方法
[html]  view plain copy 在CODE上查看代码片 派生到我的代码片
  1. public int interceptKeyBeforeQueueing(  
  2.         KeyEvent event, int policyFlags, boolean isScreenOn) {  
  3.     return mService.mPolicy.interceptKeyBeforeQueueing(event, policyFlags, isScreenOn);  
  4. }  
这里的mService就是WindowManagerService,mPolicy就是PhoneWindowManager。

下面再回到InputDispatcher::notifyKey的处理方法继续分析。
[html]  view plain copy 在CODE上查看代码片 派生到我的代码片
  1. if (shouldSendKeyToInputFilterLocked(args)) {  
  2.       mLock.unlock();  
  3.   
  4.       policyFlags |= POLICY_FLAG_FILTERED;  
  5.       if (!mPolicy->filterInputEvent(&event, policyFlags)) {  
  6.           return; // event was consumed by the filter  
  7.       }  
  8.   
  9.       mLock.lock();  
  10.   }  

接下来,按键马上进入第二轮处理。如果用户在Setting->Accessibility 中选择打开某些功能,比如说手势识别,Android的AccessbilityManagerService(辅助功能服务) 会创建一个 InputFilter 对象,它会检查输入的事件,根据需要可能会转换成新的Event,比如说两根手指头捏动的手势最终会变成ZOOM的event. 目前,InputManagerService 只支持一个InputFilter, 新注册的InputFilter会把老的覆盖。InputFilter 运行在SystemServer 的 ServerThread 线程里(除了绘制,窗口管理和Binder调用外,大部分的System Service 都运行在这个线程里)。而filterInput() 的调用是发生在Input Reader线程里,通过InputManagerService 里的 InputFilterHost 对象通知另外一个线程里的InputFilter 开始真正的解析工作。所以,InputReader 线程从这里结束一轮的工作,重新进入epoll_wait() 等待新的用户输入。InputFilter 的工作也分为两个步骤,首先由InputEventConsistencyVerifier 对象(InputEventConsistencyVerifier.java)对输入事件的完整性做一个检查,检查事件的ACTION_DOWN 和 ACTION_UP 是否一一配对。如果在Android Logcat 里看到过以下一些类似的打印:"ACTION_UP but key was not down." 就出自此处。接下来,进入到AccessibilityInputFilter 的 onInputEvent(),这里将把输入事件(主要是MotionEvent)进行处理,根据需要变成另外一个Event,然后通过sendInputEvent()将事件发回给InputDispatcher。最终调用到injectInputEvent() 将这个事件送入 mInBoundQueue。

其实,事件的过滤和拦截采用了策略模式机制进行不同的事件处理,由类图中的InputManager、InputFilter、PhoneWindowManager、Callbacks、InputMonitor等JAVA对象共同完成事件的过滤和拦截;Callbacks、InputMonitor主要负责回调事件的转发,InputFilter负责事件过滤请求的处理;应用可以通过InputManager对象的injectInputEvent函数完成事件的插入;PhoneWindowManager对象负责派发事件的拦截。事件的过滤请求和拦截请求流程相似,只是目的地不一样。

然后,将事件存储在一个输入队列mInboundQueue中:
[html]  view plain copy 在CODE上查看代码片 派生到我的代码片
  1. KeyEntry* newEntry = new KeyEntry(args->eventTime,  
  2.          args->deviceId, args->source, policyFlags,  
  3.          args->action, flags, args->keyCode, args->scanCode,  
  4.          metaState, repeatCount, args->downTime);  
  5.   
  6.  needWake = enqueueInboundEventLocked(newEntry);  

[html]  view plain copy 在CODE上查看代码片 派生到我的代码片
  1. bool InputDispatcher::enqueueInboundEventLocked(EventEntry* entry) {  
  2.     bool needWake = mInboundQueue.isEmpty();  
  3.     mInboundQueue.enqueueAtTail(entry);  
  4.     traceInboundQueueLengthLocked();  
  5.   
  6.     switch (entry->type) {  
  7.     case EventEntry::TYPE_KEY: {  
  8.         // Optimize app switch latency.  
  9.         // If the application takes too long to catch up then we drop all events preceding  
  10.         // the app switch key.  
  11.         KeyEntry* keyEntry = static_cast<KeyEntry*>(entry);  
  12.         if (isAppSwitchKeyEventLocked(keyEntry)) {  
  13.             if (keyEntry->action == AKEY_EVENT_ACTION_DOWN) {  
  14.                 mAppSwitchSawKeyDown = true;  
  15.             } else if (keyEntry->action == AKEY_EVENT_ACTION_UP) {  
  16.                 if (mAppSwitchSawKeyDown) {  
  17. #if DEBUG_APP_SWITCH  
  18.                     ALOGD("App switch is pending!");  
  19. #endif  
  20.                     mAppSwitchDueTime = keyEntry->eventTime + APP_SWITCH_TIMEOUT;  
  21.                     mAppSwitchSawKeyDown = false;  
  22.                     needWake = true;  
  23.                 }  
  24.             }  
  25.         }  
  26.         break;  
  27.     }  
  28.   
  29.     case EventEntry::TYPE_MOTION: {  
  30.         // Optimize case where the current application is unresponsive and the user  
  31.         // decides to touch a window in a different application.  
  32.         // If the application takes too long to catch up then we drop all events preceding  
  33.         // the touch into the other window.  
  34.         MotionEntry* motionEntry = static_cast<MotionEntry*>(entry);  
  35.         if (motionEntry->action == AMOTION_EVENT_ACTION_DOWN  
  36.                 && (motionEntry->source & AINPUT_SOURCE_CLASS_POINTER)  
  37.                 && mInputTargetWaitCause == INPUT_TARGET_WAIT_CAUSE_APPLICATION_NOT_READY  
  38.                 && mInputTargetWaitApplicationHandle != NULL) {  
  39.             int32_t displayId = motionEntry->displayId;  
  40.             int32_t x = int32_t(motionEntry->pointerCoords[0].  
  41.                     getAxisValue(AMOTION_EVENT_AXIS_X));  
  42.             int32_t y = int32_t(motionEntry->pointerCoords[0].  
  43.                     getAxisValue(AMOTION_EVENT_AXIS_Y));  
  44.             sp<InputWindowHandle> touchedWindowHandle = findTouchedWindowAtLocked(displayId, x, y);  
  45.             if (touchedWindowHandle != NULL  
  46.                     && touchedWindowHandle->inputApplicationHandle  
  47.                             != mInputTargetWaitApplicationHandle) {  
  48.                 // User touched a different application than the one we are waiting on.  
  49.                 // Flag the event, and start pruning the input queue.  
  50.                 mNextUnblockedEvent = motionEntry;  
  51.                 needWake = true;  
  52.             }  
  53.         }  
  54.         break;  
  55.     }  
  56.     }  
  57.   
  58.     return needWake;  

最后,唤醒InputDispatccherThread线程
[html]  view plain copy 在CODE上查看代码片 派生到我的代码片
  1. if (needWake) {  
  2.     mLooper->wake();  
  3. }  
其实,就是想管道中写入一个W。
[html]  view plain copy 在CODE上查看代码片 派生到我的代码片
  1. void Looper::wake() {  
  2. #if DEBUG_POLL_AND_WAKE  
  3.     ALOGD("%p ~ wake", this);  
  4. #endif  
  5.   
  6.     ssize_t nWrite;  
  7.     do {  
  8.         nWrite = write(mWakeWritePipeFd, "W", 1);  
  9.     } while (nWrite == -1 && errno == EINTR);  
  10.   
  11.     if (nWrite != 1) {  
  12.         if (errno != EAGAIN) {  
  13.             ALOGW("Could not write wake signal, errno=%d", errno);  
  14.         }  
  15.     }  
  16. }  

下面分析InputDispatcherThread的处理流程。
[html]  view plain copy 在CODE上查看代码片 派生到我的代码片
  1. bool InputDispatcherThread::threadLoop() {  
  2.     mDispatcher->dispatchOnce();  
  3.     return true;  
  4. }  

[html]  view plain copy 在CODE上查看代码片 派生到我的代码片
  1. void InputDispatcher::dispatchOnce() {  
  2.     nsecs_t nextWakeupTime = LONG_LONG_MAX;  
  3.     { // acquire lock  
  4.         AutoMutex _l(mLock);  
  5.         mDispatcherIsAliveCondition.broadcast();  
  6.   
  7.         // Run a dispatch loop if there are no pending commands.  
  8.         // The dispatch loop might enqueue commands to run afterwards.  
  9.         if (!haveCommandsLocked()) {  
  10.             dispatchOnceInnerLocked(&nextWakeupTime);  
  11.         }  
  12.   
  13.         // Run all pending commands if there are any.  
  14.         // If any commands were run then force the next poll to wake up immediately.  
  15.         if (runCommandsLockedInterruptible()) {  
  16.             nextWakeupTime = LONG_LONG_MIN;  
  17.         }  
  18.     } // release lock  
  19.   
  20.     // Wait for callback or timeout or wake.  (make sure we round up, not down)  
  21.     nsecs_t currentTime = now();  
  22.     int timeoutMillis = toMillisecondTimeoutDelay(currentTime, nextWakeupTime);  
  23.     mLooper->pollOnce(timeoutMillis);  

这里主要处理是
[html]  view plain copy 在CODE上查看代码片 派生到我的代码片
  1. void InputDispatcher::dispatchOnceInnerLocked(nsecs_t* nextWakeupTime) {  
  2.     nsecs_t currentTime = now();  
  3.   
  4.     // Reset the key repeat timer whenever we disallow key events, even if the next event  
  5.     // is not a key.  This is to ensure that we abort a key repeat if the device is just coming  
  6.     // out of sleep.  
  7.     if (!mPolicy->isKeyRepeatEnabled()) {  
  8.         resetKeyRepeatLocked();  
  9.     }  
  10.   
  11.     // If dispatching is frozen, do not process timeouts or try to deliver any new events.  
  12.     if (mDispatchFrozen) {  
  13. #if DEBUG_FOCUS  
  14.         ALOGD("Dispatch frozen.  Waiting some more.");  
  15. #endif  
  16.         return;  
  17.     }  
  18.   
  19.     // Optimize latency of app switches.  
  20.     // Essentially we start a short timeout when an app switch key (HOME / ENDCALL) has  
  21.     // been pressed.  When it expires, we preempt dispatch and drop all other pending events.  
  22.     bool isAppSwitchDue = mAppSwitchDueTime <= currentTime;  
  23.     if (mAppSwitchDueTime < *nextWakeupTime) {  
  24.         *nextWakeupTime = mAppSwitchDueTime;  
  25.     }  
  26.   
  27.     // Ready to start a new event.  
  28.     // If we don't already have a pending event, go grab one.  
  29.     if (! mPendingEvent) {  
  30.         if (mInboundQueue.isEmpty()) {  
  31.             if (isAppSwitchDue) {  
  32.                 // The inbound queue is empty so the app switch key we were waiting  
  33.                 // for will never arrive.  Stop waiting for it.  
  34.                 resetPendingAppSwitchLocked(false);  
  35.                 isAppSwitchDue = false;  
  36.             }  
  37.   
  38.             // Synthesize a key repeat if appropriate.  
  39.             if (mKeyRepeatState.lastKeyEntry) {  
  40.                 if (currentTime >= mKeyRepeatState.nextRepeatTime) {  
  41.                     mPendingEvent = synthesizeKeyRepeatLocked(currentTime);  
  42.                 } else {  
  43.                     if (mKeyRepeatState.nextRepeatTime < *nextWakeupTime) {  
  44.                         *nextWakeupTime = mKeyRepeatState.nextRepeatTime;  
  45.                     }  
  46.                 }  
  47.             }  
  48.   
  49.             // Nothing to do if there is no pending event.  
  50.             if (!mPendingEvent) {  
  51.                 return;  
  52.             }  
  53.         } else {  
  54.             // Inbound queue has at least one entry.  
  55.             mPendingEvent = mInboundQueue.dequeueAtHead();  
  56.             traceInboundQueueLengthLocked();  
  57.         }  
  58.   
  59.         // Poke user activity for this event.  
  60.         if (mPendingEvent->policyFlags & POLICY_FLAG_PASS_TO_USER) {  
  61.             pokeUserActivityLocked(mPendingEvent);  
  62.         }  
  63.   
  64.         // Get ready to dispatch the event.  
  65.         resetANRTimeoutsLocked();  
  66.     }  
  67.   
  68.     // Now we have an event to dispatch.  
  69.     // All events are eventually dequeued and processed this way, even if we intend to drop them.  
  70.     ALOG_ASSERT(mPendingEvent != NULL);  
  71.     bool done = false;  
  72.     DropReason dropReason = DROP_REASON_NOT_DROPPED;  
  73.     if (!(mPendingEvent->policyFlags & POLICY_FLAG_PASS_TO_USER)) {  
  74.         dropReason = DROP_REASON_POLICY;  
  75.     } else if (!mDispatchEnabled) {  
  76.         dropReason = DROP_REASON_DISABLED;  
  77.     }  
  78.   
  79.     if (mNextUnblockedEvent == mPendingEvent) {  
  80.         mNextUnblockedEvent = NULL;  
  81.     }  
  82.   
  83.     switch (mPendingEvent->type) {  
  84.     case EventEntry::TYPE_CONFIGURATION_CHANGED: {  
  85.      ......  
  86.         break;  
  87.     }  
  88.   
  89.     case EventEntry::TYPE_DEVICE_RESET: {  
  90.      ......  
  91.         break;  
  92.     }  
  93.   
  94.     case EventEntry::TYPE_KEY: {  
  95.         KeyEntry* typedEntry = static_cast<KeyEntry*>(mPendingEvent);  
  96.         if (isAppSwitchDue) {  
  97.             if (isAppSwitchKeyEventLocked(typedEntry)) {  
  98.                 resetPendingAppSwitchLocked(true);  
  99.                 isAppSwitchDue = false;  
  100.             } else if (dropReason == DROP_REASON_NOT_DROPPED) {  
  101.                 dropReason = DROP_REASON_APP_SWITCH;  
  102.             }  
  103.         }  
  104.         if (dropReason == DROP_REASON_NOT_DROPPED  
  105.                 && isStaleEventLocked(currentTime, typedEntry)) {  
  106.             dropReason = DROP_REASON_STALE;  
  107.         }  
  108.         if (dropReason == DROP_REASON_NOT_DROPPED && mNextUnblockedEvent) {  
  109.             dropReason = DROP_REASON_BLOCKED;  
  110.         }  
  111.         done = dispatchKeyLocked(currentTime, typedEntry, &dropReason, nextWakeupTime);  
  112.         break;  
  113.     }  
  114.   
  115.     case EventEntry::TYPE_MOTION: {  
  116.         ......  
  117.   
  118.     default:  
  119.         ALOG_ASSERT(false);  
  120.         break;  
  121.     }  
  122.   
  123.     if (done) {  
  124.         if (dropReason != DROP_REASON_NOT_DROPPED) {  
  125.             dropInboundEventLocked(mPendingEvent, dropReason);  
  126.         }  
  127.   
  128.         releasePendingEventLocked();  
  129.         *nextWakeupTime = LONG_LONG_MIN;  // force next poll to wake up immediately  
  130.     }  
  131. }  

这里涉及到事件的丢弃,并不是所有的InputReader发送来的事件我们都需要传递给应用,比如上节讲到的翻盖/滑盖事件,除此之外的按键,触屏,轨迹球(后两者统一按motion事件处理),也会有部分的事件被丢弃,InputDispatcher总会根据一些规则来丢弃掉一部分事件,我们来简单分析一下哪些情况下我们需要丢弃掉部分事件?
 InputDispatcher.h中定义了一个包含有丢弃原因的枚举:
[html]  view plain copy 在CODE上查看代码片 派生到我的代码片
  1. enum DropReason {  
  2.     DROP_REASON_NOT_DROPPED = 0,  
  3.     DROP_REASON_POLICY = 1,  
  4.     DROP_REASON_APP_SWITCH = 2,  
  5.     DROP_REASON_DISABLED = 3,  
  6.     DROP_REASON_BLOCKED = 4,  
  7.     DROP_REASON_STALE = 5,  
  8. };  
  1. DROP_REASON_NOT_DROPPED

     不需要丢弃

    2. DROP_REASON_POLICY

   设置为DROP_REASON_POLICY主要有两种情形:

    A. 在InputReader notify InputDispatcher之前,Policy会判断不需要传递给应用的事件。

    B. 在InputDispatcher dispatch事件前,PhoneWindowManager使用方法interceptKeyBeforeDispatching()提前consume掉一些按键事件。

    interceptKeyBeforeDispatching()主要对HOME/MENU/SEARCH按键的特殊处理,如果此时能被consume掉,那么在InputDispatcher 中将被丢弃。

    3.DROP_REASON_APP_SWITCH

    当有App switch 按键如HOME/ENDCALL按键发生时,当InputReader向InputDispatcher 传递app switch按键时,会设置一个APP_SWITCH_TIMEOUT 0.5S的超时时间,当0.5s超时时,InputDispatcher 尚未dispatch到这个app switch按键时,InputDispatcher 将会丢弃掉mInboundQueue中所有处在app switch按键前的按键事件。这么做的目的是保证app switch按键能够确保被处理。此时被丢弃掉的按键会被置为DROP_REASON_APP_SWITCH。

    4. DROP_REASON_DISABLED

    这个标志表示当前的InputDispatcher 被disable掉了,不能dispatch任何事件,比如当系统休眠时或者正在关机时会用到。

   5. DROP_REASON_BLOCKED

   如果事件传递后,已经进入了另外的应用,就把以前的事件丢弃。

   6.DROP_REASON_STALE 

    设置的超时是10秒。如果超过了10秒,事件没有处理掉,那么就直接丢弃。


我们主要分析事件传递到ViewRoot的过程接着往下分析。

主要的处理是dispatchKeyLocked。
[html]  view plain copy 在CODE上查看代码片 派生到我的代码片
  1. bool InputDispatcher::dispatchKeyLocked(nsecs_t currentTime, KeyEntry* entry,  
  2.         DropReason* dropReason, nsecs_t* nextWakeupTime) {  
  3.     // Preprocessing.  
  4.     if (! entry->dispatchInProgress) {  
  5.         if (entry->repeatCount == 0  
  6.                 && entry->action == AKEY_EVENT_ACTION_DOWN  
  7.                 && (entry->policyFlags & POLICY_FLAG_TRUSTED)  
  8.                 && (!(entry->policyFlags & POLICY_FLAG_DISABLE_KEY_REPEAT))) {  
  9.             if (mKeyRepeatState.lastKeyEntry  
  10.                     && mKeyRepeatState.lastKeyEntry->keyCode == entry->keyCode) {  
  11.                 // We have seen two identical key downs in a row which indicates that the device  
  12.                 // driver is automatically generating key repeats itself.  We take note of the  
  13.                 // repeat here, but we disable our own next key repeat timer since it is clear that  
  14.                 // we will not need to synthesize key repeats ourselves.  
  15.                 entry->repeatCount = mKeyRepeatState.lastKeyEntry->repeatCount + 1;  
  16.                 resetKeyRepeatLocked();  
  17.                 mKeyRepeatState.nextRepeatTime = LONG_LONG_MAX; // don't generate repeats ourselves  
  18.             } else {  
  19.                 // Not a repeat.  Save key down state in case we do see a repeat later.  
  20.                 resetKeyRepeatLocked();  
  21.                 mKeyRepeatState.nextRepeatTime = entry->eventTime + mConfig.keyRepeatTimeout;  
  22.             }  
  23.             mKeyRepeatState.lastKeyEntry = entry;  
  24.             entry->refCount += 1;  
  25.         } else if (! entry->syntheticRepeat) {  
  26.             resetKeyRepeatLocked();  
  27.         }  
  28.   
  29.         if (entry->repeatCount == 1) {  
  30.             entry->flags |= AKEY_EVENT_FLAG_LONG_PRESS;  
  31.         } else {  
  32.             entry->flags &= ~AKEY_EVENT_FLAG_LONG_PRESS;  
  33.         }  
  34.   
  35.         entry->dispatchInProgress = true;  
  36.   
  37.         logOutboundKeyDetailsLocked("dispatchKey - ", entry);  
  38.     }  
  39.   
  40.     // Handle case where the policy asked us to try again later last time.  
  41.     if (entry->interceptKeyResult == KeyEntry::INTERCEPT_KEY_RESULT_TRY_AGAIN_LATER) {  
  42.         if (currentTime < entry->interceptKeyWakeupTime) {  
  43.             if (entry->interceptKeyWakeupTime < *nextWakeupTime) {  
  44.                 *nextWakeupTime = entry->interceptKeyWakeupTime;  
  45.             }  
  46.             return false; // wait until next wakeup  
  47.         }  
  48.         entry->interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_UNKNOWN;  
  49.         entry->interceptKeyWakeupTime = 0;  
  50.     }  
  51.   
  52.     // Give the policy a chance to intercept the key.  
  53.     if (entry->interceptKeyResult == KeyEntry::INTERCEPT_KEY_RESULT_UNKNOWN) {  
  54.         if (entry->policyFlags & POLICY_FLAG_PASS_TO_USER) {  
  55.             CommandEntry* commandEntry = postCommandLocked(  
  56.                     & InputDispatcher::doInterceptKeyBeforeDispatchingLockedInterruptible);  
  57.             if (mFocusedWindowHandle != NULL) {  
  58.                 commandEntry->inputWindowHandle = mFocusedWindowHandle;  
  59.             }  
  60.             commandEntry->keyEntry = entry;  
  61.             entry->refCount += 1;  
  62.             return false; // wait for the command to run  
  63.         } else {  
  64.             entry->interceptKeyResult = KeyEntry::INTERCEPT_KEY_RESULT_CONTINUE;  
  65.         }  
  66.     } else if (entry->interceptKeyResult == KeyEntry::INTERCEPT_KEY_RESULT_SKIP) {  
  67.         if (*dropReason == DROP_REASON_NOT_DROPPED) {  
  68.             *dropReason = DROP_REASON_POLICY;  
  69.         }  
  70.     }  
  71.   
  72.     // Clean up if dropping the event.  
  73.     if (*dropReason != DROP_REASON_NOT_DROPPED) {  
  74.         setInjectionResultLocked(entry, *dropReason == DROP_REASON_POLICY  
  75.                 ? INPUT_EVENT_INJECTION_SUCCEEDED : INPUT_EVENT_INJECTION_FAILED);  
  76.         return true;  
  77.     }  
  78.   
  79.     // Identify targets.  
  80.     Vector<InputTarget> inputTargets;  
  81.     int32_t injectionResult = findFocusedWindowTargetsLocked(currentTime,  
  82.             entry, inputTargets, nextWakeupTime);  
  83.     if (injectionResult == INPUT_EVENT_INJECTION_PENDING) {  
  84.         return false;  
  85.     }  
  86.   
  87.     setInjectionResultLocked(entry, injectionResult);  
  88.     if (injectionResult != INPUT_EVENT_INJECTION_SUCCEEDED) {  
  89.         return true;  
  90.     }  
  91.   
  92.     addMonitoringTargetsLocked(inputTargets);  
  93.   
  94.     // Dispatch the key.  
  95.     dispatchEventLocked(currentTime, entry, inputTargets);  
  96.     return true;  
  97. }  
这里面又涉及到一次拦截:
[html]  view plain copy 在CODE上查看代码片 派生到我的代码片
  1. // Give the policy a chance to intercept the key.  
  2.     if (entry->interceptKeyResult == KeyEntry::INTERCEPT_KEY_RESULT_UNKNOWN) {  
  3.         if (entry->policyFlags & POLICY_FLAG_PASS_TO_USER) {  
  4.             CommandEntry* commandEntry = postCommandLocked(  
  5.                     & InputDispatcher::doInterceptKeyBeforeDispatchingLockedInterruptible);  
  6.             if (mFocusedWindowHandle != NULL) {  
  7.                 commandEntry->inputWindowHandle = mFocusedWindowHandle;  
  8.             }  
  9.             commandEntry->keyEntry = entry;  
  10.             entry->refCount += 1;  
  11.             return false; // wait for the command to run  
这里是把事件加入到command队列mCommandQueue(其实这个command队列经常会用到,这里只是其中一个场景),当再次回到InputDispatcher::dispatchOnce时,会调用runCommandsLockedInterruptible来执行拦截的处理函数。同样这里的拦截最终是由interceptKeyBeforeDispatching@PhoneWindowManager执行的。这部分不再具体分析了。

接下来会查找FocusedWindow,然后调用dispatchEventLocked。
[html]  view plain copy 在CODE上查看代码片 派生到我的代码片
  1. void InputDispatcher::dispatchEventLocked(nsecs_t currentTime,  
  2.         EventEntry* eventEntry, const Vector<InputTarget>& inputTargets) {  
  3. #if DEBUG_DISPATCH_CYCLE  
  4.     ALOGD("dispatchEventToCurrentInputTargets");  
  5. #endif  
  6.   
  7.     ALOG_ASSERT(eventEntry->dispatchInProgress); // should already have been set to true  
  8.   
  9.     pokeUserActivityLocked(eventEntry);  
  10.   
  11.     for (size_t i = 0; i < inputTargets.size(); i++) {  
  12.         const InputTarget& inputTarget = inputTargets.itemAt(i);  
  13.   
  14.         ssize_t connectionIndex = getConnectionIndexLocked(inputTarget.inputChannel);  
  15.         if (connectionIndex >= 0) {  
  16.             sp<Connection> connection = mConnectionsByFd.valueAt(connectionIndex);  
  17.             prepareDispatchCycleLocked(currentTime, connection, eventEntry, &inputTarget);  
  18.         } else {  
  19. #if DEBUG_FOCUS  
  20.             ALOGD("Dropping event delivery to target with channel '%s' because it "  
  21.                     "is no longer registered with the input dispatcher.",  
  22.                     inputTarget.inputChannel->getName().string());  
  23. #endif  
  24.         }  
  25.     }  
  26. }  
pokeUserActivityLocked主要是电源管理相关的,这里不再详细介绍,主要处理函数prepareDispatchCycleLocked

[html]  view plain copy 在CODE上查看代码片 派生到我的代码片
  1. void InputDispatcher::prepareDispatchCycleLocked(nsecs_t currentTime,  
  2.         const sp<Connection>& connection, EventEntry* eventEntry, const InputTarget* inputTarget) {  
  3. #if DEBUG_DISPATCH_CYCLE  
  4.     ALOGD("channel '%s' ~ prepareDispatchCycle - flags=0x%08x, "  
  5.             "xOffset=%f, yOffset=%f, scaleFactor=%f, "  
  6.             "pointerIds=0x%x",  
  7.             connection->getInputChannelName(), inputTarget->flags,  
  8.             inputTarget->xOffset, inputTarget->yOffset,  
  9.             inputTarget->scaleFactor, inputTarget->pointerIds.value);  
  10. #endif  
  11.   
  12.     // Skip this event if the connection status is not normal.  
  13.     // We don't want to enqueue additional outbound events if the connection is broken.  
  14.     if (connection->status != Connection::STATUS_NORMAL) {  
  15. #if DEBUG_DISPATCH_CYCLE  
  16.         ALOGD("channel '%s' ~ Dropping event because the channel status is %s",  
  17.                 connection->getInputChannelName(), connection->getStatusLabel());  
  18. #endif  
  19.         return;  
  20.     }  
  21.   
  22.     // Split a motion event if needed.  
  23.     if (inputTarget->flags & InputTarget::FLAG_SPLIT) {  
  24.         ALOG_ASSERT(eventEntry->type == EventEntry::TYPE_MOTION);  
  25.   
  26.         MotionEntry* originalMotionEntry = static_cast<MotionEntry*>(eventEntry);  
  27.         if (inputTarget->pointerIds.count() != originalMotionEntry->pointerCount) {  
  28.             MotionEntry* splitMotionEntry = splitMotionEvent(  
  29.                     originalMotionEntry, inputTarget->pointerIds);  
  30.             if (!splitMotionEntry) {  
  31.                 return; // split event was dropped  
  32.             }  
  33. #if DEBUG_FOCUS  
  34.             ALOGD("channel '%s' ~ Split motion event.",  
  35.                     connection->getInputChannelName());  
  36.             logOutboundMotionDetailsLocked("  ", splitMotionEntry);  
  37. #endif  
  38.             enqueueDispatchEntriesLocked(currentTime, connection,  
  39.                     splitMotionEntry, inputTarget);  
  40.             splitMotionEntry->release();  
  41.             return;  
  42.         }  
  43.     }  
  44.   
  45.     // Not splitting.  Enqueue dispatch entries for the event as is.  
  46.     enqueueDispatchEntriesLocked(currentTime, connection, eventEntry, inputTarget);  
  47. }  
一般情况下会执行到enqueueDispatchEntriesLocked
[html]  view plain copy 在CODE上查看代码片 派生到我的代码片
  1. void InputDispatcher::enqueueDispatchEntriesLocked(nsecs_t currentTime,  
  2.         const sp<Connection>& connection, EventEntry* eventEntry, const InputTarget* inputTarget) {  
  3.     bool wasEmpty = connection->outboundQueue.isEmpty();  
  4.   
  5.     // Enqueue dispatch entries for the requested modes.  
  6.     enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,  
  7.             InputTarget::FLAG_DISPATCH_AS_HOVER_EXIT);  
  8.     enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,  
  9.             InputTarget::FLAG_DISPATCH_AS_OUTSIDE);  
  10.     enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,  
  11.             InputTarget::FLAG_DISPATCH_AS_HOVER_ENTER);  
  12.     enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,  
  13.             InputTarget::FLAG_DISPATCH_AS_IS);  
  14.     enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,  
  15.             InputTarget::FLAG_DISPATCH_AS_SLIPPERY_EXIT);  
  16.     enqueueDispatchEntryLocked(connection, eventEntry, inputTarget,  
  17.             InputTarget::FLAG_DISPATCH_AS_SLIPPERY_ENTER);  
  18.   
  19.     // If the outbound queue was previously empty, start the dispatch cycle going.  
  20.     if (wasEmpty && !connection->outboundQueue.isEmpty()) {  
  21.         startDispatchCycleLocked(currentTime, connection);  
  22.     }  
这里会记录之前的事件队列是否为空的标志(wasEmpty),并判断新的事件是否加入到事件队列中,当条件不成立时,说明当前这个Activity窗口正在处事件了,因此,就不需要调用startDispatchCycleLocked来启动Activity窗口来处理这个事件了,因为一旦这个Activity窗口正在处事件,它就会一直处理下去,直到它里的connection对象的outboundQueue为空为止。当connection中的outboundQueue事件队列为空时,就需要调用startDispatchCycleLocked来通知这个Activity窗口来执行事件处理的流程了。
[html]  view plain copy 在CODE上查看代码片 派生到我的代码片
  1. void InputDispatcher::startDispatchCycleLocked(nsecs_t currentTime,  
  2.         const sp<Connection>& connection) {  
  3. #if DEBUG_DISPATCH_CYCLE  
  4.     ALOGD("channel '%s' ~ startDispatchCycle",  
  5.             connection->getInputChannelName());  
  6. #endif  
  7.   
  8.     while (connection->status == Connection::STATUS_NORMAL  
  9.             && !connection->outboundQueue.isEmpty()) {  
  10.         DispatchEntry* dispatchEntry = connection->outboundQueue.head;  
  11.         dispatchEntry->deliveryTime = currentTime;  
  12.   
  13.         // Publish the event.  
  14.         status_t status;  
  15.         EventEntry* eventEntry = dispatchEntry->eventEntry;  
  16.         switch (eventEntry->type) {  
  17.         case EventEntry::TYPE_KEY: {  
  18.             KeyEntry* keyEntry = static_cast<KeyEntry*>(eventEntry);  
  19.   
  20.             // Publish the key event.  
  21.             status = connection->inputPublisher.publishKeyEvent(dispatchEntry->seq,  
  22.                     keyEntry->deviceId, keyEntry->source,  
  23.                     dispatchEntry->resolvedAction, dispatchEntry->resolvedFlags,  
  24.                     keyEntry->keyCode, keyEntry->scanCode,  
  25.                     keyEntry->metaState, keyEntry->repeatCount, keyEntry->downTime,  
  26.                     keyEntry->eventTime);  
  27.             break;  
  28.         }  
  29.   
  30.         case EventEntry::TYPE_MOTION: {  
  31.             MotionEntry* motionEntry = static_cast<MotionEntry*>(eventEntry);  
  32.   
  33.             PointerCoords scaledCoords[MAX_POINTERS];  
  34.             const PointerCoords* usingCoords = motionEntry->pointerCoords;  
  35.   
  36.             // Set the X and Y offset depending on the input source.  
  37.             float xOffset, yOffset, scaleFactor;  
  38.             if ((motionEntry->source & AINPUT_SOURCE_CLASS_POINTER)  
  39.                     && !(dispatchEntry->targetFlags & InputTarget::FLAG_ZERO_COORDS)) {  
  40.                 scaleFactor = dispatchEntry->scaleFactor;  
  41.                 xOffset = dispatchEntry->xOffset * scaleFactor;  
  42.                 yOffset = dispatchEntry->yOffset * scaleFactor;  
  43.                 if (scaleFactor != 1.0f) {  
  44.                     for (size_t i = 0; i < motionEntry->pointerCount; i++) {  
  45.                         scaledCoords[i] = motionEntry->pointerCoords[i];  
  46.                         scaledCoords[i].scale(scaleFactor);  
  47.                     }  
  48.                     usingCoords = scaledCoords;  
  49.                 }  
  50.             } else {  
  51.                 xOffset = 0.0f;  
  52.                 yOffset = 0.0f;  
  53.                 scaleFactor = 1.0f;  
  54.   
  55.                 // We don't want the dispatch target to know.  
  56.                 if (dispatchEntry->targetFlags & InputTarget::FLAG_ZERO_COORDS) {  
  57.                     for (size_t i = 0; i < motionEntry->pointerCount; i++) {  
  58.                         scaledCoords[i].clear();  
  59.                     }  
  60.                     usingCoords = scaledCoords;  
  61.                 }  
  62.             }  
  63.   
  64.             // Publish the motion event.  
  65.             status = connection->inputPublisher.publishMotionEvent(dispatchEntry->seq,  
  66.                     motionEntry->deviceId, motionEntry->source,  
  67.                     dispatchEntry->resolvedAction, dispatchEntry->resolvedFlags,  
  68.                     motionEntry->edgeFlags, motionEntry->metaState, motionEntry->buttonState,  
  69.                     xOffset, yOffset,  
  70.                     motionEntry->xPrecision, motionEntry->yPrecision,  
  71.                     motionEntry->downTime, motionEntry->eventTime,  
  72.                     motionEntry->pointerCount, motionEntry->pointerProperties,  
  73.                     usingCoords);  
  74.             break;  
  75.         }  
  76.   
  77.         default:  
  78.             ALOG_ASSERT(false);  
  79.             return;  
  80.         }  
  81.   
  82.         // Check the result.  
  83.         if (status) {  
  84.             if (status == WOULD_BLOCK) {  
  85.                 if (connection->waitQueue.isEmpty()) {  
  86.                     ALOGE("channel '%s' ~ Could not publish event because the pipe is full. "  
  87.                             "This is unexpected because the wait queue is empty, so the pipe "  
  88.                             "should be empty and we shouldn't have any problems writing an "  
  89.                             "event to it, status=%d", connection->getInputChannelName(), status);  
  90.                     abortBrokenDispatchCycleLocked(currentTime, connection, true /*notify*/);  
  91.                 } else {  
  92.                     // Pipe is full and we are waiting for the app to finish process some events  
  93.                     // before sending more events to it.  
  94. #if DEBUG_DISPATCH_CYCLE  
  95.                     ALOGD("channel '%s' ~ Could not publish event because the pipe is full, "  
  96.                             "waiting for the application to catch up",  
  97.                             connection->getInputChannelName());  
  98. #endif  
  99.                     connection->inputPublisherBlocked = true;  
  100.                 }  
  101.             } else {  
  102.                 ALOGE("channel '%s' ~ Could not publish event due to an unexpected error, "  
  103.                         "status=%d", connection->getInputChannelName(), status);  
  104.                 abortBrokenDispatchCycleLocked(currentTime, connection, true /*notify*/);  
  105.             }  
  106.             return;  
  107.         }  
  108.   
  109.         // Re-enqueue the event on the wait queue.  
  110.         connection->outboundQueue.dequeue(dispatchEntry);  
  111.         traceOutboundQueueLengthLocked(connection);  
  112.         connection->waitQueue.enqueueAtTail(dispatchEntry);  
  113.         traceWaitQueueLengthLocked(connection);  
  114.     }  
  115. }  

从它的outboundQueue队列中取出当前需要处理的事件,然后调用 connection->inputPublisher.publishMotionEvent通知Channel的接收端。
[html]  view plain copy 在CODE上查看代码片 派生到我的代码片
  1. status_t InputPublisher::publishKeyEvent(  
  2.         uint32_t seq,  
  3.         int32_t deviceId,  
  4.         int32_t source,  
  5.         int32_t action,  
  6.         int32_t flags,  
  7.         int32_t keyCode,  
  8.         int32_t scanCode,  
  9.         int32_t metaState,  
  10.         int32_t repeatCount,  
  11.         nsecs_t downTime,  
  12.         nsecs_t eventTime) {  
  13.     .......  
  14.     InputMessage msg;  
  15.     msg.header.type = InputMessage::TYPE_KEY;  
  16.     msg.body.key.seq = seq;  
  17.     msg.body.key.deviceId = deviceId;  
  18.     msg.body.key.source = source;  
  19.     msg.body.key.action = action;  
  20.     msg.body.key.flags = flags;  
  21.     msg.body.key.keyCode = keyCode;  
  22.     msg.body.key.scanCode = scanCode;  
  23.     msg.body.key.metaState = metaState;  
  24.     msg.body.key.repeatCount = repeatCount;  
  25.     msg.body.key.downTime = downTime;  
  26.     msg.body.key.eventTime = eventTime;  
  27.     return mChannel->sendMessage(&msg);  
  28. }  

InputTransport.cpp
[html]  view plain copy 在CODE上查看代码片 派生到我的代码片
  1. status_t InputChannel::sendMessage(const InputMessage* msg) {  
  2.     size_t msgLength = msg->size();  
  3.     ssize_t nWrite;  
  4.     do {  
  5.         nWrite = ::send(mFd, msg, msgLength, MSG_DONTWAIT | MSG_NOSIGNAL);  
  6.     } while (nWrite == -1 && errno == EINTR);  
  7.   
  8.     if (nWrite < 0) {  
  9.         int error = errno;  
  10. #if DEBUG_CHANNEL_MESSAGES  
  11.         ALOGD("channel '%s' ~ error sending message of type %d, errno=%d", mName.string(),  
  12.                 msg->header.type, error);  
  13. #endif  
  14.         if (error == EAGAIN || error == EWOULDBLOCK) {  
  15.             return WOULD_BLOCK;  
  16.         }  
  17.         if (error == EPIPE || error == ENOTCONN || error == ECONNREFUSED || error == ECONNRESET) {  
  18.             return DEAD_OBJECT;  
  19.         }  
  20.         return -error;  
  21.     }  
  22.   
  23.     if (size_t(nWrite) != msgLength) {  
  24. #if DEBUG_CHANNEL_MESSAGES  
  25.         ALOGD("channel '%s' ~ error sending message type %d, send was incomplete",  
  26.                 mName.string(), msg->header.type);  
  27. #endif  
  28.         return DEAD_OBJECT;  
  29.     }  
  30.   
  31. #if DEBUG_CHANNEL_MESSAGES  
  32.     ALOGD("channel '%s' ~ sent message of type %d", mName.string(), msg->header.type);  
  33. #endif  
  34.     return OK;  

调用::send进行系统调用(加::是为了能够正确的调用系统中的send,避免该类中刚好也有一个 close 函数的情况),通过send发送了一个socket消息,那么一定会有另一个socket接收消息,接收消息的就是Channel的另一端——UI主线程。UI主线程一直阻塞在epoll_wait,是在Looper::pollInner中调用的。
应用程序注册InputChannel一节介绍过,当有事件到来的时候会调用哪个NativeInputEventReceiver::handleEvent方法。
[html]  view plain copy 在CODE上查看代码片 派生到我的代码片
  1. int NativeInputEventReceiver::handleEvent(int receiveFd, int events, void* data) {  
  2.     if (events & (ALOOPER_EVENT_ERROR | ALOOPER_EVENT_HANGUP)) {  
  3. #if DEBUG_DISPATCH_CYCLE  
  4.         // This error typically occurs when the publisher has closed the input channel  
  5.         // as part of removing a window or finishing an IME session, in which case  
  6.         // the consumer will soon be disposed as well.  
  7.         ALOGD("channel '%s' ~ Publisher closed input channel or an error occurred.  "  
  8.                 "events=0x%x", getInputChannelName(), events);  
  9. #endif  
  10.         return 0; // remove the callback  
  11.     }  
  12.   
  13.     if (events & ALOOPER_EVENT_INPUT) {  
  14.         JNIEnv* env = AndroidRuntime::getJNIEnv();  
  15.         status_t status = consumeEvents(env, false /*consumeBatches*/, -1);  
  16.         mMessageQueue->raiseAndClearException(env, "handleReceiveCallback");  
  17.         return status == OK || status == NO_MEMORY ? 1 : 0;  
  18.     }  
  19.   
  20.     if (events & ALOOPER_EVENT_OUTPUT) {  
  21.         for (size_t i = 0; i < mFinishQueue.size(); i++) {  
  22.             const Finish& finish = mFinishQueue.itemAt(i);  
  23.             status_t status = mInputConsumer.sendFinishedSignal(finish.seq, finish.handled);  
  24.             if (status) {  
  25.                 mFinishQueue.removeItemsAt(0, i);  
  26.   
  27.                 if (status == WOULD_BLOCK) {  
  28. #if DEBUG_DISPATCH_CYCLE  
  29.                     ALOGD("channel '%s' ~ Sent %u queued finish events; %u left.",  
  30.                             getInputChannelName(), i, mFinishQueue.size());  
  31. #endif  
  32.                     return 1; // keep the callback, try again later  
  33.                 }  
  34.   
  35.                 ALOGW("Failed to send finished signal on channel '%s'.  status=%d",  
  36.                         getInputChannelName(), status);  
  37.                 if (status != DEAD_OBJECT) {  
  38.                     JNIEnv* env = AndroidRuntime::getJNIEnv();  
  39.                     String8 message;  
  40.                     message.appendFormat("Failed to finish input event.  status=%d", status);  
  41.                     jniThrowRuntimeException(env, message.string());  
  42.                     mMessageQueue->raiseAndClearException(env, "finishInputEvent");  
  43.                 }  
  44.                 return 0; // remove the callback  
  45.             }  
  46.         }  
  47. #if DEBUG_DISPATCH_CYCLE  
  48.         ALOGD("channel '%s' ~ Sent %u queued finish events; none left.",  
  49.                 getInputChannelName(), mFinishQueue.size());  
  50. #endif  
  51.         mFinishQueue.clear();  
  52.         setFdEvents(ALOOPER_EVENT_INPUT);  
  53.         return 1;  
  54.     }  
  55.   
  56.     ALOGW("channel '%s' ~ Received spurious callback for unhandled poll event.  "  
  57.             "events=0x%x", getInputChannelName(), events);  
  58.     return 1;  
  59. }  
对于输入事件的场景,主要处理是consumeEvents。
[html]  view plain copy 在CODE上查看代码片 派生到我的代码片
  1. status_t NativeInputEventReceiver::consumeEvents(JNIEnv* env,  
  2.         bool consumeBatches, nsecs_t frameTime) {  
  3. #if DEBUG_DISPATCH_CYCLE  
  4.     ALOGD("channel '%s' ~ Consuming input events, consumeBatches=%s, frameTime=%lld.",  
  5.             getInputChannelName(), consumeBatches ? "true" : "false", frameTime);  
  6. #endif  
  7.   
  8.     if (consumeBatches) {  
  9.         mBatchedInputEventPending = false;  
  10.     }  
  11.   
  12.     ScopedLocalRef<jobject> receiverObj(env, NULL);  
  13.     bool skipCallbacks = false;  
  14.     for (;;) {  
  15.         uint32_t seq;  
  16.         InputEvent* inputEvent;  
  17.         status_t status = mInputConsumer.consume(&mInputEventFactory,  
  18.                 consumeBatches, frameTime, &seq, &inputEvent);  
  19.         if (status) {  
  20.             if (status == WOULD_BLOCK) {  
  21.                 if (!skipCallbacks && !mBatchedInputEventPending  
  22.                         && mInputConsumer.hasPendingBatch()) {  
  23.                     // There is a pending batch.  Come back later.  
  24.                     if (!receiverObj.get()) {  
  25.                         receiverObj.reset(jniGetReferent(env, mReceiverWeakGlobal));  
  26.                         if (!receiverObj.get()) {  
  27.                             ALOGW("channel '%s' ~ Receiver object was finalized "  
  28.                                     "without being disposed.", getInputChannelName());  
  29.                             return DEAD_OBJECT;  
  30.                         }  
  31.                     }  
  32.   
  33.                     mBatchedInputEventPending = true;  
  34. #if DEBUG_DISPATCH_CYCLE  
  35.                     ALOGD("channel '%s' ~ Dispatching batched input event pending notification.",  
  36.                             getInputChannelName());  
  37. #endif  
  38.                     env->CallVoidMethod(receiverObj.get(),  
  39.                             gInputEventReceiverClassInfo.dispatchBatchedInputEventPending);  
  40.                     if (env->ExceptionCheck()) {  
  41.                         ALOGE("Exception dispatching batched input events.");  
  42.                         mBatchedInputEventPending = false; // try again later  
  43.                     }  
  44.                 }  
  45.                 return OK;  
  46.             }  
  47.             ALOGE("channel '%s' ~ Failed to consume input event.  status=%d",  
  48.                     getInputChannelName(), status);  
  49.             return status;  
  50.         }  
  51.         assert(inputEvent);  
  52.   
  53.         if (!skipCallbacks) {  
  54.             if (!receiverObj.get()) {  
  55.                 receiverObj.reset(jniGetReferent(env, mReceiverWeakGlobal));  
  56.                 if (!receiverObj.get()) {  
  57.                     ALOGW("channel '%s' ~ Receiver object was finalized "  
  58.                             "without being disposed.", getInputChannelName());  
  59.                     return DEAD_OBJECT;  
  60.                 }  
  61.             }  
  62.   
  63.             jobject inputEventObj;  
  64.             switch (inputEvent->getType()) {  
  65.             case AINPUT_EVENT_TYPE_KEY:  
  66. #if DEBUG_DISPATCH_CYCLE  
  67.                 ALOGD("channel '%s' ~ Received key event.", getInputChannelName());  
  68. #endif  
  69.                 inputEventObj = android_view_KeyEvent_fromNative(env,  
  70.                         static_cast<KeyEvent*>(inputEvent));  
  71.                 break;  
  72.   
  73.             case AINPUT_EVENT_TYPE_MOTION:  
  74. #if DEBUG_DISPATCH_CYCLE  
  75.                 ALOGD("channel '%s' ~ Received motion event.", getInputChannelName());  
  76. #endif  
  77.                 inputEventObj = android_view_MotionEvent_obtainAsCopy(env,  
  78.                         static_cast<MotionEvent*>(inputEvent));  
  79.                 break;  
  80.   
  81.             default:  
  82.                 assert(false); // InputConsumer should prevent this from ever happening  
  83.                 inputEventObj = NULL;  
  84.             }  
  85.   
  86.             if (inputEventObj) {  
  87. #if DEBUG_DISPATCH_CYCLE  
  88.                 ALOGD("channel '%s' ~ Dispatching input event.", getInputChannelName());  
  89. #endif  
  90.                 env->CallVoidMethod(receiverObj.get(),  
  91.                         gInputEventReceiverClassInfo.dispatchInputEvent, seq, inputEventObj);  
  92.                 if (env->ExceptionCheck()) {  
  93.                     ALOGE("Exception dispatching input event.");  
  94.                     skipCallbacks = true;  
  95.                 }  
  96.                 env->DeleteLocalRef(inputEventObj);  
  97.             } else {  
  98.                 ALOGW("channel '%s' ~ Failed to obtain event object.", getInputChannelName());  
  99.                 skipCallbacks = true;  
  100.             }  
  101.         }  
  102.   
  103.         if (skipCallbacks) {  
  104.             mInputConsumer.sendFinishedSignal(seq, false);  
  105.         }  
  106.     }  
  107. }  
这里处理大体分3处:
1.
[html]  view plain copy 在CODE上查看代码片 派生到我的代码片
  1. status_t status = mInputConsumer.consume(&mInputEventFactory,  
  2.          consumeBatches, frameTime, &seq, &inputEvent);  
这里调用最终mChannel->receiveMessage取得从channel另一端发送过来的事件。
2.
[html]  view plain copy 在CODE上查看代码片 派生到我的代码片
  1. case AINPUT_EVENT_TYPE_KEY:  
  2. SPATCH_CYCLE  
  3.     ALOGD("channel '%s' ~ Received key event.", getInputChannelName());  
  4.   
  5.     inputEventObj = android_view_KeyEvent_fromNative(env,  
  6.             static_cast<KeyEvent*>(inputEvent));  
  7.     break;  
从native Event转换成java event
3.
[html]  view plain copy 在CODE上查看代码片 派生到我的代码片
  1. env->CallVoidMethod(receiverObj.get(),  
  2.         gInputEventReceiverClassInfo.dispatchInputEvent, seq, inputEventObj);  
调用java层对象WindowInputEventReceiver的dispatchInputEvent方法。(gInputEventReceiverClassInfo对应的对象是WindowInputEventReceiver,这时在应用程序进程注册InputChannel时调用本地方法nativeInit时注册进去的)。
WindowInputEventReceiver继承自InputEventReceiver
[html]  view plain copy 在CODE上查看代码片 派生到我的代码片
  1. private void dispatchInputEvent(int seq, InputEvent event) {  
  2.     mSeqMap.put(event.getSequenceNumber(), seq);  
  3.     onInputEvent(event);  
  4. }  
[html]  view plain copy 在CODE上查看代码片 派生到我的代码片
  1. public void onInputEvent(InputEvent event) {  
  2.     enqueueInputEvent(event, this, 0, true);  
  3. }  
[html]  view plain copy 在CODE上查看代码片 派生到我的代码片
  1. void enqueueInputEvent(InputEvent event,  
  2.         InputEventReceiver receiver, int flags, boolean processImmediately) {  
  3.     QueuedInputEvent q = obtainQueuedInputEvent(event, receiver, flags);  
  4.   
  5.     // Always enqueue the input event in order, regardless of its time stamp.  
  6.     // We do this because the application or the IME may inject key events  
  7.     // in response to touch events and we want to ensure that the injected keys  
  8.     // are processed in the order they were received and we cannot trust that  
  9.     // the time stamp of injected events are monotonic.  
  10.     QueuedInputEvent last = mPendingInputEventTail;  
  11.     if (last == null) {  
  12.         mPendingInputEventHead = q;  
  13.         mPendingInputEventTail = q;  
  14.     } else {  
  15.         last.mNext = q;  
  16.         mPendingInputEventTail = q;  
  17.     }  
  18.     mPendingInputEventCount += 1;  
  19.     Trace.traceCounter(Trace.TRACE_TAG_INPUT, mPendingInputEventQueueLengthCounterName,  
  20.             mPendingInputEventCount);  
  21.   
  22.     if (processImmediately) {  
  23.         doProcessInputEvents();  
  24.     } else {  
  25.         scheduleProcessInputEvents();  
  26.     }  
  27. }  
事件都是立即执行(processImmediately为true),接着进入到ViewRoot的事件处理流程,这里不再赘述。
以上分析的是从WMS到应用程序的过程。
下面简单分析一下从应用程序到WMS的过程。
当ViewRoot处理完事件后,都会调用finishInputEvent  ,下面就从这个函数开发分析ViewRoot-》wms的过程。
[html]  view plain copy 在CODE上查看代码片 派生到我的代码片
  1. private void finishInputEvent(QueuedInputEvent q) {  
  2.     if (q.mReceiver != null) {  
  3.         boolean handled = (q.mFlags & QueuedInputEvent.FLAG_FINISHED_HANDLED) != 0;  
  4.         q.mReceiver.finishInputEvent(q.mEvent, handled);  
  5.     } else {  
  6.         q.mEvent.recycleIfNeededAfterDispatch();  
  7.     }  
  8.   
  9.     recycleQueuedInputEvent(q);  
  10. }  

[html]  view plain copy
  1. public final void finishInputEvent(InputEvent event, boolean handled) {  
  2.     if (event == null) {  
  3.         throw new IllegalArgumentException("event must not be null");  
  4.     }  
  5.     if (mReceiverPtr == 0) {  
  6.         Log.w(TAG, "Attempted to finish an input event but the input event "  
  7.                 + "receiver has already been disposed.");  
  8.     } else {  
  9.         int index = mSeqMap.indexOfKey(event.getSequenceNumber());  
  10.         if (index < 0) {  
  11.             Log.w(TAG, "Attempted to finish an input event that is not in progress.");  
  12.         } else {  
  13.             int seq = mSeqMap.valueAt(index);  
  14.             mSeqMap.removeAt(index);  
  15.             nativeFinishInputEvent(mReceiverPtr, seq, handled);  
  16.         }  
  17.     }  
  18.     event.recycleIfNeededAfterDispatch();  
  19. }  

[html]  view plain copy
  1. static void nativeFinishInputEvent(JNIEnv* env, jclass clazz, jint receiverPtr,  
  2.         jint seq, jboolean handled) {  
  3.     sp<NativeInputEventReceiver> receiver =  
  4.             reinterpret_cast<NativeInputEventReceiver*>(receiverPtr);  
  5.     status_t status = receiver->finishInputEvent(seq, handled);  
  6.     if (status && status != DEAD_OBJECT) {  
  7.         String8 message;  
  8.         message.appendFormat("Failed to finish input event.  status=%d", status);  
  9.         jniThrowRuntimeException(env, message.string());  
  10.     }  
  11. }  

[html]  view plain copy
  1. status_t NativeInputEventReceiver::finishInputEvent(uint32_t seq, bool handled) {  
  2. #if DEBUG_DISPATCH_CYCLE  
  3.     ALOGD("channel '%s' ~ Finished input event.", getInputChannelName());  
  4. #endif  
  5.   
  6.     status_t status = mInputConsumer.sendFinishedSignal(seq, handled);  
  7.     if (status) {  
  8.         if (status == WOULD_BLOCK) {  
  9. #if DEBUG_DISPATCH_CYCLE  
  10.             ALOGD("channel '%s' ~ Could not send finished signal immediately.  "  
  11.                     "Enqueued for later.", getInputChannelName());  
  12. #endif  
  13.             Finish finish;  
  14.             finish.seq = seq;  
  15.             finish.handled = handled;  
  16.             mFinishQueue.add(finish);  
  17.             if (mFinishQueue.size() == 1) {  
  18.                 setFdEvents(ALOOPER_EVENT_INPUT | ALOOPER_EVENT_OUTPUT);  
  19.             }  
  20.             return OK;  
  21.         }  
  22.         ALOGW("Failed to send finished signal on channel '%s'.  status=%d",  
  23.                 getInputChannelName(), status);  
  24.     }  
  25.     return status;  
  26. }  

[html]  view plain copy
  1. status_t InputConsumer::sendFinishedSignal(uint32_t seq, bool handled) {  
  2. #if DEBUG_TRANSPORT_ACTIONS  
  3.     ALOGD("channel '%s' consumer ~ sendFinishedSignal: seq=%u, handled=%s",  
  4.             mChannel->getName().string(), seq, handled ? "true" : "false");  
  5. #endif  
  6.   
  7.     if (!seq) {  
  8.         ALOGE("Attempted to send a finished signal with sequence number 0.");  
  9.         return BAD_VALUE;  
  10.     }  
  11.   
  12.     // Send finished signals for the batch sequence chain first.  
  13.     size_t seqChainCount = mSeqChains.size();  
  14.     if (seqChainCount) {  
  15.         uint32_t currentSeq = seq;  
  16.         uint32_t chainSeqs[seqChainCount];  
  17.         size_t chainIndex = 0;  
  18.         for (size_t i = seqChainCount; i-- > 0; ) {  
  19.              const SeqChain& seqChain = mSeqChains.itemAt(i);  
  20.              if (seqChain.seq == currentSeq) {  
  21.                  currentSeq = seqChain.chain;  
  22.                  chainSeqs[chainIndex++] = currentSeq;  
  23.                  mSeqChains.removeAt(i);  
  24.              }  
  25.         }  
  26.         status_t status = OK;  
  27.         while (!status && chainIndex-- > 0) {  
  28.             status = sendUnchainedFinishedSignal(chainSeqs[chainIndex], handled);  
  29.         }  
  30.         if (status) {  
  31.             // An error occurred so at least one signal was not sent, reconstruct the chain.  
  32.             do {  
  33.                 SeqChain seqChain;  
  34.                 seqChain.seq = chainIndex != 0 ? chainSeqs[chainIndex - 1] : seq;  
  35.                 seqChain.chain = chainSeqs[chainIndex];  
  36.                 mSeqChains.push(seqChain);  
  37.             } while (chainIndex-- > 0);  
  38.             return status;  
  39.         }  
  40.     }  
  41.   
  42.     // Send finished signal for the last message in the batch.  
  43.     return sendUnchainedFinishedSignal(seq, handled);  
  44. }  

[html]  view plain copy
  1. status_t InputConsumer::sendUnchainedFinishedSignal(uint32_t seq, bool handled) {  
  2.     InputMessage msg;  
  3.     msg.header.type = InputMessage::TYPE_FINISHED;  
  4.     msg.body.finished.seq = seq;  
  5.     msg.body.finished.handled = handled;  
  6.     return mChannel->sendMessage(&msg);  
  7. }  
应用程序处理完事件后,最终也是通过Channel的sendMessage发送一个处理完成的Socket消息来通知channel的另一端。

在WMS注册Input Channel一节提到过,当WMS收到Socket消息后会调用handleReceiveCallback。
[html]  view plain copy
  1. int InputDispatcher::handleReceiveCallback(int fd, int events, void* data) {  
  2.     InputDispatcher* d = static_cast<InputDispatcher*>(data);  
  3.   
  4.     { // acquire lock  
  5.         AutoMutex _l(d->mLock);  
  6.   
  7.         ssize_t connectionIndex = d->mConnectionsByFd.indexOfKey(fd);  
  8.         if (connectionIndex < 0) {  
  9.             ALOGE("Received spurious receive callback for unknown input channel.  "  
  10.                     "fd=%d, events=0x%x", fd, events);  
  11.             return 0; // remove the callback  
  12.         }  
  13.   
  14.         bool notify;  
  15.         sp<Connection> connection = d->mConnectionsByFd.valueAt(connectionIndex);  
  16.         if (!(events & (ALOOPER_EVENT_ERROR | ALOOPER_EVENT_HANGUP))) {  
  17.             if (!(events & ALOOPER_EVENT_INPUT)) {  
  18.                 ALOGW("channel '%s' ~ Received spurious callback for unhandled poll event.  "  
  19.                         "events=0x%x", connection->getInputChannelName(), events);  
  20.                 return 1;  
  21.             }  
  22.   
  23.             nsecs_t currentTime = now();  
  24.             bool gotOne = false;  
  25.             status_t status;  
  26.             for (;;) {  
  27.                 uint32_t seq;  
  28.                 bool handled;  
  29.                 status = connection->inputPublisher.receiveFinishedSignal(&seq, &handled);  
  30.                 if (status) {  
  31.                     break;  
  32.                 }  
  33.                 d->finishDispatchCycleLocked(currentTime, connection, seq, handled);  
  34.                 gotOne = true;  
  35.             }  
  36.             if (gotOne) {  
  37.                 d->runCommandsLockedInterruptible();  
  38.                 if (status == WOULD_BLOCK) {  
  39.                     return 1;  
  40.                 }  
  41.             }  
  42.   
  43.             notify = status != DEAD_OBJECT || !connection->monitor;  
  44.             if (notify) {  
  45.                 ALOGE("channel '%s' ~ Failed to receive finished signal.  status=%d",  
  46.                         connection->getInputChannelName(), status);  
  47.             }  
  48.         } else {  
  49.             // Monitor channels are never explicitly unregistered.  
  50.             // We do it automatically when the remote endpoint is closed so don't warn  
  51.             // about them.  
  52.             notify = !connection->monitor;  
  53.             if (notify) {  
  54.                 ALOGW("channel '%s' ~ Consumer closed input channel or an error occurred.  "  
  55.                         "events=0x%x", connection->getInputChannelName(), events);  
  56.             }  
  57.         }  
  58.   
  59.         // Unregister the channel.  
  60.         d->unregisterInputChannelLocked(connection->inputChannel, notify);  
  61.         return 0; // remove the callback  
  62.     } // release lock  
  63. }  

最主要的处理是以下两句:
1. status = connection->inputPublisher.receiveFinishedSignal(&seq, &handled);
调用mChannel->receiveMessage用于获取消息。
2. d->finishDispatchCycleLocked(currentTime, connection, seq, handled);
[html]  view plain copy
  1. void InputDispatcher::finishDispatchCycleLocked(nsecs_t currentTime,  
  2.         const sp<Connection>& connection, uint32_t seq, bool handled) {  
  3. #if DEBUG_DISPATCH_CYCLE  
  4.     ALOGD("channel '%s' ~ finishDispatchCycle - seq=%u, handled=%s",  
  5.             connection->getInputChannelName(), seq, toString(handled));  
  6. #endif  
  7.   
  8.     connection->inputPublisherBlocked = false;  
  9.   
  10.     if (connection->status == Connection::STATUS_BROKEN  
  11.             || connection->status == Connection::STATUS_ZOMBIE) {  
  12.         return;  
  13.     }  
  14.   
  15.     // Notify other system components and prepare to start the next dispatch cycle.  
  16.     onDispatchCycleFinishedLocked(currentTime, connection, seq, handled);  
  17. }  

[html]  view plain copy
  1. void InputDispatcher::onDispatchCycleFinishedLocked(  
  2.         nsecs_t currentTime, const sp<Connection>& connection, uint32_t seq, bool handled) {  
  3.     CommandEntry* commandEntry = postCommandLocked(  
  4.             & InputDispatcher::doDispatchCycleFinishedLockedInterruptible);  
  5.     commandEntry->connection = connection;  
  6.     commandEntry->eventTime = currentTime;  
  7.     commandEntry->seq = seq;  
  8.     commandEntry->handled = handled;  
  9. }  

[html]  view plain copy
  1. void InputDispatcher::doDispatchCycleFinishedLockedInterruptible(  
  2.         CommandEntry* commandEntry) {  
  3.     sp<Connection> connection = commandEntry->connection;  
  4.     nsecs_t finishTime = commandEntry->eventTime;  
  5.     uint32_t seq = commandEntry->seq;  
  6.     bool handled = commandEntry->handled;  
  7.   
  8.     // Handle post-event policy actions.  
  9.     DispatchEntry* dispatchEntry = connection->findWaitQueueEntry(seq);  
  10.     if (dispatchEntry) {  
  11.         nsecs_t eventDuration = finishTime - dispatchEntry->deliveryTime;  
  12.         if (eventDuration > SLOW_EVENT_PROCESSING_WARNING_TIMEOUT) {  
  13.             String8 msg;  
  14.             msg.appendFormat("Window '%s' spent %0.1fms processing the last input event: ",  
  15.                     connection->getWindowName(), eventDuration * 0.000001f);  
  16.             dispatchEntry->eventEntry->appendDescription(msg);  
  17.             ALOGI("%s", msg.string());  
  18.         }  
  19.   
  20.         bool restartEvent;  
  21.         if (dispatchEntry->eventEntry->type == EventEntry::TYPE_KEY) {  
  22.             KeyEntry* keyEntry = static_cast<KeyEntry*>(dispatchEntry->eventEntry);  
  23.             restartEvent = afterKeyEventLockedInterruptible(connection,  
  24.                     dispatchEntry, keyEntry, handled);  
  25.         } else if (dispatchEntry->eventEntry->type == EventEntry::TYPE_MOTION) {  
  26.             MotionEntry* motionEntry = static_cast<MotionEntry*>(dispatchEntry->eventEntry);  
  27.             restartEvent = afterMotionEventLockedInterruptible(connection,  
  28.                     dispatchEntry, motionEntry, handled);  
  29.         } else {  
  30.             restartEvent = false;  
  31.         }  
  32.   
  33.         // Dequeue the event and start the next cycle.  
  34.         // Note that because the lock might have been released, it is possible that the  
  35.         // contents of the wait queue to have been drained, so we need to double-check  
  36.         // a few things.  
  37.         if (dispatchEntry == connection->findWaitQueueEntry(seq)) {  
  38.             connection->waitQueue.dequeue(dispatchEntry);  
  39.             traceWaitQueueLengthLocked(connection);  
  40.             if (restartEvent && connection->status == Connection::STATUS_NORMAL) {  
  41.                 connection->outboundQueue.enqueueAtHead(dispatchEntry);  
  42.                 traceOutboundQueueLengthLocked(connection);  
  43.             } else {  
  44.                 releaseDispatchEntryLocked(dispatchEntry);  
  45.             }  
  46.         }  
  47.   
  48.         // Start the next dispatch cycle for this connection.  
  49.         startDispatchCycleLocked(now(), connection);  
  50.     }  
由此可知在 InputDispatcher  一收到InputConsumer  发送的 finish message之后 就马上去呼叫 startDispatchCycleLocked  函數去檢查 outboundQueue  里面还有沒有新的input event.  若有的话就放入InputMessage  共享內存然後通知 ViewRootImpl  去共享內存抓取新的 input event.  若沒有新的 input event,  就不做事等待有新的input event 进入 outboundQueue.
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值