編輯:關於 Android 程式設計
按下螢幕上一個按鈕,系統內部到底跑了哪些東西?本文沿著 Android 原生的輸入子系統走一遍,從核心層的 EventHub、JNI 橋接,一路到 Java 層的讀取線程與分發線程。
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 即可。
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 物件裡。
在 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
把上面串起來,一次觸控的完整路徑是:
/dev/inputEventHub 以 poll() 監看並讀取,完成 scancode → keycode 映射readEvent 把原生結構轉為 Java 物件InputDeviceReader 線程持續讀取並塞入事件佇列WindowManagerService 的分發線程把事件派送給目標視窗dispatchTouchEvent 往下傳遞,最終由 Leaf View 處理理解這條鏈路,對排查「觸控沒反應」、「手勢被父層吃掉」、「點擊位置偏移」這類問題特別有幫助——你知道該從哪一層下手看日誌。
以上就是 Android 輸入事件流程的整體梳理,希望對有興趣深入 framework 的朋友有所幫助。
Android 使用 AlertDialog 實作消息彈窗
在 Android 應用中,當需要提醒使用者進行某項操作或確認某個決定時,常會使用對話框。AlertDialog 是最常見的選擇之一,可用來顯示標題、內容與多個操作按鈕。
這些編碼習慣正在洩漏你的記憶體:Android 常見內存洩漏陷阱
Android 的記憶體洩漏很少來自複雜的架構錯誤,絕大多數是幾個寫起來「很順手」的習慣累積出來的。以下幾個模式幾乎每個專案都會遇到,值得逐一檢視。 一、單例持有 Act
OkHttp 使用詳解:Android 網路請求完整指南
OkHttp 已被 Google 列為推薦的 Android 網路請求框架,在 Android Studio 中可直接加入依賴: 依賴庫為: compile com.s
Android 觸控事件分發機制全解析:從 Activity 到 View 的完整路徑
上一篇文章我們談過觸控事件的「來源」——手指按下螢幕之後,原始輸入事件如何被系統封裝成 MotionEvent 並投遞到應用程序的視窗。這一篇接著往下走:當事件抵達 Ac