深入解析Android中的事件传递
前言
前段时间工作中遇到了一个问题,即在软键盘弹出后想监听back事件,但是在Activity中重写了对应的onKeyDown函数却怎么也监听不到,经过一阵Google之后才发现需要重写View的dispatchKeyEventPreIme函数才行。当时就觉得这个函数名字很熟悉,仔细思索一番以后才恍然大悟,当初看WMS源码的时候有过这方面的了解,现在却把它忘到了九霄云外,于是决定写这篇文章,权当记录。
InputManagerService
首先我们知道,不论是“键盘事件”还是“点击事件”,都是系统底层传给我们的,当然这里最底层的LinuxKernel我们不去讨论,我们的起点从Framework层开始。有看过AndroidFramework层源码的同学已经比较清楚,其中存在非常多的XXXManagerService,它们运行在system_server进程中,著名的如AMS(ActivityManagerService)和WMS(WindowManagerService)等等。这里和Android事件相关的Service就是InputManagerService,那么就先让我们看看它是如何进行工作的吧。
publicvoidstart(){
Slog.i(TAG,"Startinginputmanager");
nativeStart(mPtr);
........
}
看到这个nativeStart,是不是倒吸一口凉气,没错,是一个native方法。不过这也没办法,毕竟底层嘛,少不了和c打交道~
staticvoidnativeStart(JNIEnv*env,jclass/*clazz*/,jlongptr){
NativeInputManager*im=reinterpret_cast(ptr);
status_tresult=im->getInputManager()->start();
if(result){
jniThrowRuntimeException(env,"Inputmanagercouldnotbestarted.");
}
}
可以看到,调用了InputManager的start方法。
status_tInputManager::start(){
status_tresult=mDispatcherThread->run("InputDispatcher",PRIORITY_URGENT_DISPLAY);
if(result){
ALOGE("CouldnotstartInputDispatcherthreadduetoerror%d.",result);
returnresult;
}
result=mReaderThread->run("InputReader",PRIORITY_URGENT_DISPLAY);
if(result){
ALOGE("CouldnotstartInputReaderthreadduetoerror%d.",result);
mDispatcherThread->requestExit();
returnresult;
}
returnOK;
}
其中初始化了两个线程——ReaderThread和DispatcherThread。这两个线程的作用非常重要,前者接受来自设备的事件并且将其封装成上层看得懂的信息,后者负责把事件分发出去。可以说,我们上层的Activity或者是View的事件,都是来自于这两个线程。这里我不展开讲了,有兴趣的同学可以自行根据源码进行分析。有趣的是,DispatcherThread在轮询点击事件的过程中,采用的Looper的形式,可见Android中的源码真的是处处相关联,所以不要觉得某一部分的源码看了没用,说不定以后你就会用到了。
ViewRootImpl
从前一小节我们得知,设备的点击事件是通过InputManagerService来进行传递的,其中存在两个线程一个用于处理,一个用于分发,那么事件分发到哪里去呢?直接发到Activity或者View中吗?这显然是不合理的,所以Framework层中存在一个ViewRootImpl类,作为两者沟通的桥梁。需要注意的是,该类在老版本的源码中名为ViewRoot。
ViewRootImpl这个类是在Activity的resume生命周期中初始化的,调用了ViewRootImpl.setView函数,下面让我们看看这个函数做了什么。
publicvoidsetView(Viewview,WindowManager.LayoutParamsattrs,ViewpanelParentView){
synchronized(this){
if(mView==null){
mView=view;
..........
if((mWindowAttributes.inputFeatures
&WindowManager.LayoutParams.INPUT_FEATURE_NO_INPUT_CHANNEL)==0){
mInputChannel=newInputChannel();
}
try{
mOrigWindowType=mWindowAttributes.type;
mAttachInfo.mRecomputeGlobalAttributes=true;
collectViewAttributes();
//Attentionhere!!!
res=mWindowSession.addToDisplay(mWindow,mSeq,mWindowAttributes,
getHostVisibility(),mDisplay.getDisplayId(),
mAttachInfo.mContentInsets,mAttachInfo.mStableInsets,
mAttachInfo.mOutsets,mInputChannel);
}catch(RemoteExceptione){
mAdded=false;
mView=null;
mAttachInfo.mRootView=null;
mInputChannel=null;
mFallbackEventHandler.setView(null);
unscheduleTraversals();
setAccessibilityFocus(null,null);
thrownewRuntimeException("Addingwindowfailed",e);
}finally{
if(restore){
attrs.restore();
}
}
............
if(mInputChannel!=null){
if(mInputQueueCallback!=null){
mInputQueue=newInputQueue();
mInputQueueCallback.onInputQueueCreated(mInputQueue);
}
mInputEventReceiver=newWindowInputEventReceiver(mInputChannel,
Looper.myLooper());
}
}
}
}
这个方法非常的长,我先截取了一小段,看我标注的[Attentionhere],创建了一个InputChannel的实例,并且通过mWindowSession.addToDisplay方法将其添加到了mWindowSession中。
finalIWindowSessionmWindowSession;
publicViewRootImpl(Contextcontext,Displaydisplay){
mContext=context;
mWindowSession=WindowManagerGlobal.getWindowSession();
......
}
publicstaticIWindowSessiongetWindowSession(){
synchronized(WindowManagerGlobal.class){
if(sWindowSession==null){
try{
InputMethodManagerimm=InputMethodManager.getInstance();
IWindowManagerwindowManager=getWindowManagerService();
sWindowSession=windowManager.openSession(
newIWindowSessionCallback.Stub(){
@Override
publicvoidonAnimatorScaleChanged(floatscale){
ValueAnimator.setDurationScale(scale);
}
},
imm.getClient(),imm.getInputContext());
}catch(RemoteExceptione){
Log.e(TAG,"Failedtoopenwindowsession",e);
}
}
returnsWindowSession;
}
}
mWindowSession是什么呢?通过上面的代码我们可以知道,mWindowSession就是WindowManagerService中的一个内部实例。getWindowManagerService拿到的事WindowManagerNative的proxy对象,所以由此我们可以知道,mWindowSession也是用来IPC的。
如果大家对上面一段话不是很了解,换句话说不了解Android的Binder机制的话,可以先去自行了结一下。
回到上面的setView函数,mWindowSession.addToDisplay方法肯定调用的是对应remote的addToDisplay方法,其中会调用WindowManagerService::addWindow方法去将InputChannel注册到WMS中。
看到这里大家可能会有疑问,第一小节说的是InputManagerService管理设备的事件,怎么到了这一小节就变成了和WindowManagerService打交道呢?秘密其实就在mWindowSession.addToDisplay方法中。
WindowManagerService
publicintaddWindow(Sessionsession,IWindowclient,intseq,
WindowManager.LayoutParamsattrs,intviewVisibility,intdisplayId,
RectoutContentInsets,RectoutStableInsets,RectoutOutsets,
InputChanneloutInputChannel){
..........
if(outInputChannel!=null&&(attrs.inputFeatures
&WindowManager.LayoutParams.INPUT_FEATURE_NO_INPUT_CHANNEL)==0){
Stringname=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=newWindowInputEventReceiver(mInputChannel, Looper.myLooper());
WindowInputEventReceiver,就是我们最终接受事件的接收器了。
键盘事件的传递
下面让我们看看WindowInputEventReceiver做了什么。
finalclassWindowInputEventReceiverextendsInputEventReceiver{
publicWindowInputEventReceiver(InputChannelinputChannel,Looperlooper){
super(inputChannel,looper);
}
@Override
publicvoidonInputEvent(InputEventevent){
enqueueInputEvent(event,this,0,true);
}
@Override
publicvoidonBatchedInputEventPending(){
if(mUnbufferedInputDispatch){
super.onBatchedInputEventPending();
}else{
scheduleConsumeBatchedInput();
}
}
@Override
publicvoiddispose(){
unscheduleConsumeBatchedInput();
super.dispose();
}
}
很简单,回调到onInputEvent函数的时候,就调用ViewRootImpl的enqueueInputEvent函数。
voidenqueueInputEvent(InputEventevent,
InputEventReceiverreceiver,intflags,booleanprocessImmediately){
.........
if(processImmediately){
doProcessInputEvents();
}else{
scheduleProcessInputEvents();
}
}
可以看到,如果需要立即处理该事件,就直接调用doProcessInputEvents函数,否则调用scheduleProcessInputEvents函数加入调度。
这里我们一切从简,直接看doProcessInputEvents函数。
voiddoProcessInputEvents(){
........
deliverInputEvent(q);
........
}
privatevoiddeliverInputEvent(QueuedInputEventq){
Trace.asyncTraceBegin(Trace.TRACE_TAG_VIEW,"deliverInputEvent",
q.mEvent.getSequenceNumber());
if(mInputEventConsistencyVerifier!=null){
mInputEventConsistencyVerifier.onInputEvent(q.mEvent,0);
}
InputStagestage;
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=newSyntheticInputStage(); InputStageviewPostImeStage=newViewPostImeInputStage(mSyntheticInputStage); InputStagenativePostImeStage=newNativePostImeInputStage(viewPostImeStage, "aq:native-post-ime:"+counterSuffix); InputStageearlyPostImeStage=newEarlyPostImeInputStage(nativePostImeStage); InputStageimeStage=newImeInputStage(earlyPostImeStage, "aq:ime:"+counterSuffix); InputStageviewPreImeStage=newViewPreImeInputStage(imeStage); InputStagenativePreImeStage=newNativePreImeInputStage(viewPreImeStage, "aq:native-pre-ime:"+counterSuffix); mFirstInputStage=nativePreImeStage; mFirstPostImeInputStage=earlyPostImeStage;
可以看到初始化了如此多的InputStage。这些stage的调用顺序是严格控制的,Ime的意思是输入法,所以大家应该了解这些preIme和postIme是什么意思了吧?
从上面得知,最终会调用InputStage的deliver函数:
publicfinalvoiddeliver(QueuedInputEventq){
if((q.mFlags&QueuedInputEvent.FLAG_FINISHED)!=0){
forward(q);
}elseif(shouldDropInputEvent(q)){
finish(q,false);
}else{
apply(q,onProcess(q));
}
}
其apply方法被各个子类重写的,下面我们以ViewPreImeInputStage为例:
@Override
protectedintonProcess(QueuedInputEventq){
if(q.mEventinstanceofKeyEvent){
returnprocessKeyEvent(q);
}
returnFORWARD;
}
privateintprocessKeyEvent(QueuedInputEventq){
finalKeyEventevent=(KeyEvent)q.mEvent;
if(mView.dispatchKeyEventPreIme(event)){
returnFINISH_HANDLED;
}
returnFORWARD;
}
可以看到,会调用View的dispatchKeyEventPreIme方法。看到这里,文章最开头的那个问题也就迎刃而解了,为什么在输入法弹出的情况下,监听Activity的onKeyDown没有用呢?因为该事件被输入法消耗了,对应的,就是说走到了imeStage这个InputStage中;那为什么重写View的dispatchKeyEventPreIme方法就可以呢?因为它是在ViewPreImeInputStage中被调用的,还没有轮到imeStage呢~
总结
通过这样的一篇分析,相信大家对Android中的事件分发已经有了一定的了解,希望本文的内容对大家的学习或者工作能带来一定的帮助,谢谢大家对毛票票的支持。