Android中事件傳遞分析
前段時間工作中遇到了一個問題,即在軟鍵盤彈出后想監聽back事件,但是在Activity中重寫了對應的onKeyDown函數卻怎么也監聽不到,經過一陣Google之后才發現需要重寫View的dispatchKeyEventPreIme函數才行。當時就覺得這個函數名字很熟悉,仔細思索一番以后才恍然大悟,當初看WMS源碼的時候有過這方面的了解,現在卻把它忘到了九霄云外,于是決定寫這篇文章,權當記錄。
InputManagerService
首先我們知道,不論是“鍵盤事件”還是“點擊事件”,都是系統底層傳給我們的,當然這里最底層的Linux Kernel我們不去討論,我們的起點從Framework層開始。有看過Android Framework層源碼的同學已經比較清楚,其中存在非常多的XXXManagerService,它們運行在system_server進程中,著名的如AMS(ActivityManagerService)和WMS(WindowManagerService)等等。這里和Android事件相關的Service就是InputManagerService,那么就先讓我們看看它是如何進行工作的吧。
public void start() {
Slog.i(TAG, "Starting input manager");
nativeStart(mPtr);
........
}
看到這個nativeStart,是不是倒吸一口涼氣,沒錯,是一個native方法。不過這也沒辦法,畢竟底層嘛,少不了和c打交道~
static void nativeStart(JNIEnv* env, jclass /* clazz */, jlong ptr) {
NativeInputManager* im = reinterpret_cast<NativeInputManager*>(ptr);
status_t result = im->getInputManager()->start();
if (result) {
jniThrowRuntimeException(env, "Input manager could not be started.");
}
}
可以看到,調用了InputManager的start方法。
status_t InputManager::start() {
status_t result = mDispatcherThread->run("InputDispatcher", PRIORITY_URGENT_DISPLAY);
if (result) {
ALOGE("Could not start InputDispatcher thread due to error %d.", result);
return result;
}
result = mReaderThread->run("InputReader", PRIORITY_URGENT_DISPLAY);
if (result) {
ALOGE("Could not start InputReader thread due to error %d.", result);
mDispatcherThread->requestExit();
return result;
}
return OK;
}
其中初始化了兩個線程——ReaderThread和DispatcherThread。這兩個線程的作用非常重要,前者接受來自設備的事件并且將其封裝成上層看得懂的信息,后者負責把事件分發出去。可以說,我們上層的Activity或者是View的事件,都是來自于這兩個線程。這里我不展開講了,有興趣的同學可以自行根據源碼進行分析。有趣的是,DispatcherThread在輪詢點擊事件的過程中,采用的Looper的形式,可見Android中的源碼真的是處處相關聯,所以不要覺得某一部分的源碼看了沒用,說不定以后你就會用到了。
ViewRootImpl
從前一小節我們得知,設備的點擊事件是通過InputManagerService來進行傳遞的,其中存在兩個線程一個用于處理,一個用于分發,那么事件分發到哪里去呢?直接發到Activity或者View中嗎?這顯然是不合理的,所以Framework層中存在一個ViewRootImpl類,作為兩者溝通的橋梁。需要注意的是,該類在老版本的源碼中名為ViewRoot。
ViewRootImpl這個類是在Activity的resume生命周期中初始化的,調用了ViewRootImpl.setView函數,下面讓我們看看這個函數做了什么。
public void setView(View view, WindowManager.LayoutParams attrs, View panelParentView) {
synchronized (this) {
if (mView == null) {
mView = view;
..........
if ((mWindowAttributes.inputFeatures
& WindowManager.LayoutParams.INPUT_FEATURE_NO_INPUT_CHANNEL) == 0) {
mInputChannel = new InputChannel();
}
try {
mOrigWindowType = mWindowAttributes.type;
mAttachInfo.mRecomputeGlobalAttributes = true;
collectViewAttributes();
//Attention here!!!
res = mWindowSession.addToDisplay(mWindow, mSeq, mWindowAttributes,
getHostVisibility(), mDisplay.getDisplayId(),
mAttachInfo.mContentInsets, mAttachInfo.mStableInsets,
mAttachInfo.mOutsets, mInputChannel);
} catch (RemoteException e) {
mAdded = false;
mView = null;
mAttachInfo.mRootView = null;
mInputChannel = null;
mFallbackEventHandler.setView(null);
unscheduleTraversals();
setAccessibilityFocus(null, null);
throw new RuntimeException("Adding window failed", e);
} finally {
if (restore) {
attrs.restore();
}
}
............
if (mInputChannel != null) {
if (mInputQueueCallback != null) {
mInputQueue = new InputQueue();
mInputQueueCallback.onInputQueueCreated(mInputQueue);
}
mInputEventReceiver = new WindowInputEventReceiver(mInputChannel,
Looper.myLooper());
}
}
}
}
這個方法非常的長,我先截取了一小段,看我標注的[Attention here],創建了一個InputChannel的實例,并且通過mWindowSession.addToDisplay方法將其添加到了mWindowSession中。
final IWindowSession mWindowSession;
public ViewRootImpl(Context context, Display display) {
mContext = context;
mWindowSession = WindowManagerGlobal.getWindowSession();
......
}
public static IWindowSession getWindowSession() {
synchronized (WindowManagerGlobal.class) {
if (sWindowSession == null) {
try {
InputMethodManager imm = InputMethodManager.getInstance();
IWindowManager windowManager = getWindowManagerService();
sWindowSession = windowManager.openSession(
new IWindowSessionCallback.Stub() {
@Override
public void onAnimatorScaleChanged(float scale) {
ValueAnimator.setDurationScale(scale);
}
},
imm.getClient(), imm.getInputContext());
} catch (RemoteException e) {
Log.e(TAG, "Failed to open window session", e);
}
}
return sWindowSession;
}
}
mWindowSession是什么呢?通過上面的代碼我們可以知道,mWindowSession就是WindowManagerService中的一個內部實例。getWindowManagerService拿到的事WindowManagerNative的proxy對象,所以由此我們可以知道,mWindowSession也是用來IPC的。
如果大家對上面一段話不是很了解,換句話說不了解Android的Binder機制的話,可以先去自行了結一下。
回到上面的setView函數,mWindowSession.addToDisplay方法肯定調用的是對應remote的addToDisplay方法,其中會調用WindowManagerService::addWindow方法去將InputChannel注冊到WMS中。
看到這里大家可能會有疑問,第一小節說的是InputManagerService管理設備的事件,怎么到了這一小節就變成了和WindowManagerService打交道呢?秘密其實就在mWindowSession.addToDisplay方法中。
WindowManagerService
public int addWindow(Session session, IWindow client, int seq,
WindowManager.LayoutParams attrs, int viewVisibility, int displayId,
Rect outContentInsets, Rect outStableInsets, Rect outOutsets,
InputChannel outInputChannel) {
..........
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);
}
...........
}
可以看到在addWindow方法中,創建了一個InputChannel的數組,數組中有兩個InputChannel,第一個是remote端的,通過 mInputManager.registerInputChannel方法講其注冊到InputManager中;第二個是native端的,通過inputChannels[1].transferTo(outInputChannel)方法,將其指向outInputChannel,而outInputChannel就是前面setView傳過來的那個InputChannel,也就是ViewRootImpl里的。
通過這一段代碼,我們知道,當Activity初始化的時候,我們就會在WMS中注冊兩個InputChannel,remote端的InputChannel注冊到InputManager中,用于接受ReaderThread和DispatcherThread傳遞過來的信息,native端的InputChannel指向ViewRootImpl中的InputChannel,用于接受remote端的InputChannel傳遞過來的信息。
最后,回到ViewRootImpl的setView方法的最后,有這么一句:
mInputEventReceiver = new WindowInputEventReceiver(mInputChannel,
Looper.myLooper());
WindowInputEventReceiver,就是我們最終接受事件的接收器了。
鍵盤事件的傳遞
下面讓我們看看WindowInputEventReceiver做了什么。
final class WindowInputEventReceiver extends InputEventReceiver {
public WindowInputEventReceiver(InputChannel inputChannel, Looper looper) {
super(inputChannel, looper);
}
@Override
public void onInputEvent(InputEvent event) {
enqueueInputEvent(event, this, 0, true);
}
@Override
public void onBatchedInputEventPending() {
if (mUnbufferedInputDispatch) {
super.onBatchedInputEventPending();
} else {
scheduleConsumeBatchedInput();
}
}
@Override
public void dispose() {
unscheduleConsumeBatchedInput();
super.dispose();
}
}
很簡單,回調到onInputEvent函數的時候,就調用ViewRootImpl的enqueueInputEvent函數。
void enqueueInputEvent(InputEvent event,
InputEventReceiver receiver, int flags, boolean processImmediately) {
.........
if (processImmediately) {
doProcessInputEvents();
} else {
scheduleProcessInputEvents();
}
}
可以看到,如果需要立即處理該事件,就直接調用doProcessInputEvents函數,否則調用scheduleProcessInputEvents函數加入調度。
這里我們一切從簡,直接看doProcessInputEvents函數。
void doProcessInputEvents() {
........
deliverInputEvent(q);
........
}
private void deliverInputEvent(QueuedInputEvent q) {
Trace.asyncTraceBegin(Trace.TRACE_TAG_VIEW, "deliverInputEvent",
q.mEvent.getSequenceNumber());
if (mInputEventConsistencyVerifier != null) {
mInputEventConsistencyVerifier.onInputEvent(q.mEvent, 0);
}
InputStage stage;
if (q.shouldSendToSynthesizer()) {
stage = mSyntheticInputStage;
} else {
stage = q.shouldSkipIme() ? mFirstPostImeInputStage : mFirstInputStage;
}
if (stage != null) {
stage.deliver(q);
} else {
finishInputEvent(q);
}
}
可以看到deliverInputEvent函數中,存在一個很有意思的東西叫InputStage,通過一些標記位去確定到底是用哪個InputStage去處理。
這些InputStage是在哪里初始化的呢?顯示是在setView函數啦。
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;
可以看到初始化了如此多的InputStage。這些stage的調用順序是嚴格控制的,Ime的意思是輸入法,所以大家應該了解這些preIme和postIme是什么意思了吧?
從上面得知,最終會調用InputStage的deliver函數:
public final void deliver(QueuedInputEvent q) {
if ((q.mFlags & QueuedInputEvent.FLAG_FINISHED) != 0) {
forward(q);
} else if (shouldDropInputEvent(q)) {
finish(q, false);
} else {
apply(q, onProcess(q));
}
}
其apply方法被各個子類重寫的,下面我們以ViewPreImeInputStage為例:
@Override
protected int onProcess(QueuedInputEvent q) {
if (q.mEvent instanceof KeyEvent) {
return processKeyEvent(q);
}
return FORWARD;
}
private int processKeyEvent(QueuedInputEvent q) {
final KeyEvent event = (KeyEvent)q.mEvent;
if (mView.dispatchKeyEventPreIme(event)) {
return FINISH_HANDLED;
}
return FORWARD;
}
可以看到,會調用View的dispatchKeyEventPreIme方法。看到這里,文章最開頭的那個問題也就迎刃而解了,為什么在輸入法彈出的情況下,監聽Activity的onKeyDown沒有用呢?因為該事件被輸入法消耗了,對應的,就是說走到了imeStage這個InputStage中;那為什么重寫View的dispatchKeyEventPreIme方法就可以呢?因為它是在ViewPreImeInputStage中被調用的,還沒有輪到imeStage呢~
后記
通過這樣的一篇分析,相信大家對Android中的事件分發已經有了一定的了解。
最重要的,還是要Read the fucking source code啊!
來自:http://zjutkz.net/2016/11/17/Android中事件傳遞分析/