为了账号安全,请及时绑定邮箱和手机立即绑定

Android事件分发机制源码解析

标签:
Android

在更简单的学习Android事件分发中,使用日志、比喻、流程图相结合的方式,以更简单的方法去分析了Android的事件分发机制。本篇文章将采用分析源码的方式,更深入的解析Android的事件分发机制。

一、从Activity开始

Android的触摸事件,是由windowManagerService进行采集,之后传递到Activiy进行处理。我们这里从Activity#dispatchTouchEvent方法开始解析

[代码]java代码:

?

1

2

3

4

5

6

7

8

9

public boolean dispatchTouchEvent(MotionEvent   ev) {

    if (ev.getAction() ==   MotionEvent.ACTION_DOWN) {

        onUserInteraction();

    }

    if (getWindow().superDispatchTouchEvent(ev))   {

        return true;

    }

    return onTouchEvent(ev);

}

 

上述代码中,onUserInteraction()是一个空的实现,我们直接来看下
getWindow().superDispatchTouchEvent(ev)方法。window是一个抽象的方法,不过系统给它提供了一个实现类PhoneWindow,我们这里看下它的superDispatchTouchEvent(ev)方法。

[代码]java代码:

?

1

2

3

public boolean superDispatchTouchEvent(MotionEvent   event) {

    return mDecor.superDispatchTouchEvent(event);

}

 

上述代码调用了DecorView类的superDispatchTouchEvent方法,继续跟进

[代码]java代码:

?

1

2

3

public boolean superDispatchTouchEvent(MotionEvent   event) {

    return super.dispatchTouchEvent(event);

}

 

上述代码调用了父类的dispatchTouchEvent方法,DecorView的父类为FrameLayout,其直接继承了ViewGroup#dispatchTouchEvent方法。

二、ViewGroup中的事件分发

ViewGroup#dispatchTouchEvent方法比较长,这里只截取部分进行分析

[代码]java代码:

?

001

002

003

004

005

006

007

008

009

010

011

012

013

014

015

016

017

018

019

020

021

022

023

024

025

026

027

028

029

030

031

032

033

034

035

036

037

038

039

040

041

042

043

044

045

046

047

048

049

050

051

052

053

054

055

056

057

058

059

060

061

062

063

064

065

066

067

068

069

070

071

072

073

074

075

076

077

078

079

080

081

082

083

084

085

086

087

088

089

090

091

092

093

094

095

096

097

098

099

100

101

102

103

104

105

106

107

108

109

110

111

112

113

114

115

116

117

118

119

120

121

122

123

124

125

126

127

128

129

130

131

132

133

134

135

136

137

138

139

140

141

142

143

144

145

146

147

148

149

150

151

152

153

154

155

156

157

158

159

160

161

162

163

164

165

166

167

168

169

170

171

172

173

174

175

176

177

178

179

180

181

public boolean dispatchTouchEvent(MotionEvent   ev) {

 

    ...

        //   在ACTION_DOWN事件时,初始化Touch标记

        //   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.

            cancelAndClearTouchTargets(ev);

            resetTouchState();

        }

 

        //   Check for interception.

        final boolean intercepted;

        if (actionMasked == MotionEvent.ACTION_DOWN

                ||   mFirstTouchTarget != null) {

            //   是否拦截的标志位,假如设置requestDisallowInterceptTouchEvent(true),

            //   则为true,不拦截事件

            final boolean disallowIntercept = (mGroupFlags & FLAG_DISALLOW_INTERCEPT) != 0;

            if (!disallowIntercept) {

                //   默认返回false

                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;

        }

 

        ...

 

        //   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;

        //   不是ACTION_CANCEL事件,并且不拦截事件

        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;

                    //   遍历所有子View

                    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);

 

                        ...

 

                        resetCancelNextUpFlag(child);

                        //   把事件(ACTION_DOWN、ACTION_POINTER_DOWN、ACTION_HOVER_MOVE)传递给子View处理

                        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();

                            newTouchTarget   = addTouchTarget(child, idBitsToAssign);

                            alreadyDispatchedToNewTouchTarget   = true;

                            break;

                        }

                        ...

                    }

                    ...

                }

                ...

                }

            }

        }

 

        //   分发事件到目标View

        //   Dispatch to touch targets.

        if (mFirstTouchTarget == null) {

            //   没有找到事件分发目标的情况,将会调用自己的onTouchEvent方法

            //   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) {

                final TouchTarget next = target.next;

                //   ACTION_DOWN已经完成事件分发,并消费了事件,直接返回true

                if (alreadyDispatchedToNewTouchTarget   && target == newTouchTarget) {

                    handled   = true;

                }   else {

                    final boolean cancelChild = resetCancelNextUpFlag(target.child)

                            ||   intercepted;

                    //   其余事件则需要传递给目标View进行处理

                    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;

            }

        }

 

        //   对ACTION_CANCEL事件进行处理

        //   Update list of touch targets for pointer up or cancel, if needed.

        if (canceled

                ||   actionMasked == MotionEvent.ACTION_UP

                ||   actionMasked == MotionEvent.ACTION_HOVER_MOVE) {

            //   重置Touch状态

            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;

}

 

// 默认返回false

public boolean onInterceptTouchEvent(MotionEvent   ev) {

    return false;

}</view>

 

我们现在来看看传递事件的dispatchTransformedTouchEvent方法,同样我也只是截取了其中比较关键的部分

[代码]java代码:

?

01

02

03

04

05

06

07

08

09

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

private boolean dispatchTransformedTouchEvent(MotionEvent   event, boolean cancel,

        View   child, int desiredPointerIdBits)   {

    final boolean handled;

    ...

    final MotionEvent transformedEvent;

    // 对transformedEvent的一系列计算

    ...

    if (child == null) {

        //   如果没有子View,则执行super.dispatchTouchEvent方法,

        //   调用自己的onTouchEvent方法

        handled   = super.dispatchTouchEvent(transformedEvent);

    } else {

        final float offsetX = mScrollX - child.mLeft;

        final float offsetY = mScrollY - child.mTop;

        transformedEvent.offsetLocation(offsetX,   offsetY);

        if (! child.hasIdentityMatrix()) {

            transformedEvent.transform(child.getInverseMatrix());

        }

        //   如果有子View,则调用子View#dispatchTouchEvent方法

        handled   = child.dispatchTouchEvent(transformedEvent);

    }

 

    // Done.

    transformedEvent.recycle();

    return handled;

}

 

三、View中的事件处理

ViewGroup中不拦截事件,调用子View#dispatchTouchEvent方法进行处理

[代码]java代码:

?

01

02

03

04

05

06

07

08

09

10

11

12

13

14

15

16

17

18

19

20

21

22

public boolean dispatchTouchEvent(MotionEvent   event) {

 

    ...

    if (onFilterTouchEventForSecurity(event)) {

        //   如果设置了OnTouchListener,使用onTouch对事件进行处理,

        //   并返回true,则不需要再执行onTouchEvent方法

        //noinspection   SimplifiableIfStatement

        ListenerInfo   li = mListenerInfo;

        if (li != null && li.mOnTouchListener != null

                &&   (mViewFlags & ENABLED_MASK) == ENABLED

                &&   li.mOnTouchListener.onTouch(this, event)) {

            result   = true;

        }

 

        if (!result && onTouchEvent(event))   {

            result   = true;

        }

    }

    ...

 

    return result;

}

 

这里继续看看View#onTouchEvent方法

[代码]java代码:

?

01

02

03

04

05

06

07

08

09

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

public boolean onTouchEvent(MotionEvent   event) {

    final float x = event.getX();

    final float y = event.getY();

    final int viewFlags = mViewFlags;

    final int action = event.getAction();

 

    ...

 

    if (((viewFlags & CLICKABLE) ==   CLICKABLE ||

            (viewFlags   & LONG_CLICKABLE) == LONG_CLICKABLE) ||

            (viewFlags   & CONTEXT_CLICKABLE) == CONTEXT_CLICKABLE) {

        switch (action) {

            case MotionEvent.ACTION_UP:

                ...

                //   移除长按

                removeLongPressCallback();

                ...

                    //   检查单击

                    performClick();

                ...

                break;

 

            case MotionEvent.ACTION_DOWN:

                ...

                //   检测是否为长按

                checkForLongClick(0);

                ...

                break;

 

            ....

        }

 

        return true;

    }

 

    return false;

}

 

上述代码,主要是检查View是否可以点击,如果可点击,则会返回true,同时也会执行可点击的事件。

四、小结
通过本文的源码解析,我们可以更深入的理解Android的事件分发。可以简单的推出一个流程 : ActivityPhoneWindowDecorViewViewGroupView。

原文链接:http://www.apkbus.com/blog-705730-61800.html

点击查看更多内容
TA 点赞

若觉得本文不错,就分享一下吧!

评论

作者其他优质文章

正在加载中
  • 推荐
  • 评论
  • 收藏
  • 共同学习,写下你的评论
感谢您的支持,我会继续努力的~
扫码打赏,你说多少就多少
赞赏金额会直接到老师账户
支付方式
打开微信扫一扫,即可进行扫码打赏哦
今天注册有机会得

100积分直接送

付费专栏免费学

大额优惠券免费领

立即参与 放弃机会
意见反馈 帮助中心 APP下载
官方微信

举报

0/150
提交
取消