Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲

Android 輸入事件流程剖析:從 EventHub 到事件分發線程

編輯:關於 Android 程式設計

按下螢幕上一個按鈕,系統內部到底跑了哪些東西?本文沿著 Android 原生的輸入子系統走一遍,從核心層的 EventHub、JNI 橋接,一路到 Java 層的讀取線程與分發線程。

EventHub:輸入設備的統一入口

EventHub 負責封裝所有輸入設備。Linux 核心的輸入子系統會在 /dev/input 底下產生對應的設備檔案,EventHub 啟動時掃描這個目錄並逐一開啟:

bool EventHub::openPlatformInput(void) {
    ...
    mFDCount = 1;
    mFDs = (pollfd *)calloc(1, sizeof(mFDs[0]));
    mDevices = (device_t **)calloc(1, sizeof(mDevices[0]));
    mFDs[0].events = POLLIN;
    mDevices[0] = NULL;
    res = scan_dir(device_path);
    ...
    return true;
}

它對外提供 getEvent() 供上層讀取事件。這個方法用 poll() 同時監看多個檔案描述符,並在讀到資料後做按鍵碼轉換:

bool EventHub::getEvent(int32_t* outDeviceId, int32_t* outType, int32_t* outScancode,
                        int32_t* outKeycode, uint32_t *outFlags, int32_t* outValue,
                        nsecs_t* outWhen) {
    ...
    while (1) {
        // 先回報裝置的加入/移除
        if (mClosingDevices != NULL) {
            device_t* device = mClosingDevices;
            mClosingDevices = device->next;
            *outDeviceId = device->id;
            if (*outDeviceId == mFirstKeyboardId) *outDeviceId = 0;
            *outType = DEVICE_REMOVED;
            delete device;
            return true;
        }
        if (mOpeningDevices != NULL) {
            device_t* device = mOpeningDevices;
            mOpeningDevices = device->next;
            *outDeviceId = device->id;
            if (*outDeviceId == mFirstKeyboardId) *outDeviceId = 0;
            *outType = DEVICE_ADDED;
            return true;
        }

        release_wake_lock(WAKE_LOCK_ID);
        pollres = poll(mFDs, mFDCount, -1);
        acquire_wake_lock(PARTIAL_WAKE_LOCK, WAKE_LOCK_ID);

        if (pollres <= 0) {
            if (errno != EINTR) {
                LOGW("select failed (errno=%d)\n", errno);
                usleep(100000);
            }
            continue;
        }

        for (i = 1; i < mFDCount; i++) {
            if (mFDs[i].revents & POLLIN) {
                res = read(mFDs[i].fd, &iev, sizeof(iev));
                if (res == sizeof(iev)) {
                    *outDeviceId = mDevices[i]->id;
                    if (*outDeviceId == mFirstKeyboardId) *outDeviceId = 0;
                    *outType = iev.type;
                    *outScancode = iev.code;
                    if (iev.type == EV_KEY) {
                        err = mDevices[i]->layoutMap->map(iev.code, outKeycode, outFlags);
                        if (err != 0) {
                            *outKeycode = 0;
                            *outFlags = 0;
                        }
                    } else {
                        *outKeycode = iev.code;
                    }
                    *outValue = iev.value;
                    *outWhen = s2ns(iev.time.tv_sec) + us2ns(iev.time.tv_usec);
                    return true;
                }
                continue;
            }
        }
    }
}

值得注意的兩個設計細節:一是 poll() 前後分別 release_wake_lock 與 acquire_wake_lock,讓系統在等待輸入的期間可以進入休眠,有事件來才喚醒;二是遇到 EV_KEY 類型時會呼叫 layoutMap->map() 做按鍵映射,把硬體的 scancode 轉成 Android 統一的 keycode。

映射規則由 KeyLayoutMap::map 完成,它讀取 qwerty.kl 這類設定檔,檔中定義了鍵值對應關係。想自訂(例如把某顆實體鍵改成返回鍵),修改 ./development/emulator/keymaps/qwerty.kl 即可。

JNI 層:把 C++ 結構轉成 Java 物件

frameworks/base/services/jni/com_android_server_KeyInputQueue.cpp 對 Java 提供了 android_server_KeyInputQueue_readEvent:

static jboolean android_server_KeyInputQueue_readEvent(JNIEnv* env, jobject clazz, jobject event) {
    gLock.lock();
    sp<EventHub> hub = gHub;
    if (hub == NULL) {
        hub = new EventHub;
        gHub = hub;
    }
    gLock.unlock();

    int32_t deviceId, type, scancode, keycode;
    uint32_t flags;
    int32_t value;
    nsecs_t when;
    bool res = hub->getEvent(&deviceId, &type, &scancode, &keycode, &flags, &value, &when);

    env->SetIntField(event, gInputOffsets.mDeviceId, (jint)deviceId);
    env->SetIntField(event, gInputOffsets.mType, (jint)type);
    env->SetIntField(event, gInputOffsets.mScancode, (jint)scancode);
    env->SetIntField(event, gInputOffsets.mKeycode, (jint)keycode);
    env->SetIntField(event, gInputOffsets.mFlags, (jint)flags);
    env->SetIntField(event, gInputOffsets.mValue, value);
    env->SetLongField(event, gInputOffsets.mWhen, (jlong)(nanoseconds_to_milliseconds(when)));
    return res;
}

也就是呼叫 hub->getEvent() 取得事件後,用 SetIntField 家族把 C++ 的欄位逐一寫進 Java 的 RawInputEvent 物件裡。

Java 層:讀取線程與分發線程

在 frameworks/base/services/java/com/android/server/KeyInputQueue.java 中建立了一個名為 InputDeviceReader 的線程,它不停地把事件讀出來放進佇列:

Thread mThread = new Thread("InputDeviceReader") {
    public void run() {
        android.os.Process.setThreadPriority(
                android.os.Process.THREAD_PRIORITY_URGENT_DISPLAY);
        try {
            RawInputEvent ev = new RawInputEvent();
            while (true) {
                InputDevice di;
                readEvent(ev);
                send = preprocessEvent(di, ev);
                addLocked(di, curTime, ev.flags, ..., me);
            }
        }
    }
};

注意它開頭就把線程優先權設為 THREAD_PRIORITY_URGENT_DISPLAY——輸入延遲直接影響觸控手感,這個值僅次於即時(RT)等級,體現了輸入路徑對延遲的敏感度。

接著在 WindowManagerService.java 裡有一個分發線程,負責把佇列中的事件派送給目前有焦點的視窗:

mQueue.getEvent  →  dispatchKey / dispatchPointer / dispatchTrackball

整體流程回顧

把上面串起來,一次觸控的完整路徑是:

  1. 核心輸入驅動產生事件節點於 /dev/input
  2. EventHub 以 poll() 監看並讀取,完成 scancode → keycode 映射
  3. JNI 的 readEvent 把原生結構轉為 Java 物件
  4. InputDeviceReader 線程持續讀取並塞入事件佇列
  5. WindowManagerService 的分發線程把事件派送給目標視窗
  6. 視窗所在的 UI 線程透過 dispatchTouchEvent 往下傳遞,最終由 Leaf View 處理

理解這條鏈路,對排查「觸控沒反應」、「手勢被父層吃掉」、「點擊位置偏移」這類問題特別有幫助——你知道該從哪一層下手看日誌。

以上就是 Android 輸入事件流程的整體梳理,希望對有興趣深入 framework 的朋友有所幫助。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved