關於Android事件派發流程的理解
以前看了很多人介紹的Android事件派發流程,但最近使用那些來寫程式碼的時候出現了不少錯誤。所以回顧一下整個流程,簡單介紹從手觸控式螢幕幕開始到事件在View樹派發。從原始碼上分析ViewGroup.dispatchTouchEvent。
事件從觸控到View簡述
Android的事件產生是從我們觸控式螢幕幕開始,在經過Input子系統,最後達到我們的應用程式(或者經過WindowManagerService到達應用程式)。
而其中Input子系統在Java層對應著InputManagerService,其主要在native層,由InputReader讀取EventHub的元資料,將這些資料加工成InputEvent,最後發到InputDispatcher,而InputDispatcher則負責將時間發到應用程式,Input子系統流程可以參見這篇文章
對於應用層的時間流程,主要是下面的流程圖所示:
其中最後一步就是我們經常說的View事件派發流程。另外上面DecorView是經過了兩次,第一次是呼叫DecorView的dispatchTouchEvent,它的原始碼是:
@Override public boolean dispatchTouchEvent(MotionEvent ev) { final Callback cb = getCallback(); return cb != null && !isDestroyed() && mFeatureId < 0 ? cb.dispatchTouchEvent(ev) : super.dispatchTouchEvent(ev); }
Callback就是Window.Callback,Activity實現了這個介面。在Activity的attach函式中,會呼叫window的setCallback,將Activity設定給Window。所以這裡getCallback返回的就是Activity,最終會呼叫Activity的dispatchTouchEvent。下面看一下Activity的dispatchTouchEvent函式:
public boolean dispatchTouchEvent(MotionEvent ev) { if (ev.getAction() == MotionEvent.ACTION_DOWN) { onUserInteraction(); } if (getWindow().superDispatchTouchEvent(ev)) { return true; } return onTouchEvent(ev); }
在ACTION_DOWN的時候會呼叫onUserInteraction方法,然後呼叫Window(實際上是PhoneWindow)的superDispatchTouchEvent,如果Window的superDispatchTouchEvent消耗了事件,則直接返回,不會呼叫Activity的onTouchEvent方法。
@Override
public boolean superDispatchTouchEvent(MotionEvent event) {
return mDecor.superDispatchTouchEvent(event);
}
而DecorView的superDispatchTouchEvent為:
public boolean superDispatchTouchEvent(MotionEvent event) {
return super.dispatchTouchEvent(event);
}
最終還是呼叫DecorView的父類的dispatchTouchEvent,DecorView的父類是FrameLayout,它沒實現該方法,最終會呼叫ViewGroup的dispatchTouchEvent方法。從這裡開始就進入了view樹的時間派發流程了。
View樹的事件派發流程
這裡從原始碼上分析事件派發的一些特性。事件派發最開始會進入到ViewGroup的dispatchTouchEvent(DecorVIew父類),下面是ViewGroup的dispatchTouchEvent虛擬碼的分析,直接在對應的程式碼部分加了註釋:
“`
@Override
public boolean dispatchTouchEvent(MotionEvent ev) {
//一開始做一些除錯驗證,另外如果事件的目標是focused view,並且當前view就是一個focused view,
//有可能view的子View就會處理這次事件,所以將targetAccessibilityFocus設定為false。
…
boolean handled = false;
if (onFilterTouchEventForSecurity(ev)) { //檢查event是否是安全的
final int action = ev.getAction();
final int actionMasked = action & MotionEvent.ACTION_MASK;
// Handle an initial down.
if (actionMasked == MotionEvent.ACTION_DOWN) {
// Throw away all previous state when starting a new touch gesture.
// The framework may have dropped the up or cancel event for the previous gesture
// due to an app switch, ANR, or some other state change.
//清除之前的事件狀態。比如說在app切換,ANR或其他狀態改變時,系統框架將會去掉up或cancel事件。在這裡會將mFirstTouchTarget清空,mFirstTouchTarget是儲存了會接受事件的View處理物件。
cancelAndClearTouchTargets(ev);
resetTouchState(); //這裡會將mGroupFlags的FLAG_DISALLOW_INTERCEPT標識清除,
//1. 每次事件流開始的時候都會先清除FLAG_DISALLOW_INTERCEPT,所以子view的requestDisallowInterceptTouchEvent只有當次事件流有效。
}
// 判斷是否需要攔截事件,去判斷是否攔截事件的條件是此次事件是DOWN事件,或者有子類會處理這次事件(mFirstTouchTarget不為null),並且FLAG_DISALLOW_INTERCEPT沒被設定。
final boolean intercepted;
if (actionMasked == MotionEvent.ACTION_DOWN
|| mFirstTouchTarget != null) {
final boolean disallowIntercept = (mGroupFlags & FLAG_DISALLOW_INTERCEPT) != 0;
if (!disallowIntercept) {
//2. 只有有TouchTarget並且沒有被disallow,或者是ACTION_DOWN時才會呼叫onInterceptTouchEvent。
intercepted = onInterceptTouchEvent(ev);
ev.setAction(action); // restore action in case it was changed
} else {
intercepted = false;
}
} else {
// There are no touch targets and this action is not an initial down
// so this view group continues to intercept touches.
intercepted = true;
}
// If intercepted, start normal event dispatch. Also if there is already
// a view that is handling the gesture, do normal event dispatch.
if (intercepted || mFirstTouchTarget != null) {
ev.setTargetAccessibilityFocus(false);
}
// Check for cancelation.判斷是否取消
final boolean canceled = resetCancelNextUpFlag(this)
|| actionMasked == MotionEvent.ACTION_CANCEL;
// Update list of touch targets for pointer down, if needed.
final boolean split = (mGroupFlags & FLAG_SPLIT_MOTION_EVENTS) != 0;
TouchTarget newTouchTarget = null;
boolean alreadyDispatchedToNewTouchTarget = false;
if (!canceled && !intercepted) {
// If the event is targeting accessiiblity focus we give it to the
// view that has accessibility focus and if it does not handle it
// we clear the flag and dispatch the event to all children as usual.
// We are looking up the accessibility focused host to avoid keeping
// state since these events are very rare.
View childWithAccessibilityFocus = ev.isTargetAccessibilityFocus()
? findChildWithAccessibilityFocus() : null;
if (actionMasked == MotionEvent.ACTION_DOWN
|| (split && actionMasked == MotionEvent.ACTION_POINTER_DOWN)
|| actionMasked == MotionEvent.ACTION_HOVER_MOVE) {
final int actionIndex = ev.getActionIndex(); // always 0 for down
final int idBitsToAssign = split ? 1 << ev.getPointerId(actionIndex)
: TouchTarget.ALL_POINTER_IDS;
// Clean up earlier touch targets for this pointer id in case they
// have become out of sync.
removePointersFromTouchTargets(idBitsToAssign);
final int childrenCount = mChildrenCount;
if (newTouchTarget == null && childrenCount != 0) {
final float x = ev.getX(actionIndex);
final float y = ev.getY(actionIndex);
// Find a child that can receive the event.
// Scan children from front to back.
final ArrayList<View> preorderedList = buildOrderedChildList();
final boolean customOrder = preorderedList == null
&& isChildrenDrawingOrderEnabled();
final View[] children = mChildren;
for (int i = childrenCount - 1; i >= 0; i--) {
final int childIndex = customOrder
? getChildDrawingOrder(childrenCount, i) : i;
final View child = (preorderedList == null)
? children[childIndex] : preorderedList.get(childIndex);
// If there is a view that has accessibility focus we want it
// to get the event first and if not handled we will perform a
// normal dispatch. We may do a double iteration but this is
// safer given the timeframe.
if (childWithAccessibilityFocus != null) {
if (childWithAccessibilityFocus != child) {
continue;
}
childWithAccessibilityFocus = null;
i = childrenCount - 1;
}
//判斷當前的child是否可以接收事件,並且事件是否在當前的view範圍
if (!canViewReceivePointerEvents(child)
|| !isTransformedTouchPointInView(x, y, child, null)) {
ev.setTargetAccessibilityFocus(false);
continue;
}
newTouchTarget = getTouchTarget(child);
if (newTouchTarget != null) {
// Child is already receiving touch within its bounds.
// Give it the new pointer in addition to the ones it is handling.
newTouchTarget.pointerIdBits |= idBitsToAssign;
break;
}
resetCancelNextUpFlag(child);
//3.dispatchTransformedTouchEvent會將Event轉化為child座標空間(getX的變化),然後去除無關的points id,如果有必要更改事件,最後呼叫child.dispatchTouchEvent。 dispatchTransformedTouchEvent把事件派發給child,如果child成功處理了,則會將child新增到mFirstTouchTarget
if (dispatchTransformedTouchEvent(ev, false, child, idBitsToAssign)) {
// Child wants to receive touch within its bounds.
mLastTouchDownTime = ev.getDownTime();
if (preorderedList != null) {
// childIndex points into presorted list, find original index
for (int j = 0; j < childrenCount; j++) {
if (children[childIndex] == mChildren[j]) {
mLastTouchDownIndex = j;
break;
}
}
} else {
mLastTouchDownIndex = childIndex;
}
mLastTouchDownX = ev.getX();
mLastTouchDownY = ev.getY();
//addTouchTarget會建立新的TouchTarget,並將其加入到mFirstTouchTarget
newTouchTarget = addTouchTarget(child, idBitsToAssign);
alreadyDispatchedToNewTouchTarget = true;
break;
}
// The accessibility focus didn't handle the event, so clear
// the flag and do a normal dispatch to all children.
ev.setTargetAccessibilityFocus(false);
}
if (preorderedList != null) preorderedList.clear();
}
if (newTouchTarget == null && mFirstTouchTarget != null) {
// Did not find a child to receive the event.
// Assign the pointer to the least recently added target.
newTouchTarget = mFirstTouchTarget;
while (newTouchTarget.next != null) {
newTouchTarget = newTouchTarget.next;
}
newTouchTarget.pointerIdBits |= idBitsToAssign;
}
}
}
//4. 派發事件
// Dispatch to touch targets.
if (mFirstTouchTarget == null) { //mFirstTouchTarget為空表示沒有子View會處理這次事件,則交給當前的ViewGroup處理。
// No touch targets so treat this as an ordinary view.
handled = dispatchTransformedTouchEvent(ev, canceled, null,
TouchTarget.ALL_POINTER_IDS);
} else {
// Dispatch to touch targets, excluding the new touch target if we already
// dispatched to it. Cancel touch targets if necessary.
TouchTarget predecessor = null;
TouchTarget target = mFirstTouchTarget;
while (target != null) {//遍歷mFirstTouchTarget連結串列,一個一個地處理TouchTarget。
final TouchTarget next = target.next;
if (alreadyDispatchedToNewTouchTarget && target == newTouchTarget) {//新新增的不會立刻處理,ACTION_DOWN已經在前面派發了
handled = true;
} else {
final boolean cancelChild = resetCancelNextUpFlag(target.child)
|| intercepted;
//dispatchTransformedTouchEvent會將Event轉化為child座標空間(getX的變化),然後去除無關的points id,如果有必要更改事件,最後呼叫child.dispatchTouchEvent
if (dispatchTransformedTouchEvent(ev, cancelChild,
target.child, target.pointerIdBits)) {
handled = true;
}
if (cancelChild) {
if (predecessor == null) {
mFirstTouchTarget = next;
} else {
predecessor.next = next;
}
target.recycle();
target = next;
continue;
}
}
predecessor = target;
target = next;
}
}
// Update list of touch targets for pointer up or cancel, if needed.
if (canceled
|| actionMasked == MotionEvent.ACTION_UP
|| actionMasked == MotionEvent.ACTION_HOVER_MOVE) {
resetTouchState();
} else if (split && actionMasked == MotionEvent.ACTION_POINTER_UP) {
final int actionIndex = ev.getActionIndex();
final int idBitsToRemove = 1 << ev.getPointerId(actionIndex);
removePointersFromTouchTargets(idBitsToRemove);
}
}
...
//用於測試的程式碼
return handled;
}
“`
事件派發流程主要集中在這幾個方法的呼叫:
- dispatchTouchEvent 這是事件派發每個View的時候,第一個被呼叫的方法,如果是ViewGroup,dispatchTouchEvent會先去呼叫onInterceptTouchEvent是否應該攔截事件,不攔截的話會先從子View中判斷是否有處理該次事件的(在ACTION_DOWN中採用mFirstTouchTarget連結儲存會處理事件的TouchTarget),如果沒有的話則呼叫當前View的onTouchEvent。
- onInterceptTouchEvent 判斷是否應該攔截事件,ViewGroup預設實現是返回false,子View可以呼叫getParent.requestDisallowInterceptTouchEvent()來阻止父View攔截。否則只要有子View可能消費事件,該方法都會被呼叫。
- onTouchEvent這個方法是在沒有子View將會消耗事件時才會被呼叫,onClickListener,onTouchListener,onLongClickListener都是在這個方法中處理的。如果返回true表示消費這次事件。
對於事件派發流程,我覺得有幾個地方需要注意的:
1. 應該把ViewGroup以及它所包含的子View都看作是這個ViewGroup的一部分,對於一個ViewGroup是否會處理一次事件,應該是包含了它的子View是否也處理。
2. 如果整個ViewGroup以及它的子類沒有一個View處理ACTION_DOWN事件,那麼下一次就不會呼叫這個ViewGroup的dispatchTouchEvent。但是如果ACTION_DOWN返回了true,那麼下一次事件還是會繼續派發到ViewGroup,即使中間某個ACTION_MOVE返回了false。
3. onInterceptTouchEvent是在子View可能會處理該次事件,並且沒有被設定FLAG_DISALLOW_INTERCEPT才會被呼叫。正常情況下,它在ACTION_DOWN的時候一定會被呼叫的,因為在ACTION_DOWN的時候會先呼叫resetTouchState()。
原始碼是解釋很多現象的最根本的原因,閱讀原始碼能夠更好地理解事件派發流程,理解地更加深刻。