首先在網上看了很多文章包括郭霖大神的文章,他們都完美分析了ViewGroup和View的事件分發。可是還是很疑惑:觸摸事件ViewGroup是怎么捕獲到的?大神們都說Activity,Window,ViewRoot等等這些東西都是參與了事件分發,他們是怎么參加的?是誰最先接收到的觸摸事件的?我是非常不解的,因此咬牙查資料分析源碼學習了一波,接下來我們來一探究竟!由于為了講得詳細也為了全面,所以篇幅略長。所以分為兩個部分分析。本文為上半部分,用來專門分析事件從手機硬件源頭傳遞到我們自己寫的布局之前的過程。本文源碼均來自API24。
首先我先總結一下附帶上一張流程圖來提前劇透一下:
當觸摸事件發生時,手機硬件監測到后將事件交給ViewRootImpl,然后ViewRootImpl交給DecorView,然后DecorView通過Window將事件交給Activity,然后Activity將事件交給Window,Window交給DecorView,然后DecorView開始就交給我們定義的布局啦。
(圖中左邊的Receiver,Handler,Stage會在下文中講解)
接下來我們來仔細分析分析。
當我們手指觸碰屏幕時,先是手機硬件會進行相應處理然后發出通知。而在源碼中有一個叫做InputEventReceiver的接收器。顧名思義,輸入事件接收器。這個東西在哪里用到了呢?找啊找,哈哈,發現在ViewRootImpl里用到了這個東西!
而ViewRootImpl是什么呢?簡單說明一下:
他是一個用來連接Window和DecorView的紐帶,也是它來觸發完成View的包括measure、layout、draw繪制過程。它也起到向View分發一系列輸入事件的作用,例如觸摸,鍵盤事件等。
在ViewRootImpl中有一個WindowInputEventReceiver類繼承自InputEventReceiver并且重寫了onInputEvent()方法:
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);
}
那么這個類是在哪里實例化的呢?在ViewRoot的setView()方法中有這么一段代碼:
if (mInputChannel != null) {
if (mInputQueueCallback != null) {
mInputQueue = new InputQueue();
mInputQueueCallback.onInputQueueCreated(mInputQueue);
}
mInputEventReceiver = new WindowInputEventReceiver(mInputChannel,
Looper.myLooper());
}
正是在這里進行了實例化,因此在ViewRoot將Window加入到WindowManager的時候(setView()具體在何時調用讀者自行查找,可以看我的另一篇Window相關文章,這里不再深究)會創建了一個接收器。當手機硬件發出InputEvent后會調用Receiver的onInputEvent()方法,而在這里就調用了enqueueInputEvent(event, this, 0, true)(見上面的WindowInputEventReceiver源碼)。
可以看到這里調用了enqueueInputEvent()方法,顧名思義,插入輸入事件。我們繼續跟入查看:
void enqueueInputEvent(InputEvent event,
InputEventReceiver receiver, int flags, boolean processImmediately) {
....//其他代碼
if (processImmediately) {
doProcessInputEvents();
} else {
scheduleProcessInputEvents();
}
}
繼續貼出關鍵代碼,首先對processImmediately進行了判斷,如實為true,調用doProcessInputEvents()方法,如果為false,調用scheduleProcessInputEvents()方法,實際上scheduleProcessInputEvents()內部最終還是調用了doProcessInputEvents()方法,這里不深究,有興趣的同志可以自行查看。
我們再跟進doProcessInputEvents()方法(跟得好累啊...):
void doProcessInputEvents() {
...//其他代碼
deliverInputEvent(q);
...//其他代碼
}
老規矩,我們貼出關鍵代碼,在這里又調用了deliverInputEvent()方法,還是顧名思義,傳遞輸入事件,我們繼續跟進:
private void deliverInputEvent(QueuedInputEvent q) {
....//其他代碼
InputStage stage;
if (q.shouldSendToSynthesizer()) {
stage = mSyntheticInputStage;
} else {
stage = q.shouldSkipIme() ? mFirstPostImeInputStage : mFirstInputStage;
}
代碼標注處-----------------------------------
if (stage != null) {
stage.deliver(q);
} else {
finishInputEvent(q);
}
}
在上面中我們可以看到定義了一個InputStage,這是什么呢?在這里我們看一下官方注釋:
/**
* Base class for implementing a stage in the chain of responsibility
* for processing input events.
* <p>
* Events are delivered to the stage by the {@link #deliver} method. The stage
* then has the choice of finishing the event or forwarding it to the next stage.
* </p>
*/
abstract class InputStage {
大概意思就是這就是用來處理一系列輸入事件(例如觸屏,鍵盤)的類,事件通過調用deliver方法來傳遞到這個類,這個類可以選擇終止事件,可以選擇處理。
回到剛才,在上面的上面的代碼標注處調用了stage.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方法,我理解為表示處理事件。
而當一個InputEvent到來時,ViewRootImpl會尋找合適它的InputStage來處理。而ViewRootImpl中又定義了多個xxxInputStage類來繼承自InputStage類,用來針對不同事件做不同處理。
對于點擊事件來說,ViewPostImeInputStage可以處理它,因此調用ViewPostImeInputStage類中的onProcess方法。當onProcess被回調時,processKeyEvent、processPointerEvent、processTrackballEvent、processGenericMotionEvent至少有一個方法就會被調用,這些方法都是屬于ViewPostImeInputStage的。onProgress方法如下:
@Override
protected int onProcess(QueuedInputEvent q) {
if (q.mEvent instanceof KeyEvent) {
return processKeyEvent(q);
} else {
final int source = q.mEvent.getSource();
if ((source & InputDevice.SOURCE_CLASS_POINTER) != 0) {
return processPointerEvent(q);
} else if ((source & InputDevice.SOURCE_CLASS_TRACKBALL) != 0) {
return processTrackballEvent(q);
} else {
return processGenericMotionEvent(q);
}
}
}
這里就看到根據輸入事件的不同調用不同的處理方法,我們跟進幾個processxxxEvent方法進去都會發現會調用mView.dispatchxxxEvent()方法。而這些dispatchxxxEvent()方法就是分發事件機制的實現方法了。
好了說了那么久了終于撒花撒花撒.....啊呸,啥玩意兒啊?mView是個啥啊?你這坑爹啊。啥了半天啥Window啊什么之類的都沒出現。。好好好,別說了,自己挖的坑自己慢慢填。。。我們再繼續看看這個mView是啥(說實話很惡心這種變量名字,只能說比test名字好一點)。
第一反應是去ViewRootImpl的構造方法去看看,結果沒有找到賦值,然后就只能不停的去找,找了一會兒,誒?找到了,哈哈。在ViewRootImpl的setView()方法中發現,先上源碼:
public void setView(View view, WindowManager.LayoutParams attrs, View panelParentView) {
synchronized (this) {
if (mView == null) {
mView = view;
...//其他代碼
}
...//其他代碼
}
...//其他代碼
}
在這里進行了賦值,那么這個傳入的view是啥呢?其實這個傳入的View一般都是DecorView,因為ViewRoot是聯系Window和根View的紐帶,而根View都是DecorView。至于在哪里調用這個方法,有興趣的同志可以自行(算了吧我去,都寫到這兒了我一并寫出來吧)。在我的另一篇記錄里面初探Android中Window與DecorView中提到,將Window加入到WindowManager是在Activity的makeVisible()方法中調用了windowManager.addView(mDecor, getWindow().getAttributes()); 方法。而addView()方法源碼如下(在WindowManagerImpl中查看):
@Override
public void addView(@NonNull View view, @NonNull ViewGroup.LayoutParams params) {
applyDefaultToken(params);
mGlobal.addView(view, params, mContext.getDisplay(), mParentWindow);
}
我們看到是調用了 mGlobal.addView()方法,在跟進去看看:
public void addView(View view, ViewGroup.LayoutParams params,
Display display, Window parentWindow) {
...//其他代碼
ViewRootImpl root;
View panelParentView = null;
...//其他代碼
root = new ViewRootImpl(view.getContext(), display);
...//其他代碼
root.setView(view, wparams, panelParentView);
...//其他代碼
}
}
在這里看到,實例化了ViweRootImpl對象,調用了setView()方法。
!!!!看到沒!我我我曹!終于看到這個方法了!在這里將view傳入,而這個view就是傳入的DecorView!
由此真相大白!事已至此我們就已經看到了ViewRoot在事件分發過程中的作用!起到了獲取觸摸事件,然后將事件傳遞給DecorView。
那么接下來很久回到之前我們說到的調用mView.dispatchxxxEvent()方法。那么接下來我們去DecorView去看看dispatchxxxEvent()方法,這里拿觸摸事件(dispatchTouchEvent()方法)來分析,先上代碼:
@Override
public boolean dispatchTouchEvent(MotionEvent ev) {
final Window.Callback cb = mWindow.getCallback();//getCallback()返回mCallback變量
return cb != null && !mWindow.isDestroyed() && mFeatureId < 0
? cb.dispatchTouchEvent(ev) : super.dispatchTouchEvent(ev);
}
我們看到,在這里又調用了一個Window.Callback的dispatchTouchEvent()方法。沃德天吶,這又是啥(說實話我對這種變量名真是一覽無遺無可奈何/(ㄒoㄒ)/~~)
又開始苦逼的找啊找,曹,發現在Window中沒找到,然后仔細想了想,Window是在Activity的attach()方法中新建的,那么去看看呢?
結果一看,沃日啊,沃德天,我那么厲害?先上代碼:
final void attach(Context context, ActivityThread aThread,
Instrumentation instr, IBinder token, int ident,
Application application, Intent intent, ActivityInfo info,
CharSequence title, Activity parent, String id,
NonConfigurationInstances lastNonConfigurationInstances,
Configuration config, String referrer, IVoiceInteractor voiceInteractor,
Window window) {
...//其他代碼
mWindow.setCallback(this);
...//其他代碼
}
我們看到,在這里設置了CallBack,參數為this,意味著當前Activity。恍然大悟,原來CallBack就是Activity啊!那么之前的調用的cb.dispatchTouchEvent()方法就是Activity的方法。那么接下來我們就繼續去Activity看看,先上Activity的dispatchTouchEvent()源碼:
public boolean dispatchTouchEvent(MotionEvent ev) {
if (ev.getAction() == MotionEvent.ACTION_DOWN) {
onUserInteraction();//內部實現為空
}
if (getWindow().superDispatchTouchEvent(ev)) {
return true;
}
return onTouchEvent(ev);
}
首先看到調用了window的superDispatchTouchEvent()方法。我們跟進PhoneWindow(Android內唯一的Winodw實現類)看看源碼分析:
@Override
public boolean superDispatchTouchEvent(MotionEvent event) {
return mDecor.superDispatchTouchEvent(event);
}
我們可以看到,這里調用了DecorView的superDispatchTouchEvent()方法,我們繼續跟進去看看:
public boolean superDispatchTouchEvent(MotionEvent event) {
return super.dispatchTouchEvent(event);
}
這里又調用了父類的dispatchTouchEvent()方法,而DecorView是繼承自FrameLayout的,也就是繼承自ViewGroup的。因此dispatchTouchEvent()就是ViewGroup的方法。
至此我們就已經將事件分發從源頭分析到了系統內部布局的DecorView。接下來可以說就是從我們自己寫的布局開始傳遞,處理分發事件。
介于本文已經太長了,別說讀,我寫都寫暈了。那么具體的ViewGroup和View的事件分發我將會再寫一篇來進行記錄。
終于完結撒花!!!!