Android事件分发机制源码分析之Activity篇

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq_435559203/article/details/53002298

在之前的事件分发分析中,曾提及到View的事件是由ViewGroup分发的,然而ViewGroup的事件我们只是稍微带过是由Activity分发的。而我们知道,事件产生于用户按下屏幕的一瞬间,事件生成后,经过一系列的过程来到我们的Activity层,那么事件是怎样从Activity传递到根ViewGroup的呢?

注:建议先阅读 Android事件分发机制源码分析之View篇 Android事件分发机制源码分析之ViewGroup篇

实例代码

我们依旧用回之前用过的代码。对MainActivity稍作修改。

public class MainActivity extends Activity {
    private static final String TAG = "MainActivity";
    private CustomButton mbtn;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        mbtn = (CustomButton) findViewById(R.id.button);
    }


    @Override
    public boolean dispatchTouchEvent(MotionEvent ev) {
        Log.i(TAG, "dispatchTouchEvent" + ev.getAction());
        return super.dispatchTouchEvent(ev);
    }

    @Override
    public void onUserInteraction() {
        Log.i(TAG, "onUserInteraction");
        super.onUserInteraction();
    }

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        Log.i(TAG, "onTouchEvent" + event.getAction());
        return super.onTouchEvent(event);
    }
}

我们看一下当点击CustomButton的打印情况:

11-01 15:47:52.738 30414-30414/com.example.pc.myapplication I/MainActivity: dispatchTouchEvent0
11-01 15:47:52.738 30414-30414/com.example.pc.myapplication I/MainActivity: onUserInteraction
11-01 15:47:52.739 30414-30414/com.example.pc.myapplication I/CustomLayout: dispatchTouchEvent0
11-01 15:47:52.739 30414-30414/com.example.pc.myapplication I/CustomLayout: onInterceptTouchEvent0
11-01 15:47:52.739 30414-30414/com.example.pc.myapplication I/CustomButton: dispatchTouchEvent0
11-01 15:47:52.739 30414-30414/com.example.pc.myapplication I/CustomButton: onTouchEvent0
11-01 15:47:52.799 30414-30414/com.example.pc.myapplication I/MainActivity: dispatchTouchEvent1
11-01 15:47:52.799 30414-30414/com.example.pc.myapplication I/CustomLayout: dispatchTouchEvent1
11-01 15:47:52.799 30414-30414/com.example.pc.myapplication I/CustomLayout: onInterceptTouchEvent1
11-01 15:47:52.799 30414-30414/com.example.pc.myapplication I/CustomButton: dispatchTouchEvent1
11-01 15:47:52.799 30414-30414/com.example.pc.myapplication I/CustomButton: onTouchEvent1

我们再看一下点击非CustomButton范围的打印情况:

11-01 15:54:17.025 30414-30414/com.example.pc.myapplication I/MainActivity: dispatchTouchEvent0
11-01 15:54:17.025 30414-30414/com.example.pc.myapplication I/MainActivity: onUserInteraction
11-01 15:54:17.025 30414-30414/com.example.pc.myapplication I/CustomLayout: dispatchTouchEvent0
11-01 15:54:17.025 30414-30414/com.example.pc.myapplication I/CustomLayout: onInterceptTouchEvent0
11-01 15:54:17.025 30414-30414/com.example.pc.myapplication I/CustomLayout: onTouchEvent0
11-01 15:54:17.025 30414-30414/com.example.pc.myapplication I/MainActivity: onTouchEvent0
11-01 15:54:17.051 30414-30414/com.example.pc.myapplication I/MainActivity: dispatchTouchEvent2
11-01 15:54:17.051 30414-30414/com.example.pc.myapplication I/MainActivity: onTouchEvent2
11-01 15:54:17.059 30414-30414/com.example.pc.myapplication I/MainActivity: dispatchTouchEvent2
11-01 15:54:17.060 30414-30414/com.example.pc.myapplication I/MainActivity: onTouchEvent2
11-01 15:54:17.060 30414-30414/com.example.pc.myapplication I/MainActivity: dispatchTouchEvent1
11-01 15:54:17.060 30414-30414/com.example.pc.myapplication I/MainActivity: onTouchEvent1

从结果现象中,我们假设它的ACTION_DOWN事件首先触发dispatchTouchEvent,然后触发onUserInteraction,再次onTouchEvent,接着的ACTION_UP事件触发dispatchTouchEvent后触发了onTouchEvent,也就是说ACTION_UP事件时不会触发onUserInteraction。

下面我们去看看源码的情况。

源码分析。源码参考Android API 23 Platform

我们依旧先看一下Activity的dispatchTouchEvent()。

    /**
     * Called to process touch screen events.  You can override this to
     * intercept all touch screen events before they are dispatched to the
     * window.  Be sure to call this implementation for touch screen events
     * that should be handled normally.
     *
     * @param ev The touch screen event.
     *
     * @return boolean Return true if this event was consumed.
     */
    public boolean dispatchTouchEvent(MotionEvent ev) {
        if (ev.getAction() == MotionEvent.ACTION_DOWN) {
            onUserInteraction();
        }
        if (getWindow().superDispatchTouchEvent(ev)) {
            return true;
        }
        return onTouchEvent(ev);
    }

好像代码比想象中要少一点。首先在第一个条件判断中,我们可以看到只有是ACTION_DOWN的动作才会去执行onUserInteraction(),验证了上面打印台在ACTION_UP动作中没有执行onUserInteraction()。另外当我们点开onUserInteraction()时,发现它是一个空方法:

    /**
     * Called whenever a key, touch, or trackball event is dispatched to the
     * activity.  Implement this method if you wish to know that the user has
     * interacted with the device in some way while your activity is running.
     * This callback and {@link #onUserLeaveHint} are intended to help
     * activities manage status bar notifications intelligently; specifically,
     * for helping activities determine the proper time to cancel a notfication.
     *
     * <p>All calls to your activity's {@link #onUserLeaveHint} callback will
     * be accompanied by calls to {@link #onUserInteraction}.  This
     * ensures that your activity will be told of relevant user activity such
     * as pulling down the notification pane and touching an item there.
     *
     * <p>Note that this callback will be invoked for the touch down action
     * that begins a touch gesture, but may not be invoked for the touch-moved
     * and touch-up actions that follow.
     *
     * @see #onUserLeaveHint()
     */
    public void onUserInteraction() {
    }

从注释中我们可以了解到,当此activity在栈顶时,触屏点击按home,back,menu键等都会触发此方法。下拉statubar、旋转屏幕、锁屏不会触发此方法。所以它会用在屏保应用上,因为当你触屏机器 就会立马触发一个事件,而这个事件又不太明确是什么,正好屏保满足此需求。

继续往下看。到了第二个条件判断,先是getWindow()返回的是Window对象,对象mWindow在Activity类中是

mWindow = new PhoneWindow(this);

这个实例化的。而Window是一个抽象类,所以superDispatchTouchEvent()相当于是PhoneWindow的其中一个方法。我们看一下Window中的superDispatchTouchEvent():

    /**
     * Used by custom windows, such as Dialog, to pass the touch screen event
     * further down the view hierarchy. Application developers should
     * not need to implement or call this.
     *
     */
    public abstract boolean superDispatchTouchEvent(MotionEvent event);

从注释我们看到,不需要实现该方法。我们去看一下PhoneWindow里看下Window抽象方法的实现吧,如下:

    @Override
    public boolean superDispatchTouchEvent(MotionEvent event) {
        return mDecor.superDispatchTouchEvent(event);
    }

你会发现在PhoneWindow的superDispatchTouchEvent方法里又直接返回了另一个mDecor对象的superDispatchTouchEvent方法,mDecor是啥?继续分析。这参考工匠若水的分析。

在PhoneWindow类里发现,mDecor是DecorView类的实例,同时DecorView是PhoneWindow的内部类。而我们发现:

private final class DecorView extends FrameLayout implements RootViewSurfaceTaker

这里实现的类名称中说是root view,我们可以通过Android App开发技巧中关于UI布局优化使用的SDK工具Hierarchy Viewer(用虚拟机)来验证一下。
这里写图片描述

在上面的图看到我们的xml布局放置在FrameLayout的布局中。(从其他的Demo也是统一的效果)。那就说明,我们的xml布局是加载在一个FrameLayout中。

这里我们继续分析一下,上面PhoneWindow的superDispatchTouchEvent直接返回了DecorView的superDispatchTouchEvent,而DecorView又是继承FrameLayout,FrameLayout又是继承ViewGroup的。我们看一下DecorView类的superDispatchTouchEvent方法:

        public boolean superDispatchTouchEvent(MotionEvent event) {
            return super.dispatchTouchEvent(event);
        }

那么我们可以理清了吗?方法调来调去,在getWindow().superDispatchTouchEvent(ev)这句中其实本质执行的是一个ViewGroup的dispatchTouchEvent()方法。(这个ViewGroup是Activity特有的root view,也就是id为content的FrameLayout布局),ViewGroup的dispatchTouchEvent()的内容就是我们前两篇分析的内容。

然后我们继续往下看Activity的onTouchEvent()方法。

    /**
     * Called when a touch screen event was not handled by any of the views
     * under it.  This is most useful to process touch events that happen
     * outside of your window bounds, where there is no view to receive it.
     *
     * @param event The touch screen event being processed.
     *
     * @return Return true if you have consumed the event, false if you haven't.
     * The default implementation always returns false.
     */
    public boolean onTouchEvent(MotionEvent event) {
        if (mWindow.shouldCloseOnTouch(this, event)) {
            finish();
            return true;
        }

        return false;
    }

我们看一下条件判断里面的mWindow.shouldCloseOnTouch(this, event),我们去Window看一下shouldCloseOnTouch():

    public boolean shouldCloseOnTouch(Context context, MotionEvent event) {
        if (mCloseOnTouchOutside && event.getAction() == MotionEvent.ACTION_DOWN
                && isOutOfBounds(context, event) && peekDecorView() != null) {
            return true;
        }
        return false;
    }

这里判断mCloseOnTouchOutside变量的值及是否为ACTION_DOWN事件,同时判断event的x、y坐标是不是超出Bounds,然后检查FrameLayout的content的id的DecorView是否为空。其实没啥太重要的,这只是对于处理window边界之外的Touch事件有判断价值而已。一般都是返回false。也就是说onTouchEvent()一般也是返回false。

那么我们Activity的事件分发基本分析完。总结一下:
我们参照着流程图来总结:
这里写图片描述

  1. 事件到达Activity时,会调用Activity#dispatchTouchEvent方法,在这个方法,会把事件传递给Window,然后Window把事件传递给DecorView根布局,我们所设置的布局是它的一个子View。最后再从DecorView传递给我们的根ViewGroup。所以在Activity传递事件给ViwGroup的流程是这样的:Activity->Window->DecorView->ViewGroup
  2. dispatchTouchEvent方法中如果是ACTION_DOWN的情况下会接着触发onUserInteraction方法。
  3. 若Activity下面的子view拦截了TouchEvent事件(返回true)则Activity.onTouchEvent方法就不会执行。

猜你喜欢

转载自blog.csdn.net/qq_435559203/article/details/53002298