Android应用程序键盘(Keyboard)消息处理机制分析(一)

        在Android系统中,键盘按键事件是由WindowManagerService服务来管理的,然后再以消息的形式来分发给应用程序处理,不过和普通消息不一样,它是由硬件中断触发的;在上一篇文章《Android应用程序消息处理机制(Looper、Handler)分析》中,我们分析了Android应用程序的消息处理机制,本文将结合这种消息处理机制来详细分析Android应用程序是如何获得键盘按键消息的。


        在系统启动的时候,SystemServer会启动窗口管理服务WindowManagerService,WindowManagerService在启动的时候就会通过系统输入管理器InputManager来总负责监控键盘消息。这些键盘消息一般都是分发给当前激活的Activity窗口来处理的,因此,当前激活的Activity窗口在创建的时候,会到WindowManagerService中去注册一个接收键盘消息的通道,表明它要处理键盘消息,而当InputManager监控到有键盘消息时,就会分给给它处理。当当前激活的Activity窗口不再处于激活状态时,它也会到WindowManagerService中去反注册之前的键盘消息接收通道,这样,InputManager就不会再把键盘消息分发给它来处理。

        由于本文的内容比较多,在接下面的章节中,我们将分为五个部分来详细描述Android应用程序获得键盘按键消息的过程,每一个部分都是具体描述键盘消息处理过程中的一个过程。结合上面的键盘消息处理框架,这四个过程分别是InputManager的启动过程、应用程序注册键盘消息接收通道的过程、InputManager分发键盘消息给应用程序的过程以及应用程序注销键盘消息接收通道的过程。为了更好地理解Android应用程序获得键盘按键消息的整个过程,建议读者首先阅读Android应用程序消息处理机制(Looper、Handler)分析一文,理解了Android应用程序的消息处理机制后,就能很好的把握本文的内容。

        1. InputManager的启动过程分析 

        前面说过,Android系统的键盘事件是由InputManager来监控的,而InputManager是由窗口管理服务WindowManagerService来启动的。

        从前面一篇文章Android系统进程Zygote启动过程的源代码分析中,我们知道在Android系统中,Zygote进程负责启动系统服务进程SystemServer,而系统服务进程SystemServer负责启动系统中的各种关键服务,例如我们在前面两篇文章Android应用程序安装过程源代码分析Android系统默认Home应用程序(Launcher)的启动过程源代码分析中提到的Package管理服务PackageManagerService和Activity管理服务ActivityManagerService。这里我们所讨论的窗口管理服务WindowManagerService也是由SystemServer来启动的,具体的启动过程这里就不再详述了,具体可以参考PackageManagerService和ActivityManagerService的启动过程。

       了解了WindowManagerService的启动过程之后,我们就可以继续分析InputManager的启动过程了。我们先来看一下InputManager启动过程的序列图,然后根据这个序列图来一步步分析它的启动过程:


点击查看大图

        Step 1. WindowManagerService.main

        这个函数定义在frameworks/base/services/java/com/android/server/WindowManagerService.java文件

中:

  1. public class WindowManagerService extends IWindowManager.Stub  
  2.         implements Watchdog.Monitor {  
  3.     ......  
  4.   
  5.     public static WindowManagerService main(Context context,  
  6.             PowerManagerService pm, boolean haveInputMethods) {  
  7.         WMThread thr = new WMThread(context, pm, haveInputMethods);  
  8.         thr.start();  
  9.   
  10.         synchronized (thr) {  
  11.             while (thr.mService == null) {  
  12.                 try {  
  13.                     thr.wait();  
  14.                 } catch (InterruptedException e) {  
  15.                 }  
  16.             }  
  17.             return thr.mService;  
  18.         }  
  19.     }  
  20.   
  21.     ......  
  22. }  
        它通过一个线程WMThread实例来执行全局唯一的WindowManagerService实例的启动操作。这里调用WMThread实例thr的start成员函数时,会进入到WMThread实例thr的run函数中去。

        Step 2. WMThread.run

        这个函数定义在frameworks/base/services/java/com/android/server/WindowManagerService.java文件中:

  1. public class WindowManagerService extends IWindowManager.Stub  
  2.         implements Watchdog.Monitor {  
  3.     ......  
  4.   
  5.     static class WMThread extends Thread {  
  6.         ......  
  7.   
  8.         public void run() {  
  9.             ......  
  10.   
  11.             WindowManagerService s = new WindowManagerService(mContext, mPM,  
  12.                 mHaveInputMethods);  
  13.             ......  
  14.         }  
  15.     }  
  16.   
  17.   
  18.     ......  
  19. }  
       这里执行的主要操作就是创建一个WindowManagerService实例,这样会调用到WindowManagerService构造函数中去。

       Step 3. WindowManagerService<init>

       WindowManagerService类的构造函数定义在frameworks/base/services/java/com/android/server/WindowManagerService.java文件中:

  1. public class WindowManagerService extends IWindowManager.Stub  
  2.         implements Watchdog.Monitor {  
  3.     ......  
  4.   
  5.     final InputManager mInputManager;  
  6.   
  7.     ......  
  8.   
  9.     private WindowManagerService(Context context, PowerManagerService pm,  
  10.             boolean haveInputMethods) {  
  11.         ......  
  12.   
  13.         mInputManager = new InputManager(context, this);  
  14.   
  15.         ......  
  16.   
  17.         mInputManager.start();  
  18.   
  19.         ......  
  20.     }  
  21.   
  22.   
  23.     ......  
  24. }  
         这里我们只关心InputManager的创建过程,而忽略其它无关部分。首先是创建一个InputManager实例,然后再调用它的start成员函数来监控键盘事件。在创建InputManager实例的过程中,会执行一些初始化工作,因此,我们先进入到InputManager类的构造函数去看看,然后再回过头来分析它的start成员函数。

         Step 4. InputManager<init>@java

         Java层的InputManager类的构造函数定义在frameworks/base/services/java/com/android/server/InputManager.java文件中:

  1. public class InputManager {  
  2.     ......  
  3.   
  4.     public InputManager(Context context, WindowManagerService windowManagerService) {  
  5.         this.mContext = context;  
  6.         this.mWindowManagerService = windowManagerService;  
  7.   
  8.         this.mCallbacks = new Callbacks();  
  9.   
  10.         init();  
  11.     }  
  12.   
  13.     ......  
  14. }  
        这里只是简单地初始化InputManager类的一些成员变量,然后调用init函数进一步执行初始化操作。

        Step 5. InputManager.init

        这个函数定义在frameworks/base/services/java/com/android/server/InputManager.java文件中:

  1. public class InputManager {  
  2.     ......  
  3.   
  4.     private void init() {  
  5.         Slog.i(TAG, "Initializing input manager");  
  6.         nativeInit(mCallbacks);  
  7.     }  
  8.   
  9.     ......  
  10. }  
       函数init通过调用本地方法nativeInit来执行C++层的相关初始化操作。

       Step 6. InputManager.nativeInit

       这个函数定义在frameworks/base/services/jni$ vi com_android_server_InputManager.cpp文件中:

  1. static void android_server_InputManager_nativeInit(JNIEnv* env, jclass clazz,  
  2.         jobject callbacks) {  
  3.     if (gNativeInputManager == NULL) {  
  4.         gNativeInputManager = new NativeInputManager(callbacks);  
  5.     } else {  
  6.         LOGE("Input manager already initialized.");  
  7.         jniThrowRuntimeException(env, "Input manager already initialized.");  
  8.     }  
  9. }  
        这个函数的作用是创建一个NativeInputManager实例,并保存在gNativeInputManager变量中。由于是第一次调用到这里,因此,gNativeInputManager为NULL,于是就会new一个NativeInputManager对象出来,这样就会执行NativeInputManager类的构造函数来执其它的初始化操作。

       Step 7. NativeInputManager<init>

       NativeInputManager类的构造函数定义在frameworks/base/services/jni$ vi com_android_server_InputManager.cpp文件中:

  1. NativeInputManager::NativeInputManager(jobject callbacksObj) :  
  2.     mFilterTouchEvents(-1), mFilterJumpyTouchEvents(-1), mVirtualKeyQuietTime(-1),  
  3.     mMaxEventsPerSecond(-1),  
  4.     mDisplayWidth(-1), mDisplayHeight(-1), mDisplayOrientation(ROTATION_0) {  
  5.     JNIEnv* env = jniEnv();  
  6.   
  7.     mCallbacksObj = env->NewGlobalRef(callbacksObj);  
  8.   
  9.     sp<EventHub> eventHub = new EventHub();  
  10.     mInputManager = new InputManager(eventHub, thisthis);  
  11. }  
        这里只要是创建了一个EventHub实例,并且把这个EventHub作为参数来创建InputManager对象。注意,这里的InputManager类是定义在C++层的,和前面在Java层的InputManager不一样,不过它们是对应关系。EventHub类是真正执行监控键盘事件操作的地方,后面我们会进一步分析到,现在我们主要关心InputManager实例的创建过程,它会InputManager类的构造函数里面执行一些初始化操作。

        Step 8. InputManager<init>@C++

        C++层的InputManager类的构造函数定义在frameworks/base/libs/ui/InputManager.cpp 文件中:

  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类是负责把键盘消息分发给当前激活的Activity窗口的,而InputReader类则是通过EventHub类来实现读取键盘事件的,后面我们会进一步分析。创建了这两个对象后,还要调用initialize函数来执行其它的初始化操作。

        Step 9. InputManager.initialize

        这个函数定义在frameworks/base/libs/ui/InputManager.cpp 文件中:

  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来分发键盘消息的。

        至此,InputManager的初始化工作就完成了,在回到Step 3中继续分析InputManager的进一步启动过程之前,我们先来作一个小结,看看这个初始化过程都做什么事情:

        A. 在Java层中的WindowManagerService中创建了一个InputManager对象,由它来负责管理Android应用程序框架层的键盘消息处理;

        B. 在C++层也相应地创建一个InputManager本地对象来负责监控键盘事件;

        C. 在C++层中的InputManager对象中,分别创建了一个InputReader对象和一个InputDispatcher对象,前者负责读取系统中的键盘消息,后者负责把键盘消息分发出去;

        D. InputReader对象和一个InputDispatcher对象分别是通过InputReaderThread线程实例和InputDispatcherThread线程实例来实键盘消息的读取和分发的。

        有了这些对象之后,万事就俱备了,回到Step 3中,调用InputManager类的start函数来执行真正的启动操作。

        Step 10. InputManager.start

        这个函数定义在frameworks/base/services/java/com/android/server/InputManager.java文件中:

  1. public class InputManager {  
  2.     ......  
  3.   
  4.     public void start() {  
  5.         Slog.i(TAG, "Starting input manager");  
  6.         nativeStart();  
  7.     }  
  8.   
  9.     ......  
  10. }  
        这个函数通过调用本地方法nativeStart来执行进一步的启动操作。

        Step 11. InputManager.nativeStart

        这个函数定义在frameworks/base/services/jni$ vi com_android_server_InputManager.cpp文件中:

  1. static void android_server_InputManager_nativeStart(JNIEnv* env, jclass clazz) {  
  2.     if (checkInputManagerUnitialized(env)) {  
  3.         return;  
  4.     }  
  5.   
  6.     status_t result = gNativeInputManager->getInputManager()->start();  
  7.     if (result) {  
  8.         jniThrowRuntimeException(env, "Input manager could not be started.");  
  9.     }  
  10. }  
        这里的gNativeInputManager对象是在前面的Step 6中创建的,通过它的getInputManager函数可以返回C++层的InputManager对象,接着调用这个InputManager对象的start函数。

        Step 12. InputManager.start

        这个函数定义在frameworks/base/libs/ui/InputManager.cpp 文件中:

  1. status_t InputManager::start() {  
  2.     status_t result = mDispatcherThread->run("InputDispatcher", PRIORITY_URGENT_DISPLAY);  
  3.     if (result) {  
  4.         LOGE("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.         LOGE("Could not start InputReader thread due to error %d.", result);  
  11.   
  12.         mDispatcherThread->requestExit();  
  13.         return result;  
  14.     }  
  15.   
  16.     return OK;  
  17. }  
        这个函数主要就是分别启动一个InputDispatcherThread线程和一个InputReaderThread线程来读取和分发键盘消息的了。这里的InputDispatcherThread线程对象mDispatcherThread和InputReaderThread线程对象是在前面的Step 9中创建的,调用了它们的run函数后,就会进入到它们的threadLoop函数中去,只要threadLoop函数返回true,函数threadLoop就会一直被循环调用,于是这两个线程就起到了不断地读取和分发键盘消息的作用。

        我们先来分析InputDispatcherThread线程分发消息的过程,然后再回过头来分析InputReaderThread线程读取消息的过程。

        Step 13. InputDispatcherThread.threadLoop

        这个函数定义在frameworks/base/libs/ui/InputDispatcher.cpp文件中:

  1. bool InputDispatcherThread::threadLoop() {  
  2.     mDispatcher->dispatchOnce();  
  3.     return true;  
  4. }  
        这里的成员变量mDispatcher即为在前面Step 8中创建的InputDispatcher对象,调用它的dispatchOnce成员函数执行一次键盘消息分发的操作。

        Step 14. InputDispatcher.dispatchOnce

        这个函数定义在frameworks/base/libs/ui/InputDispatcher.cpp文件中:

  1. void InputDispatcher::dispatchOnce() {  
  2.     nsecs_t keyRepeatTimeout = mPolicy->getKeyRepeatTimeout();  
  3.     nsecs_t keyRepeatDelay = mPolicy->getKeyRepeatDelay();  
  4.   
  5.     nsecs_t nextWakeupTime = LONG_LONG_MAX;  
  6.     { // acquire lock  
  7.         AutoMutex _l(mLock);  
  8.         dispatchOnceInnerLocked(keyRepeatTimeout, keyRepeatDelay, & nextWakeupTime);  
  9.   
  10.         if (runCommandsLockedInterruptible()) {  
  11.             nextWakeupTime = LONG_LONG_MIN;  // force next poll to wake up immediately  
  12.         }  
  13.     } // release lock  
  14.   
  15.     // Wait for callback or timeout or wake.  (make sure we round up, not down)  
  16.     nsecs_t currentTime = now();  
  17.     int32_t timeoutMillis;  
  18.     if (nextWakeupTime > currentTime) {  
  19.         uint64_t timeout = uint64_t(nextWakeupTime - currentTime);  
  20.         timeout = (timeout + 999999LL) / 1000000LL;  
  21.         timeoutMillis = timeout > INT_MAX ? -1 : int32_t(timeout);  
  22.     } else {  
  23.         timeoutMillis = 0;  
  24.     }  
  25.   
  26.     mLooper->pollOnce(timeoutMillis);  
  27. }  
        这个函数很简单,把键盘消息交给dispatchOnceInnerLocked函数来处理,这个过程我们在后面再详细分析,然后调用mLooper->pollOnce函数等待下一次键盘事件的发生。这里的成员变量mLooper的类型为Looper,它定义在C++层中,具体可以参考前面 Android应用程序消息处理机制(Looper、Handler)分析 一文。

        Step 15. Looper.pollOnce

        这个函数定义在frameworks/base/libs/utils/Looper.cpp文件中,具体可以参考前面Android应用程序消息处理机制(Looper、Handler)分析一文,这里就不再详述了。总的来说,就是在Looper类中,会创建一个管道,当调用Looper类的pollOnce函数时,如果管道中没有内容可读,那么当前线程就会进入到空闲等待状态;当有键盘事件发生时,InputReader就会往这个管道中写入新的内容,这样就会唤醒前面正在等待键盘事件发生的线程。

        InputDispatcher类分发消息的过程就暂时分析到这里,后面会有更进一步的分析,现在,我们回到Step 12中,接着分析InputReader类读取键盘事件的过程。在调用了InputReaderThread线程类的run就函数后,同样会进入到InputReaderThread线程类的threadLoop函数中去。

        Step 16. InputReaderThread.threadLoop

        这个函数定义在frameworks/base/libs/ui/InputReader.cpp文件中:

  1. bool InputReaderThread::threadLoop() {  
  2.     mReader->loopOnce();  
  3.     return true;  
  4. }  
       这里的成员变量mReader即为在前面Step 8中创建的InputReader对象,调用它的loopOnce成员函数执行一次键盘事件的读取操作。

       Step 17. InputReader.loopOnce

       这个函数定义在frameworks/base/libs/ui/InputReader.cpp文件中:

  1. void InputReader::loopOnce() {  
  2.     RawEvent rawEvent;  
  3.     mEventHub->getEvent(& rawEvent);  
  4.   
  5. #if DEBUG_RAW_EVENTS  
  6.     LOGD("Input event: device=0x%x type=0x%x scancode=%d keycode=%d value=%d",  
  7.         rawEvent.deviceId, rawEvent.type, rawEvent.scanCode, rawEvent.keyCode,  
  8.         rawEvent.value);  
  9. #endif  
  10.   
  11.     process(& rawEvent);  
  12. }  
        这里通过成员函数mEventHub来负责键盘消息的读取工作,如果当前有键盘事件发生或者有键盘事件等待处理,通过mEventHub的getEvent函数就可以得到这个事件,然后交给process函数进行处理,这个函数主要就是唤醒前面的InputDispatcherThread线程,通知它有新的键盘事件发生了,它需要进行一次键盘消息的分发操作了,这个函数我们后面再进一步详细分析;如果没有键盘事件发生或者没有键盘事件等待处理,那么调用mEventHub的getEvent函数时就会进入等待状态。

        Step 18. EventHub.getEvent

        这个函数定义在frameworks/base/libs/ui/EventHub.cpp文件中:

  1. bool EventHub::getEvent(RawEvent* outEvent)  
  2. {  
  3.     outEvent->deviceId = 0;  
  4.     outEvent->type = 0;  
  5.     outEvent->scanCode = 0;  
  6.     outEvent->keyCode = 0;  
  7.     outEvent->flags = 0;  
  8.     outEvent->value = 0;  
  9.     outEvent->when = 0;  
  10.   
  11.     // Note that we only allow one caller to getEvent(), so don't need  
  12.     // to do locking here...  only when adding/removing devices.  
  13.   
  14.     if (!mOpened) {  
  15.         mError = openPlatformInput() ? NO_ERROR : UNKNOWN_ERROR;  
  16.         mOpened = true;  
  17.         mNeedToSendFinishedDeviceScan = true;  
  18.     }  
  19.   
  20.     for (;;) {  
  21.         // Report any devices that had last been added/removed.  
  22.         if (mClosingDevices != NULL) {  
  23.             device_t* device = mClosingDevices;  
  24.             LOGV("Reporting device closed: id=0x%x, name=%s\n",  
  25.                 device->id, device->path.string());  
  26.             mClosingDevices = device->next;  
  27.             if (device->id == mFirstKeyboardId) {  
  28.                 outEvent->deviceId = 0;  
  29.             } else {  
  30.                 outEvent->deviceId = device->id;  
  31.             }  
  32.             outEvent->type = DEVICE_REMOVED;  
  33.             outEvent->when = systemTime(SYSTEM_TIME_MONOTONIC);  
  34.             delete device;  
  35.             mNeedToSendFinishedDeviceScan = true;  
  36.             return true;  
  37.         }  
  38.   
  39.         if (mOpeningDevices != NULL) {  
  40.             device_t* device = mOpeningDevices;  
  41.             LOGV("Reporting device opened: id=0x%x, name=%s\n",  
  42.                 device->id, device->path.string());  
  43.             mOpeningDevices = device->next;  
  44.             if (device->id == mFirstKeyboardId) {  
  45.                 outEvent->deviceId = 0;  
  46.             } else {  
  47.                 outEvent->deviceId = device->id;  
  48.             }  
  49.             outEvent->type = DEVICE_ADDED;  
  50.             outEvent->when = systemTime(SYSTEM_TIME_MONOTONIC);  
  51.             mNeedToSendFinishedDeviceScan = true;  
  52.             return true;  
  53.         }  
  54.   
  55.         if (mNeedToSendFinishedDeviceScan) {  
  56.             mNeedToSendFinishedDeviceScan = false;  
  57.             outEvent->type = FINISHED_DEVICE_SCAN;  
  58.             outEvent->when = systemTime(SYSTEM_TIME_MONOTONIC);  
  59.             return true;  
  60.         }  
  61.   
  62.         // Grab the next input event.  
  63.         for (;;) {  
  64.             // Consume buffered input events, if any.  
  65.             if (mInputBufferIndex < mInputBufferCount) {  
  66.                 const struct input_event& iev = mInputBufferData[mInputBufferIndex++];  
  67.                 const device_t* device = mDevices[mInputDeviceIndex];  
  68.   
  69.                 LOGV("%s got: t0=%d, t1=%d, type=%d, code=%d, v=%d", device->path.string(),  
  70.                     (int) iev.time.tv_sec, (int) iev.time.tv_usec, iev.type, iev.code, iev.value);  
  71.                 if (device->id == mFirstKeyboardId) {  
  72.                     outEvent->deviceId = 0;  
  73.                 } else {  
  74.                     outEvent->deviceId = device->id;  
  75.                 }  
  76.                 outEvent->type = iev.type;  
  77.                 outEvent->scanCode = iev.code;  
  78.                 if (iev.type == EV_KEY) {  
  79.                     status_t err = device->layoutMap->map(iev.code,  
  80.                         & outEvent->keyCode, & outEvent->flags);  
  81.                     LOGV("iev.code=%d keyCode=%d flags=0x%08x err=%d\n",  
  82.                         iev.code, outEvent->keyCode, outEvent->flags, err);  
  83.                     if (err != 0) {  
  84.                         outEvent->keyCode = AKEYCODE_UNKNOWN;  
  85.                         outEvent->flags = 0;  
  86.                     }  
  87.                 } else {  
  88.                     outEvent->keyCode = iev.code;  
  89.                 }  
  90.                 outEvent->value = iev.value;  
  91.   
  92.                 // Use an event timestamp in the same timebase as  
  93.                 // java.lang.System.nanoTime() and android.os.SystemClock.uptimeMillis()  
  94.                 // as expected by the rest of the system.  
  95.                 outEvent->when = systemTime(SYSTEM_TIME_MONOTONIC);  
  96.                 return true;  
  97.             }  
  98.   
  99.             // Finish reading all events from devices identified in previous poll().  
  100.             // This code assumes that mInputDeviceIndex is initially 0 and that the  
  101.             // revents member of pollfd is initialized to 0 when the device is first added.  
  102.             // Since mFDs[0] is used for inotify, we process regular events starting at index 1.  
  103.             mInputDeviceIndex += 1;  
  104.             if (mInputDeviceIndex >= mFDCount) {  
  105.                 break;  
  106.             }  
  107.   
  108.             const struct pollfd& pfd = mFDs[mInputDeviceIndex];  
  109.             if (pfd.revents & POLLIN) {  
  110.                 int32_t readSize = read(pfd.fd, mInputBufferData,  
  111.                     sizeof(struct input_event) * INPUT_BUFFER_SIZE);  
  112.                 if (readSize < 0) {  
  113.                     if (errno != EAGAIN && errno != EINTR) {  
  114.                         LOGW("could not get event (errno=%d)", errno);  
  115.                     }  
  116.                 } else if ((readSize % sizeof(struct input_event)) != 0) {  
  117.                     LOGE("could not get event (wrong size: %d)", readSize);  
  118.                 } else {  
  119.                     mInputBufferCount = readSize / sizeof(struct input_event);  
  120.                     mInputBufferIndex = 0;  
  121.                 }  
  122.             }  
  123.         }  
  124.   
  125.         ......  
  126.   
  127.         mInputDeviceIndex = 0;  
  128.   
  129.         // Poll for events.  Mind the wake lock dance!  
  130.         // We hold a wake lock at all times except during poll().  This works due to some  
  131.         // subtle choreography.  When a device driver has pending (unread) events, it acquires  
  132.         // a kernel wake lock.  However, once the last pending event has been read, the device  
  133.         // driver will release the kernel wake lock.  To prevent the system from going to sleep  
  134.         // when this happens, the EventHub holds onto its own user wake lock while the client  
  135.         // is processing events.  Thus the system can only sleep if there are no events  
  136.         // pending or currently being processed.  
  137.         release_wake_lock(WAKE_LOCK_ID);  
  138.   
  139.         int pollResult = poll(mFDs, mFDCount, -1);  
  140.   
  141.         acquire_wake_lock(PARTIAL_WAKE_LOCK, WAKE_LOCK_ID);  
  142.   
  143.         if (pollResult <= 0) {  
  144.             if (errno != EINTR) {  
  145.                 LOGW("poll failed (errno=%d)\n", errno);  
  146.                 usleep(100000);  
  147.             }  
  148.         }  
  149.   
  150.     }  
  151. }  
        这个函数比较长,我们一步一步来分析。

        首先,如果是第一次进入到这个函数中时,成员变量mOpened的值为false,于是就会调用openPlatformInput函数来打开系统输入设备,在本文中,我们主要讨论的输入设备就是键盘了。打开了这些输入设备文件后,就可以对这些输入设备进行是监控了。如果不是第一次进入到这个函数,那么就会分析当前有没有输入事件发生,如果有,就返回这个事件,否则就会进入等待状态,等待下一次输入事件的发生。在我们这个场景中,就是等待下一次键盘事件的发生了。

       我们先分析openPlatformInput函数的实现,然后回过头来分析这个getEvent函数的具体的实现。

       Step 19. EventHub.openPlatformInput

       这个函数定义在frameworks/base/libs/ui/EventHub.cpp文件中:

  1. bool EventHub::openPlatformInput(void)  
  2. {  
  3.     ......  
  4.   
  5.     res = scanDir(device_path);  
  6.     if(res < 0) {  
  7.         LOGE("scan dir failed for %s\n", device_path);  
  8.     }  
  9.   
  10.     return true;  
  11. }  
        这个函数主要是扫描device_path目录下的设备文件,然后打开它们,这里的变量device_path定义在frameworks/base/libs/ui/EventHub.cpp文件开始的地方:

  1. static const char *device_path = "/dev/input";  
        在设备目录/dev/input中,一般有三个设备文件存在,分别是event0、mice和mouse0设备文件,其中,键盘事件就包含在event0设备文件中了。

        Step 20. EventHub.scanDir

        这个函数定义在frameworks/base/libs/ui/EventHub.cpp文件中:

  1. int EventHub::scanDir(const char *dirname)  
  2. {  
  3.     char devname[PATH_MAX];  
  4.     char *filename;  
  5.     DIR *dir;  
  6.     struct dirent *de;  
  7.     dir = opendir(dirname);  
  8.     if(dir == NULL)  
  9.         return -1;  
  10.     strcpy(devname, dirname);  
  11.     filename = devname + strlen(devname);  
  12.     *filename++ = '/';  
  13.     while((de = readdir(dir))) {  
  14.         if(de->d_name[0] == '.' &&  
  15.             (de->d_name[1] == '\0' ||  
  16.             (de->d_name[1] == '.' && de->d_name[2] == '\0')))  
  17.             continue;  
  18.         strcpy(filename, de->d_name);  
  19.         openDevice(devname);  
  20.     }  
  21.     closedir(dir);  
  22.     return 0;  
  23. }  
       根据上面一步的分析,这个函数主要就是调用openDevice函数来分别打开/dev/input/event0、/dev/input/mice和/dev/input/mouse0三个设备文件了。

       Step 21. EventHub.openDevice
       这个函数定义在frameworks/base/libs/ui/EventHub.cpp文件中:

  1. int EventHub::openDevice(const char *deviceName) {  
  2.     int version;  
  3.     int fd;  
  4.     struct pollfd *new_mFDs;  
  5.     device_t **new_devices;  
  6.     char **new_device_names;  
  7.     char name[80];  
  8.     char location[80];  
  9.     char idstr[80];  
  10.     struct input_id id;  
  11.   
  12.     LOGV("Opening device: %s", deviceName);  
  13.   
  14.     AutoMutex _l(mLock);  
  15.   
  16.     fd = open(deviceName, O_RDWR);  
  17.     if(fd < 0) {  
  18.         LOGE("could not open %s, %s\n", deviceName, strerror(errno));  
  19.         return -1;  
  20.     }  
  21.   
  22.     ......  
  23.   
  24.     int devid = 0;  
  25.     while (devid < mNumDevicesById) {  
  26.         if (mDevicesById[devid].device == NULL) {  
  27.             break;  
  28.         }  
  29.         devid++;  
  30.     }  
  31.       
  32.     ......  
  33.   
  34.     mDevicesById[devid].seq = (mDevicesById[devid].seq+(1<<SEQ_SHIFT))&SEQ_MASK;  
  35.     if (mDevicesById[devid].seq == 0) {  
  36.         mDevicesById[devid].seq = 1<<SEQ_SHIFT;  
  37.     }  
  38.   
  39.     new_mFDs = (pollfd*)realloc(mFDs, sizeof(mFDs[0]) * (mFDCount + 1));  
  40.     new_devices = (device_t**)realloc(mDevices, sizeof(mDevices[0]) * (mFDCount + 1));  
  41.     if (new_mFDs == NULL || new_devices == NULL) {  
  42.         LOGE("out of memory");  
  43.         return -1;  
  44.     }  
  45.     mFDs = new_mFDs;  
  46.     mDevices = new_devices;  
  47.   
  48.     ......  
  49.   
  50.     device_t* device = new device_t(devid|mDevicesById[devid].seq, deviceName, name);  
  51.     if (device == NULL) {  
  52.         LOGE("out of memory");  
  53.         return -1;  
  54.     }  
  55.   
  56.     device->fd = fd;  
  57.     mFDs[mFDCount].fd = fd;  
  58.     mFDs[mFDCount].events = POLLIN;  
  59.     mFDs[mFDCount].revents = 0;  
  60.   
  61.     // Figure out the kinds of events the device reports.  
  62.   
  63.     uint8_t key_bitmask[sizeof_bit_array(KEY_MAX + 1)];  
  64.     memset(key_bitmask, 0, sizeof(key_bitmask));  
  65.   
  66.     LOGV("Getting keys...");  
  67.     if (ioctl(fd, EVIOCGBIT(EV_KEY, sizeof(key_bitmask)), key_bitmask) >= 0) {  
  68.         // See if this is a keyboard.  Ignore everything in the button range except for  
  69.         // gamepads which are also considered keyboards.  
  70.         if (containsNonZeroByte(key_bitmask, 0, sizeof_bit_array(BTN_MISC))  
  71.             || containsNonZeroByte(key_bitmask, sizeof_bit_array(BTN_GAMEPAD),  
  72.             sizeof_bit_array(BTN_DIGI))  
  73.             || containsNonZeroByte(key_bitmask, sizeof_bit_array(KEY_OK),  
  74.             sizeof_bit_array(KEY_MAX + 1))) {  
  75.                 device->classes |= INPUT_DEVICE_CLASS_KEYBOARD;  
  76.   
  77.                 device->keyBitmask = new uint8_t[sizeof(key_bitmask)];  
  78.                 if (device->keyBitmask != NULL) {  
  79.                     memcpy(device->keyBitmask, key_bitmask, sizeof(key_bitmask));  
  80.                 } else {  
  81.                     delete device;  
  82.                     LOGE("out of memory allocating key bitmask");  
  83.                     return -1;  
  84.                 }  
  85.         }  
  86.     }  
  87.   
  88.     ......  
  89.   
  90.     if ((device->classes & INPUT_DEVICE_CLASS_KEYBOARD) != 0) {  
  91.         char tmpfn[sizeof(name)];  
  92.         char keylayoutFilename[300];  
  93.   
  94.         // a more descriptive name  
  95.         device->name = name;  
  96.   
  97.         // replace all the spaces with underscores  
  98.         strcpy(tmpfn, name);  
  99.         for (char *p = strchr(tmpfn, ' '); p && *p; p = strchr(tmpfn, ' '))  
  100.             *p = '_';  
  101.   
  102.         // find the .kl file we need for this device  
  103.         const char* root = getenv("ANDROID_ROOT");  
  104.         snprintf(keylayoutFilename, sizeof(keylayoutFilename),  
  105.             "%s/usr/keylayout/%s.kl", root, tmpfn);  
  106.         bool defaultKeymap = false;  
  107.         if (access(keylayoutFilename, R_OK)) {  
  108.             snprintf(keylayoutFilename, sizeof(keylayoutFilename),  
  109.                 "%s/usr/keylayout/%s", root, "qwerty.kl");  
  110.             defaultKeymap = true;  
  111.         }  
  112.         status_t status = device->layoutMap->load(keylayoutFilename);  
  113.         if (status) {  
  114.             LOGE("Error %d loading key layout.", status);  
  115.         }  
  116.   
  117.         // tell the world about the devname (the descriptive name)  
  118.         if (!mHaveFirstKeyboard && !defaultKeymap && strstr(name, "-keypad")) {  
  119.             // the built-in keyboard has a well-known device ID of 0,  
  120.             // this device better not go away.  
  121.             mHaveFirstKeyboard = true;  
  122.             mFirstKeyboardId = device->id;  
  123.             property_set("hw.keyboards.0.devname", name);  
  124.         } else {  
  125.             // ensure mFirstKeyboardId is set to -something-.  
  126.             if (mFirstKeyboardId == 0) {  
  127.                 mFirstKeyboardId = device->id;  
  128.             }  
  129.         }  
  130.         char propName[100];  
  131.         sprintf(propName, "hw.keyboards.%u.devname", device->id);  
  132.         property_set(propName, name);  
  133.   
  134.         // 'Q' key support = cheap test of whether this is an alpha-capable kbd  
  135.         if (hasKeycodeLocked(device, AKEYCODE_Q)) {  
  136.             device->classes |= INPUT_DEVICE_CLASS_ALPHAKEY;  
  137.         }  
  138.   
  139.         // See if this device has a DPAD.  
  140.         if (hasKeycodeLocked(device, AKEYCODE_DPAD_UP) &&  
  141.             hasKeycodeLocked(device, AKEYCODE_DPAD_DOWN) &&  
  142.             hasKeycodeLocked(device, AKEYCODE_DPAD_LEFT) &&  
  143.             hasKeycodeLocked(device, AKEYCODE_DPAD_RIGHT) &&  
  144.             hasKeycodeLocked(device, AKEYCODE_DPAD_CENTER)) {  
  145.                 device->classes |= INPUT_DEVICE_CLASS_DPAD;  
  146.         }  
  147.   
  148.         // See if this device has a gamepad.  
  149.         for (size_t i = 0; i < sizeof(GAMEPAD_KEYCODES)/sizeof(GAMEPAD_KEYCODES[0]); i++) {  
  150.             if (hasKeycodeLocked(device, GAMEPAD_KEYCODES[i])) {  
  151.                 device->classes |= INPUT_DEVICE_CLASS_GAMEPAD;  
  152.                 break;  
  153.             }  
  154.         }  
  155.   
  156.         LOGI("New keyboard: device->id=0x%x devname='%s' propName='%s' keylayout='%s'\n",  
  157.             device->id, name, propName, keylayoutFilename);  
  158.     }  
  159.   
  160.     ......  
  161.   
  162.     mDevicesById[devid].device = device;  
  163.     device->next = mOpeningDevices;  
  164.     mOpeningDevices = device;  
  165.     mDevices[mFDCount] = device;  
  166.   
  167.     mFDCount++;  
  168.     return 0;  
  169. }  
         函数首先根据文件名来打开这个设备文件:

  1. fd = open(deviceName, O_RDWR);  
        系统中所有输入设备文件信息都保存在成员变量mDevicesById中,因此,先在mDevicesById找到一个空位置来保存当前打开的设备文件信息:

  1. mDevicesById[devid].seq = (mDevicesById[devid].seq+(1<<SEQ_SHIFT))&SEQ_MASK;  
  2. if (mDevicesById[devid].seq == 0) {  
  3.     mDevicesById[devid].seq = 1<<SEQ_SHIFT;  
  4. }  
        找到了空闲位置后,就为这个输入设备文件创建相应的device_t信息:
  1. mDevicesById[devid].seq = (mDevicesById[devid].seq+(1<<SEQ_SHIFT))&SEQ_MASK;  
  2. if (mDevicesById[devid].seq == 0) {  
  3.     mDevicesById[devid].seq = 1<<SEQ_SHIFT;  
  4. }  
  5.   
  6. new_mFDs = (pollfd*)realloc(mFDs, sizeof(mFDs[0]) * (mFDCount + 1));  
  7. new_devices = (device_t**)realloc(mDevices, sizeof(mDevices[0]) * (mFDCount + 1));  
  8. if (new_mFDs == NULL || new_devices == NULL) {  
  9.     LOGE("out of memory");  
  10.     return -1;  
  11. }  
  12. mFDs = new_mFDs;  
  13. mDevices = new_devices;  
  14.   
  15. ......  
  16.   
  17. device_t* device = new device_t(devid|mDevicesById[devid].seq, deviceName, name);  
  18. if (device == NULL) {  
  19.     LOGE("out of memory");  
  20.     return -1;  
  21. }  
  22.   
  23. device->fd = fd;  

        同时,这个设备文件还会保存在数组mFDs中:

  1. mFDs[mFDCount].fd = fd;  
  2. mFDs[mFDCount].events = POLLIN;  
  3. mFDs[mFDCount].revents = 0;  
       接下来查看这个设备是不是键盘:

  1. // Figure out the kinds of events the device reports.  
  2.   
  3. uint8_t key_bitmask[sizeof_bit_array(KEY_MAX + 1)];  
  4. memset(key_bitmask, 0, sizeof(key_bitmask));  
  5.   
  6. LOGV("Getting keys...");  
  7. if (ioctl(fd, EVIOCGBIT(EV_KEY, sizeof(key_bitmask)), key_bitmask) >= 0) {  
  8.     // See if this is a keyboard.  Ignore everything in the button range except for  
  9.     // gamepads which are also considered keyboards.  
  10.     if (containsNonZeroByte(key_bitmask, 0, sizeof_bit_array(BTN_MISC))  
  11.         || containsNonZeroByte(key_bitmask, sizeof_bit_array(BTN_GAMEPAD),  
  12.         sizeof_bit_array(BTN_DIGI))  
  13.         || containsNonZeroByte(key_bitmask, sizeof_bit_array(KEY_OK),  
  14.         sizeof_bit_array(KEY_MAX + 1))) {  
  15.             device->classes |= INPUT_DEVICE_CLASS_KEYBOARD;  
  16.   
  17.             device->keyBitmask = new uint8_t[sizeof(key_bitmask)];  
  18.             if (device->keyBitmask != NULL) {  
  19.                 memcpy(device->keyBitmask, key_bitmask, sizeof(key_bitmask));  
  20.             } else {  
  21.                 delete device;  
  22.                 LOGE("out of memory allocating key bitmask");  
  23.                 return -1;  
  24.             }  
  25.     }  
  26. }  
        如果是的话,还要继续进一步初始化前面为这个设备文件所创建的device_t结构体,主要就是把结构体device的classes成员变量的INPUT_DEVICE_CLASS_KEYBOARD位置为1了,以表明这是一个键盘。
        如果是键盘设备,初始化工作还未完成,还要继续设置键盘的布局等信息:

  1. if ((device->classes & INPUT_DEVICE_CLASS_KEYBOARD) != 0) {  
  2.     char tmpfn[sizeof(name)];  
  3.     char keylayoutFilename[300];  
  4.   
  5.     // a more descriptive name  
  6.     device->name = name;  
  7.   
  8.     // replace all the spaces with underscores  
  9.     strcpy(tmpfn, name);  
  10.     for (char *p = strchr(tmpfn, ' '); p && *p; p = strchr(tmpfn, ' '))  
  11.         *p = '_';  
  12.   
  13.     // find the .kl file we need for this device  
  14.     const char* root = getenv("ANDROID_ROOT");  
  15.     snprintf(keylayoutFilename, sizeof(keylayoutFilename),  
  16.         "%s/usr/keylayout/%s.kl", root, tmpfn);  
  17.     bool defaultKeymap = false;  
  18.     if (access(keylayoutFilename, R_OK)) {  
  19.         snprintf(keylayoutFilename, sizeof(keylayoutFilename),  
  20.             "%s/usr/keylayout/%s", root, "qwerty.kl");  
  21.         defaultKeymap = true;  
  22.     }  
  23.     status_t status = device->layoutMap->load(keylayoutFilename);  
  24.     if (status) {  
  25.         LOGE("Error %d loading key layout.", status);  
  26.     }  
  27.   
  28.     // tell the world about the devname (the descriptive name)  
  29.     if (!mHaveFirstKeyboard && !defaultKeymap && strstr(name, "-keypad")) {  
  30.         // the built-in keyboard has a well-known device ID of 0,  
  31.         // this device better not go away.  
  32.         mHaveFirstKeyboard = true;  
  33.         mFirstKeyboardId = device->id;  
  34.         property_set("hw.keyboards.0.devname", name);  
  35.     } else {  
  36.         // ensure mFirstKeyboardId is set to -something-.  
  37.         if (mFirstKeyboardId == 0) {  
  38.             mFirstKeyboardId = device->id;  
  39.         }  
  40.     }  
  41.     char propName[100];  
  42.     sprintf(propName, "hw.keyboards.%u.devname", device->id);  
  43.     property_set(propName, name);  
  44.   
  45.     // 'Q' key support = cheap test of whether this is an alpha-capable kbd  
  46.     if (hasKeycodeLocked(device, AKEYCODE_Q)) {  
  47.         device->classes |= INPUT_DEVICE_CLASS_ALPHAKEY;  
  48.     }  
  49.   
  50.     // See if this device has a DPAD.  
  51.     if (hasKeycodeLocked(device, AKEYCODE_DPAD_UP) &&  
  52.         hasKeycodeLocked(device, AKEYCODE_DPAD_DOWN) &&  
  53.         hasKeycodeLocked(device, AKEYCODE_DPAD_LEFT) &&  
  54.         hasKeycodeLocked(device, AKEYCODE_DPAD_RIGHT) &&  
  55.         hasKeycodeLocked(device, AKEYCODE_DPAD_CENTER)) {  
  56.             device->classes |= INPUT_DEVICE_CLASS_DPAD;  
  57.     }  
  58.   
  59.     // See if this device has a gamepad.  
  60.     for (size_t i = 0; i < sizeof(GAMEPAD_KEYCODES)/sizeof(GAMEPAD_KEYCODES[0]); i++) {  
  61.         if (hasKeycodeLocked(device, GAMEPAD_KEYCODES[i])) {  
  62.             device->classes |= INPUT_DEVICE_CLASS_GAMEPAD;  
  63.             break;  
  64.         }  
  65.     }  
  66.   
  67.     LOGI("New keyboard: device->id=0x%x devname='%s' propName='%s' keylayout='%s'\n",  
  68.         device->id, name, propName, keylayoutFilename);  
  69. }  
        到这里,系统中的输入设备文件就打开了。

        回到Step 18中,我们继续分析EventHub.getEvent函数的实现。

        在中间的for循环里面,首先会检查当前是否有输入设备被关闭,如果有,就返回一个设备移除的事件给调用方:

  1. // Report any devices that had last been added/removed.  
  2. if (mClosingDevices != NULL) {  
  3.     device_t* device = mClosingDevices;  
  4.     LOGV("Reporting device closed: id=0x%x, name=%s\n",  
  5.         device->id, device->path.string());  
  6.     mClosingDevices = device->next;  
  7.     if (device->id == mFirstKeyboardId) {  
  8.         outEvent->deviceId = 0;  
  9.     } else {  
  10.         outEvent->deviceId = device->id;  
  11.     }  
  12.     outEvent->type = DEVICE_REMOVED;  
  13.     outEvent->when = systemTime(SYSTEM_TIME_MONOTONIC);  
  14.     delete device;  
  15.     mNeedToSendFinishedDeviceScan = true;  
  16.     return true;  
  17. }  
        接着,检查当前是否有新的输入设备加入进来:

  1. if (mOpeningDevices != NULL) {  
  2.     device_t* device = mOpeningDevices;  
  3.     LOGV("Reporting device opened: id=0x%x, name=%s\n",  
  4.         device->id, device->path.string());  
  5.     mOpeningDevices = device->next;  
  6.     if (device->id == mFirstKeyboardId) {  
  7.         outEvent->deviceId = 0;  
  8.     } else {  
  9.         outEvent->deviceId = device->id;  
  10.     }  
  11.     outEvent->type = DEVICE_ADDED;  
  12.     outEvent->when = systemTime(SYSTEM_TIME_MONOTONIC);  
  13.     mNeedToSendFinishedDeviceScan = true;  
  14.     return true;  
  15. }  
        接着,再检查是否需要结束监控输入事件:

  1. if (mNeedToSendFinishedDeviceScan) {  
  2.     mNeedToSendFinishedDeviceScan = false;  
  3.     outEvent->type = FINISHED_DEVICE_SCAN;  
  4.     outEvent->when = systemTime(SYSTEM_TIME_MONOTONIC);  
  5.     return true;  
  6. }  
        最后,就是要检查当前是否有还未处理的输入设备事件发生了:

  1. // Grab the next input event.  
  2. for (;;) {  
  3.     // Consume buffered input events, if any.  
  4.     if (mInputBufferIndex < mInputBufferCount) {  
  5.         const struct input_event& iev = mInputBufferData[mInputBufferIndex++];  
  6.         const device_t* device = mDevices[mInputDeviceIndex];  
  7.   
  8.         LOGV("%s got: t0=%d, t1=%d, type=%d, code=%d, v=%d", device->path.string(),  
  9.             (int) iev.time.tv_sec, (int) iev.time.tv_usec, iev.type, iev.code, iev.value);  
  10.         if (device->id == mFirstKeyboardId) {  
  11.             outEvent->deviceId = 0;  
  12.         } else {  
  13.             outEvent->deviceId = device->id;  
  14.         }  
  15.         outEvent->type = iev.type;  
  16.         outEvent->scanCode = iev.code;  
  17.         if (iev.type == EV_KEY) {  
  18.             status_t err = device->layoutMap->map(iev.code,  
  19.                 & outEvent->keyCode, & outEvent->flags);  
  20.             LOGV("iev.code=%d keyCode=%d flags=0x%08x err=%d\n",  
  21.                 iev.code, outEvent->keyCode, outEvent->flags, err);  
  22.             if (err != 0) {  
  23.                 outEvent->keyCode = AKEYCODE_UNKNOWN;  
  24.                 outEvent->flags = 0;  
  25.             }  
  26.         } else {  
  27.             outEvent->keyCode = iev.code;  
  28.         }  
  29.         outEvent->value = iev.value;  
  30.   
  31.         // Use an event timestamp in the same timebase as  
  32.         // java.lang.System.nanoTime() and android.os.SystemClock.uptimeMillis()  
  33.         // as expected by the rest of the system.  
  34.         outEvent->when = systemTime(SYSTEM_TIME_MONOTONIC);  
  35.         return true;  
  36.     }  
  37.   
  38.     // Finish reading all events from devices identified in previous poll().  
  39.     // This code assumes that mInputDeviceIndex is initially 0 and that the  
  40.     // revents member of pollfd is initialized to 0 when the device is first added.  
  41.     // Since mFDs[0] is used for inotify, we process regular events starting at index 1.  
  42.     mInputDeviceIndex += 1;  
  43.     if (mInputDeviceIndex >= mFDCount) {  
  44.         break;  
  45.     }  
  46.   
  47.     const struct pollfd& pfd = mFDs[mInputDeviceIndex];  
  48.     if (pfd.revents & POLLIN) {  
  49.         int32_t readSize = read(pfd.fd, mInputBufferData,  
  50.             sizeof(struct input_event) * INPUT_BUFFER_SIZE);  
  51.         if (readSize < 0) {  
  52.             if (errno != EAGAIN && errno != EINTR) {  
  53.                 LOGW("could not get event (errno=%d)", errno);  
  54.             }  
  55.         } else if ((readSize % sizeof(struct input_event)) != 0) {  
  56.             LOGE("could not get event (wrong size: %d)", readSize);  
  57.         } else {  
  58.             mInputBufferCount = readSize / sizeof(struct input_event);  
  59.             mInputBufferIndex = 0;  
  60.         }  
  61.     }  
  62. }  
        未处理的输入事件保存在成员变量mInputBufferData中,如果有的话,就可以直接返回了,否则的话,就要通过系统调用poll来等待输入设备上发生新的事件了,在我们这个场景中,就是等待键盘有键被按下或者松开了。:

  1. int pollResult = poll(mFDs, mFDCount, -1);  

        这里的mFDs包含了我们所要监控的输入设备的打开文件描述符,这是在前面的openPlatformInput函数中初始化的。

        Step 22. poll

        这是一个Linux系统的文件操作系统调用,它用来查询指定的文件列表是否有有可读写的,如果有,就马上返回,否则的话,就阻塞线程,并等待驱动程序唤醒,重新调用poll函数,或超时返回。在我们的这个场景中,就是要查询是否有键盘事件发生,如果有的话,就返回,否则的话,当前线程就睡眠等待键盘事件的发生了。

        这样,InputManager的启动过程就分析完了,下面我们再分析应用程序注册键盘消息接收通道的过程。

-------

转自:老罗的Android应用程序键盘(Keyboard)消息处理机制分析

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值