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

Android 系統源碼閱讀(11):InputManagerService 的工作過程

編輯:關於 Android 程式設計

本文對照 AOSP 版本:6.0.1_r50。

與老羅當年的版本相比,這裡有了明顯變化——多了一個 InputManagerService 來管理 InputManager。本文就沿著系統源碼,把輸入系統從創建、啟動到事件分發的脈絡完整梳理一遍。

1. 創建 InputManager

1.1 從 SystemServer 出發

要探索輸入系統是如何啟動的,得從 SystemServer 說起。SystemServer 進程一旦開始運行,便會創建一系列系統服務,其中就包括 Input Manager 與 Window Manager 這兩個服務。

frameworks/base/services/java/com/android/server/SystemServer.java :

Slog.i(TAG, "Input Manager");
inputManager = new InputManagerService(context);
Slog.i(TAG, "Window Manager");
wm = WindowManagerService.main(context, inputManager, mFactoryTestMode != FactoryTest.FACTORY_TEST_LOW_LEVEL, !mFirstBoot, mOnlyCore);
ServiceManager.addService(Context.WINDOW_SERVICE, wm);
ServiceManager.addService(Context.INPUT_SERVICE, inputManager);

1.2 走進構造函數

仔細端詳 InputManagerService 的構造函數,會發現它呼叫了 C++ 層的初始化函數。

InputManagerService.java :

mPtr = nativeInit(this, mContext, mHandler.getLooper().getQueue());

注意,這裡把一個本地的 MessageQueue 傳到了 C++ 層。

1.3 抵達 JNI 層

這一步先把 Java 層的 MessageQueue 轉換為 C++ 的 MessageQueue,接著構造一個 NativeInputManager 物件,最後把指向它的指標 mPtr 返回給 Java 層。

com_android_server_input_InputManagerService.cpp :

NativeInputManager* im = new NativeInputManager(contextObj, serviceObj, messageQueue->getLooper());

1.4 構造 NativeInputManager

在構造 NativeInputManager 時,會創建一個 InputManager 物件。

com_android_server_input_InputManagerService.cpp :

sp eventHub = new EventHub();
mInputManager = new InputManager(eventHub, this, this);

1.5 創建分發者與讀取者

這一步創建了一個負責分發輸入事件的 dispatcher,以及一個負責獲取事件的 reader。

frameworks/native/services/inputflinger/InputManager.cpp :

mDispatcher = new InputDispatcher(dispatcherPolicy);
mReader = new InputReader(eventHub, readerPolicy, mDispatcher);
initialize();

1.6 創建兩個線程

這裡創建了兩個線程,用於隨後運行前面創建的 dispatcher 與 reader。

InputManager.cpp :

mReaderThread = new InputReaderThread(mReader);
mDispatcherThread = new InputDispatcherThread(mDispatcher);

2. 啟動 InputManager

視線回到 SystemServer。創建完 InputManagerService 後,需要把它啟動起來。同樣在 startOtherServices 函數中,呼叫了 InputManagerService 的成員函數 start。

2.1 start 方法

這裡首先呼叫 C++ 層的 nativeStart,接著把 InputManagerService 交給 Watchdog 監視,並註冊了 PointerSpeedSetting 與 ShowTouchesSetting 兩個 Observer。

InputManagerService.java :

nativeStart(mPtr);
// 把自己加入 Watchdog 監控
Watchdog.getInstance().addMonitor(this);
registerPointerSpeedSettingObserver();
registerShowTouchesSettingObserver();

2.2 nativeStart 抵達 C++ 層

這一步把傳來的 mPtr 轉化為 NativeInputManager 指標,並啟動其中的 InputManager。

com_android_server_input_InputManagerService.cpp :

NativeInputManager* im = reinterpret_cast(ptr);
status_t result = im->getInputManager()->start();

2.3 啟動兩個線程

這裡啟動了 1.6 中創建的兩個線程,分別負責分發與監聽 Input 事件。

InputManager.cpp :

status_t result = mDispatcherThread->run("InputDispatcher", PRIORITY_URGENT_DISPLAY);
result = mReaderThread->run("InputReader", PRIORITY_URGENT_DISPLAY);

3. 啟動 InputDispatcher

在 2.3 中運行的線程以 threadLoop 為入口,進入循環。

3.1 threadLoop 分派任務

這一步直接把任務交給 InputDispatcher 的 dispatchOnce 函數。

InputDispatcher.cpp :

bool InputDispatcherThread::threadLoop() {
    mDispatcher->dispatchOnce();
    return true;
}

3.2 dispatchOnce 的核心邏輯

void InputDispatcher::dispatchOnce() {
    nsecs_t nextWakeupTime = LONG_LONG_MAX;
    {
        AutoMutex _l(mLock);
        mDispatcherIsAliveCondition.broadcast();
        // 若沒有待處理命令,則嘗試獲取輸入事件
        if (!haveCommandsLocked()) {
            dispatchOnceInnerLocked(&nextWakeupTime);
        }
        // 執行緩存命令,若有執行則下次立即喚醒
        if (runCommandsLockedInterruptible()) {
            nextWakeupTime = LONG_LONG_MIN;
        }
    }
    nsecs_t currentTime = now();
    int timeoutMillis = toMillisecondTimeoutDelay(currentTime, nextWakeupTime);
    mLooper->pollOnce(timeoutMillis);
}

這裡首先判斷是否有命令尚未執行:若有,則不必去獲取輸入事件;否則呼叫 dispatchOnceInnerLocked 嘗試獲取事件,並透過 nextWakeupTime 設置合適的喚醒時間。接著 runCommandsLockedInterruptible 執行緩存命令,若有命令在此被執行,就把喚醒時間設為 LONG_LONG_MIN——因為執行命令頗耗時,其間可能已有新事件到來,下次循環便無需再等待。最後根據等待時間與當前時間算出睡眠時長,透過 pollOnce 進入睡眠,等待喚醒或超時。

3.3 進入 Looper 輪詢

道理與前章的 pollOnce 相同。

3.4 epoll_wait 等待事件

這裡呼叫 epoll_wait,在 mEpollFd 所描述的 epoll 上等待一段時間。這個 epoll 監聽著 pipe 的讀寫事件:若有人在 pipe 中寫入則立即返回,否則等待指定時間後返回。

system/core/libutils/Looper.cpp

int eventCount = epoll_wait(mEpollFd, eventItems, EPOLL_MAX_EVENTS, timeoutMillis);

4. 啟動 InputReader

在 2.3 中運行的另一線程同樣以 threadLoop 為入口進入循環。

4.1 把任務交給 InputReader

與 3.1 同理,將任務丟給 InputReader 處理。

4.2 從 EventHub 批量獲取事件

這一步會嘗試從 mEventHub 中獲取事件,若取到一些,便進行處理。值得注意的是,它一次能取回一組 event(而非單個),這是工程師為提升性能所做的優化。

frameworks/native/services/inputflinger/InputReader.cpp :

// 從 EventHub 中獲取 event
size_t count = mEventHub->getEvents(timeoutMillis, mEventBuffer, EVENT_BUFFER_SIZE);
if (count) {
    // 事件處理,後續博客講解
    processEventsLocked(mEventBuffer, count);
}

4.3 EventHub::getEvents 逐段解讀

這個函數並非簡單地取一個 event,而是想辦法填充整塊 buffer。核心邏輯如下:

size_t EventHub::getEvents(int timeoutMillis, RawEvent* buffer, size_t bufferSize) {
    struct input_event readBuffer[bufferSize];
    RawEvent* event = buffer;
    size_t capacity = bufferSize;
    bool awoken = false;
    for (;;) {
        nsecs_t now = systemTime(SYSTEM_TIME_MONOTONIC);
        // 若需重新打開設備,先關閉所有設備
        if (mNeedToReopenDevices) {
            mNeedToReopenDevices = false;
            closeAllDevicesLocked();
            mNeedToScanDevices = true;
            break;
        }
        // 移除所有已關閉的設備,生成 DEVICE_REMOVED 事件
        while (mClosingDevices) { /* ... 生成移除事件 ... */ }
        // 若關閉了設備,重新掃描
        if (mNeedToScanDevices) {
            mNeedToScanDevices = false;
            scanDevicesLocked();
            mNeedToSendFinishedDeviceScan = true;
        }
        // 添加正在開啟的設備,生成 DEVICE_ADDED 事件
        while (mOpeningDevices != NULL) { /* ... 生成添加事件 ... */ }
        if (mNeedToSendFinishedDeviceScan) { /* ... 生成掃描完成事件 ... */ }

        // 循環讀取 pending event,填充 buffer
        while (mPendingEventIndex < mPendingEventCount) {
            const struct epoll_event& eventItem = mPendingEventItems[mPendingEventIndex++];
            // INotify 事件、wake 事件等特殊處理略
            ssize_t deviceIndex = mDevices.indexOfKey(eventItem.data.u32);
            Device* device = mDevices.valueAt(deviceIndex);
            if (eventItem.events & EPOLLIN) {
                int32_t readSize = read(device->fd, readBuffer, sizeof(struct input_event) * capacity);
                size_t count = size_t(readSize) / sizeof(struct input_event);
                for (size_t i = 0; i < count; i++) {
                    struct input_event& iev = readBuffer[i];
                    // 將獲取的事件存入 event
                    event->deviceId = deviceId;
                    event->type = iev.type;
                    event->code = iev.code;
                    event->value = iev.value;
                    event += 1;
                    capacity -= 1;
                }
                if (capacity == 0) {
                    // buffer 已滿,退出,下次再接着讀該設備
                    mPendingEventIndex -= 1;
                    break;
                }
            }
        }
        // buffer 已填充或顯式喚醒,退出外層循環
        if (event != buffer || awoken) {
            break;
        }
        // buffer 為空且無 pending event,等待有人向 pipe 寫入
        int pollResult = epoll_wait(mEpollFd, mPendingEventItems, EPOLL_MAX_EVENTS, timeoutMillis);
        if (pollResult == 0) { mPendingEventCount = 0; break; }  // 超時
        if (pollResult < 0) { /* 出錯處理略 */ }
        else { mPendingEventCount = size_t(pollResult); }  // 有事件,繼續填充
    }
    return event - buffer;
}

4.4 掃描設備的起點

研究 scanDevicesLocked 前,先看 DEVICE_PATH 的來頭。在 EventHub 的構造函數中,用了 Linux 的 inotify 機制——它能監控文件的變化,於是系統便能即時感知設備的添加與移除。

EventHub.cpp :

// 位於 EventHub 構造函數中
mINotifyFd = inotify_init();
int result = inotify_add_watch(mINotifyFd, DEVICE_PATH, IN_DELETE | IN_CREATE);

scanDevicesLocked 會掃描 /dev/input 目錄,並創建一個虛擬鍵盤:

void EventHub::scanDevicesLocked() {
    status_t res = scanDirLocked(DEVICE_PATH);
    if (res < 0) {
        ALOGE("scan dir failed for %s\n", DEVICE_PATH);
    }
    if (mDevices.indexOfKey(VIRTUAL_KEYBOARD_ID) < 0) {
        createVirtualKeyboardLocked();
    }
}

4.5 遍歷目錄下的設備

scanDirLocked 會遍歷 /dev/input/ 下的所有設備文件,逐一打開。

status_t EventHub::scanDirLocked(const char *dirname) {
    char devname[PATH_MAX];
    char *filename;
    DIR *dir = opendir(dirname);
    if (dir == NULL) return -1;
    strcpy(devname, dirname);
    filename = devname + strlen(devname);
    *filename++ = '/';
    while ((de = readdir(dir))) {
        if (de->d_name[0] == '.' && (de->d_name[1] == '\0' || (de->d_name[1] == '.' && de->d_name[2] == '\0'))) continue;
        strcpy(filename, de->d_name);
        openDeviceLocked(devname);
    }
    closedir(dir);
    return 0;
}

4.6 打開並初始化設備

openDeviceLocked 打開設備文件,讀取其名稱、驅動版本、物理位置等各項資訊,創建 Device 物件,並將其文件描述符交給 epoll 監視,以便即時獲悉變化。

status_t EventHub::openDeviceLocked(const char *devicePath) {
    char buffer[80];
    int fd = open(devicePath, O_RDWR | O_CLOEXEC);
    if (fd < 0) { /* 打開失敗處理 */ return -1; }
    InputDeviceIdentifier identifier;
    if (ioctl(fd, EVIOCGNAME(sizeof(buffer) - 1), &buffer) >= 1) {
        buffer[sizeof(buffer) - 1] = '\0';
        identifier.name.setTo(buffer);
    }
    // 讀取驅動版本、標識、物理位置、唯一 id 等,略
    int32_t deviceId = mNextDeviceId++;
    Device* device = new Device(fd, deviceId, String8(devicePath), identifier);
    // 依據設備特徵設置 class,略
    struct epoll_event eventItem;
    memset(&eventItem, 0, sizeof(eventItem));
    eventItem.events = EPOLLIN;
    eventItem.data.u32 = deviceId;
    // 將設備 fd 交給 epoll 監視
    if (epoll_ctl(mEpollFd, EPOLL_CTL_ADD, fd, &eventItem)) { /* 失敗處理 */ return -1; }
    addDeviceLocked(device);
    return 0;
}

4.7 登記設備

最後這步相對輕鬆,把創建好的 Device 物件放入 mDevices 即可。

void EventHub::addDeviceLocked(Device* device) {
    mDevices.add(device->id, device);
    device->next = mOpeningDevices;
    mOpeningDevices = device;
}

至此,我們便沿著 SystemServer → InputManagerService → JNI → InputManager → InputDispatcher / InputReader → EventHub 這條主線,把 Android 輸入系統從初始化到設備掃描、事件讀取的完整工作過程走了一遍。理解了這套「讀取者讀事件、分發者派事件」的架構,也就掌握了 Android 觸控與按鍵響應背後的底層邏輯。

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