編輯:關於 Android 程式設計
Android 5.0 的輸入子系統在框架與流程上和 4.4 並沒有本質變化,主要差別是位置調整了:Service 端實作搬到位於 /frameworks/native/services/inputflinger/(4.4 時在 /frameworks/base/services/input),通用部分則在 /frameworks/native/libs/input/。本文按「初始化 → 讀取 → 分發 → 回饋」的順序,把一個按鍵從核心一路送到 App 的過程走一遍。
系統中負責管理輸入事件的是 InputManagerService(IMS),它的任務是從裝置讀取事件、把事件送到焦點視窗,同時讓系統有機會攔下音量鍵、電源鍵這類系統按鍵。要完成這件事,IMS 主要得和 WMS 與 ViewRootImpl 打交道。

各模組職責如下:
getEvents()。input_event 轉為 RawEvent。SystemServer 先建立 IMS,再把它作為參數傳給 WMS,最後呼叫 start():
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);
...
inputManager.start();
IMS 的建構子中會呼叫 nativeInit()。值得注意的是它取得的是 DisplayThread 的 Handler,意味著 IMS 的訊息佇列處理都在這個共享的前台單例線程中進行,讓對使用者體驗敏感的輸入處理少受其他工作干擾。

初始化順序是 NativeInputManager → EventHub → InputManager → InputDispatcher → InputReader → InputReaderThread → InputDispatcherThread。
EventHub 的建構子主要做三件事:
wake() 往寫端寫入即可讓線程返回。/dev/input 目錄的變更,一有變化就代表裝置增減需要處理。因為事件處理是流水線,InputDispatcher 需要監聽 InputReader。這裡用的是 Listener 模式:InputDispatcher 實作 InputListenerInterface,並作為第三個參數傳進 InputReader 的建構子,在其中被包裝成 QueuedInputListener。QueuedInputListener 的 mArgsQueue 是一個緩衝佇列,只有呼叫 flush() 時才會一次通知 InputDispatcher。它同時套用了 Command 模式,把事件處理請求封裝成 NotifyArgs,因而具備緩衝批次執行的能力。
兩個線程都跑起來之後,先看 InputReaderThread,它是事件在使用者態處理的起點。以按鍵為例:

它不斷呼叫 loopOnce() → getEvents()。首次進入時會掃描 /dev/input 建立裝置清單(EventHub 有 KeyedVector<int32_t, Device*> mDevices,InputReader 對應有 KeyedVector<int32_t, InputDevice*> mDevices;先加入前者,再由 addDeviceLocked() 加入後者),並把新增的 fd 掛進 epoll 等待集合。
epoll_wait() 回來後,裝置上的原始 input_event 會被轉成 RawEvent 放進輸出參數 buffer。回到 InputReader 後呼叫 processEventsLocked():若是裝置變更,依情況呼叫 addDeviceLocked()、removeDeviceLocked() 或 handleConfigurationChangedLocked();若是輸入事件,則交給 processEventsForDeviceLocked(),由當時註冊的 InputMapper 處理,再把處理請求塞進 QueuedInputListener 的 mArgsQueue。
void QueuedInputListener::notifyKey(const NotifyKeyArgs* args) {
mArgsQueue.push(new NotifyKeyArgs(*args));
}
在 loopOnce() 尾聲,flush() 會統一回呼佇列中所有元素的 notify():
void QueuedInputListener::flush() {
size_t count = mArgsQueue.size();
for (size_t i = 0; i < count; i++) {
NotifyArgs* args = mArgsQueue[i];
args->notify(mInnerListener);
delete args;
}
mArgsQueue.clear();
}
按鍵最終會走到 InputDispatcher 的 notifyKey(),先把參數封裝成 KeyEvent:
KeyEvent event;
event.initialize(args->deviceId, args->source, args->action,
flags, keyCode, args->scanCode, metaState, 0,
args->downTime, args->eventTime);
接著交給 NativeInputManager 的 interceptKeyBeforeQueueing()——顧名思義,就是在放進待處理佇列之前,先看看是不是需要系統處理的按鍵。它會透過 JNI 回到 Java 世界,最終落到 PhoneWindowManager 的 interceptKeyBeforeQueueing()。然後建立 KeyEntry,放進佇列等 InputDispatcherThread 來取:
KeyEntry* newEntry = new KeyEntry(args->eventTime,
args->deviceId, args->source, policyFlags,
args->action, flags, keyCode, args->scanCode,
metaState, repeatCount, args->downTime);
needWake = enqueueInboundEventLocked(newEntry);

InputDispatcherThread 會從 mInboundQueue 取出事件處理:
if (!haveCommandsLocked()) {
dispatchOnceInnerLocked(&nextWakeupTime);
}
...
if (runCommandsLockedInterruptible()) {
nextWakeupTime = LONG_LONG_MIN;
}
dispatchOnceInnerLocked() 依 EventEntry 型別分派,按鍵會走 dispatchKeyLocked():
CommandEntry* commandEntry = postCommandLocked(
&InputDispatcher::doInterceptKeyBeforeDispatchingLockedInterruptible);
if (mFocusedWindowHandle != NULL) {
commandEntry->inputWindowHandle = mFocusedWindowHandle;
}
commandEntry->keyEntry = entry;
...
// Identify targets.
Vector<InputTarget> inputTargets;
int32_t injectionResult = findFocusedWindowTargetsLocked(
currentTime, entry, inputTargets, nextWakeupTime);
...
addMonitoringTargetsLocked(inputTargets);
// Dispatch the key.
dispatchEventLocked(currentTime, entry, inputTargets);
它會找出目標視窗,透過先前與 App 建立的連線送出事件。若屬於需要系統處理的按鍵,這裡會封裝成 CommandEntry 插入 mCommandQueue,後續由 runCommandsLockedInterruptible() 呼叫 doInterceptKeyBeforeDispatchingLockedInterruptible(),讓 PWM 有機會介入。最後 dispatchOnce() 呼叫 pollOnce(),等待 App 回報處理完成。
那 InputDispatcher 怎麼知道該往哪個視窗送?答案是 mFocusedWindowHandle,而它背後是一整套視窗連線機制。App 端新的頂層視窗在 ViewRootImpl 的 setView() 中向 WMS 註冊。

與輸入相關的關鍵步驟是:先建立 InputChannel(此時尚未初始化),再透過 WMS 的 addToDisplay() 完成初始化:
mInputChannel = new InputChannel();
...
res = mWindowSession.addToDisplay(mWindow, mSeq, mWindowAttributes,
getHostVisibility(), mDisplay.getDisplayId(),
mAttachInfo.mContentInsets, mInputChannel);
WMS 的 addWindow() 會建立一對 InputChannel(本質上是一對本地 socket),一個註冊給 InputDispatcher,一個回傳給 App:
if (outInputChannel != null
&& (attrs.inputFeatures
& WindowManager.LayoutParams.INPUT_FEATURE_NO_INPUT_CHANNEL) == 0) {
String name = win.makeInputChannelName();
InputChannel[] inputChannels = InputChannel.openInputChannelPair(name);
win.setInputChannel(inputChannels[0]);
inputChannels[1].transferTo(outInputChannel);
mInputManager.registerInputChannel(win.mInputChannel, win.mInputWindowHandle);
}
InputDispatcher 這邊為每個連線建立一個 Connection:
sp<Connection> connection =
new Connection(inputChannel, inputWindowHandle, monitor);
int fd = inputChannel->getFd();
mConnectionsByFd.add(fd, connection);
...
mLooper->addFd(fd, 0, ALOOPER_EVENT_INPUT, handleReceiveCallback, this);
Connection 除了傳輸用的 inputChannel,還包含 inputPublisher 與代表接收方的 inputWindowHandle,以及兩個佇列:outboundQueue 是要發出的事件,waitQueue 是已發出但尚未收到完成通知的。之所以要分兩層,是因為某些事件在前一個處理完之前不會送出下一個。mLooper->addFd() 把 fd 掛進等待集合,回呼函式為 handleReceiveCallback(),最後 wake() 讓 InputDispatcherThread 從 epoll_wait 返回。
App 端接著建立事件接收端 WindowInputEventReceiver,把 fd 掛到主線程的等待集合,之後連線一有訊息就會回呼 NativeInputEventReceiver::handleEvent():
mInputEventReceiver = new WindowInputEventReceiver(mInputChannel, Looper.myLooper());
App 端的事件處理流水線用的是 Chain of Responsibility 模式,每個 InputStage 可以自行處理,也可以往下傳:
// Set up the input pipeline.
CharSequence counterSuffix = attrs.getTitle();
mSyntheticInputStage = new SyntheticInputStage();
InputStage viewPostImeStage = new ViewPostImeInputStage(mSyntheticInputStage);
InputStage nativePostImeStage = new NativePostImeInputStage(viewPostImeStage,
"aq:native-post-ime:" + counterSuffix);
InputStage earlyPostImeStage = new EarlyPostImeInputStage(nativePostImeStage);
InputStage imeStage = new ImeInputStage(earlyPostImeStage, "aq:ime:" + counterSuffix);
InputStage viewPreImeStage = new ViewPreImeInputStage(imeStage);
InputStage nativePreImeStage = new NativePreImeInputStage(viewPreImeStage,
"aq:native-pre-ime:" + counterSuffix);
mFirstInputStage = nativePreImeStage;
mFirstPostImeInputStage = earlyPostImeStage;
也就是說,InputDispatcher 維護著與 WMS 中所有視窗的連線,但一般只會往焦點視窗送事件。

當新視窗加入 WMS,焦點通常會移轉到它身上。焦點變化時,WMS 依序做三件事:
mInputMonitor.setInputFocusLw(mCurrentFocus, updateInputWindows); ... mInputMonitor.updateInputWindowsLw(true); ... mService.mInputManager.setInputWindows(mInputWindowHandles);
其中 updateInputWindowsLw() 會建立 InputWindowHandle 清單,被設為焦點的那一個 hasFocus 會被置位;最後 setInputWindows() 把資訊送到 Native 層的 InputDispatcher,更新其中的焦點視窗句柄。這樣 InputDispatcher 就知道該往哪送。

App 端收到事件後,流程是:接收 → 放進 ViewRootImpl 的待處理佇列 → 走過一系列 InputStage → dispatch 給 View → 處理完再向 IMS 回送完成訊號。
以上是以 Key 事件為例。Motion 事件有個重要差異:不一定每個都要處理。螢幕刷新約 60Hz,若輸入裝置是 100Hz,全部處理只是浪費計算資源。從 Jelly Bean 開始,App 對輸入事件的處理由 VSync 驅動,Choreographer 的 VSync 回呼中第一件處理的就是輸入事件:
doCallbacks(Choreographer.CALLBACK_INPUT, frameTimeNanos); doCallbacks(Choreographer.CALLBACK_ANIMATION, frameTimeNanos); doCallbacks(Choreographer.CALLBACK_TRAVERSAL, frameTimeNanos);
非 VSync 觸發時,NativeInputEventReceiver::handleEvent() 呼叫 consumeEvents() 時 consumeBatches 為 false,事件會被累進 Batch:
if (canAddSample(batch, &mMsg)) {
batch.samples.push(mMsg);
迴圈退出條件不滿足,於是一直讀到 receiveMessage() 失敗;返回不為 0,事件便不會立即處理。等 VSync 到來,consumeBatches 設為 true,Batch 才會被一起消化。

ViewRootImpl 用 mPendingInputEventHead/mPendingInputEventTail 維護待處理事件清單,元素型別為 QueuedInputEvent,由 enqueueInputEvent() 加入,再由 doProcessInputEvents() 取出,交給 deliverInputEvent() 與各 InputStage 的 deliver(),最後 finishInputEvent() 回送完成訊號(內部呼叫 NativeInputEventReceiver::finishInputEvent(),再用 InputConsumer 的 sendFinishedSignal() 送出)。
當重採樣機制開啟(由系統屬性 ro_input.noresample 控制),InputConsumer 對 Motion 事件的處理更複雜一些。VSync 代表 Display 已顯示完一幀、系統要準備下一幀,因此我們需要知道 VSync 那一刻的觸摸座標。問題是輸入裝置的事件並不按 VSync 節拍而來(例如週期 10ms,而 VSync 是 16.67ms),座標只能靠估計——做法是取樣後內外插結合的估值演算法。
InputDispatcher 除了送事件給 App,還負責攔系統按鍵。截取點有兩個函式:interceptKeyBeforeDispatching() 主要處理 home、menu、search;interceptKeyBeforeQueueing() 主要處理音量與電源鍵。這些處理的實作都放在 PWM,呼叫者則是 InputDispatcherThread。這樣切分的好處是平台相關的策略集中在 PWM,InputDispatcher 只留平台通用邏輯,廠商客製只需改 PWM。
呼叫路徑是透過幾個 hook 進去的:
nsecs_t delay = mPolicy->interceptKeyBeforeDispatching(
commandEntry->inputWindowHandle, &event, entry->policyFlags);
這裡的 mPolicy 實際是 NativeInputManager,它透過 JNI 回到 Java 的 IMS:
// Native callback.
private long interceptKeyBeforeDispatching(InputWindowHandle focus,
KeyEvent event, int policyFlags) {
return mWindowManagerCallbacks.interceptKeyBeforeDispatching(focus, event, policyFlags);
}
mWindowManagerCallbacks 就是 InputMonitor,再往下就進到 PWM:
public long interceptKeyBeforeDispatching(InputWindowHandle focus,
KeyEvent event, int policyFlags) {
WindowState windowState = focus != null ? (WindowState) focus.windowState : null;
return mService.mPolicy.interceptKeyBeforeDispatching(windowState, event, policyFlags);
}

從 Input driver 讀出的是 input_event,經過各模組時會按需被包裝成 RawEvent、KeyEntry、DispatchEntry、InputMessage、InputEvent、QueuedInputEvent 等結構。有些是單純的封裝關係,例如 DispatchEntry 包著 KeyEntry,QueuedInputEvent 包著 InputEvent。
App 處理完之後,InputDispatcher 收到完成訊號,會由 handleReceiveCallback() 接手:先往 Command 佇列丟一件 doDispatchCycleFinishedLockedInterruptible(),稍後在 runCommandsLockedInterruptible() 中取出執行。該函式會先呼叫 afterKeyEventLockedInterruptible()——Android 可以在這裡定義 Fallback 鍵,也就是 App 沒處理的按鍵改送另一個預設按鍵,實作在 dispatchUnhandledKey() 中。接著把該事件從等待佇列移除,並啟動下一輪分發:
// Dequeue the event and start the next cycle.
// Note that because the lock might have been released, it is possible that the
// contents of the wait queue to have been drained, so we need to double-check
// a few things.
if (dispatchEntry == connection->findWaitQueueEntry(seq)) {
connection->waitQueue.dequeue(dispatchEntry);
...
}
// Start the next dispatch cycle for this connection.
startDispatchCycleLocked(now(), connection);
startDispatchCycleLocked() 會檢查該連線的 outboundQueue 是否還有事件,有的話就透過 InputChannel 送出去。至此,一個按鍵從核心到 App 與 PWM 的完整旅程才真正收尾。
Picasso 圖片加載庫詳解:二次封裝 PicassoUtils 打造微信精選
官網:https://square.github.io/picasso/ Picasso(學名畢加索)是 Square 公司開源的一款 Android 圖形緩存庫,使
Android 加載本地圖片縮略圖的終極方案
學 Android 果然還是要在項目裡摸爬滾打,脫離實際一切都是空談~! 花了一下午,終於搞定了項目中「獲取本地圖片縮略圖並顯示在 ListView 上、點擊還能拿到該圖
自定義 View 之 ProgressBar:測量、繪制與自定義屬性一次講透
這次要動手做一個圓形的 ProgressBar。順便把自定義 View 裡兩個繞不開的知識點講清楚:View 的測量與自定義屬性。 先看效果: 一、準備工作:先想清
Android 編譯系統剖析(三):make 的默認編譯流程
本文的目標是徹底摸清「默認編譯整個 Android 系統」時的程式碼流程。 當我們執行 make 時,它會查找並執行當前的 Makefile。在 Android 頂層源碼