前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >View·从 InputEvent 到 dispatchTouchEvent 源码分析(二)

View·从 InputEvent 到 dispatchTouchEvent 源码分析(二)

作者头像
幺鹿
发布2018-08-21 15:42:25
6010
发布2018-08-21 15:42:25
举报
文章被收录于专栏:Java呓语Java呓语

大概

延续上一篇文章(View·InputEvent事件投递源码分析(一))得出的结论,本文接着对 View、ViewGroup 的事件派发、拦截进行源码分析。

ViewRootImpl#setView 里的 View 是什么?

上一篇文章得到 View 的屏幕触摸事件的处理由 ViewPostImeInputStage 类进行处理。

代码语言:javascript
复制
// ViewRootImpl.java
private int processPointerEvent(QueuedInputEvent q) {
            final MotionEvent event = (MotionEvent)q.mEvent;
            //  ……
            boolean handled = mView.dispatchPointerEvent(event);
            //  ……
            return handled ? FINISH_HANDLED : FORWARD;
        }

【 Tips : 阅读源码的时候,时刻需要带着问题去找答案。】

分析上述代码我们需要先确定 mView 指代的含义,再我们继续分析之前。 先有如下猜想: 1、 mView 是获得焦点的 View; 2、mView 是顶层的 DecorView;

我们通过查找 mView 的实例,很容易找到 setView 方法。这个方法将 mView 与 ViewRootImpl 互相绑定,mView 的身份已经呼之欲出了。但是在没有足够的证据(代码)说明之前,我们对结果仍保持怀疑。

代码语言:javascript
复制
// ViewRootImpl.java
public void setView(View view, WindowManager.LayoutParams attrs, View panelParentView) {
        synchronized (this) {
            if (mView == null) {
                mView = view;
                ...
                requestLayout();
                if (...) {
                    mInputChannel = new InputChannel();
                }
                ...
                try {
                    ...
                    res = mWindowSession.addToDisplay(mWindow, mSeq, mWindowAttributes,
                            getHostVisibility(), mDisplay.getDisplayId(),
                            mAttachInfo.mContentInsets, mAttachInfo.mStableInsets,
                            mAttachInfo.mOutsets, mInputChannel);
                } catch (RemoteException e) {
                    ...
                } finally {
                   ...
                }
            }
        }
}

因为 setView 是实例方法,所以可以将注意点先转移到 ViewRootImpl 对象是如何被创建的。

我们发现 ViewRootImpl 的构造器权限是 public 的,所以不存在单例调用。

一番查找在 WindowManagerGlobal 的 addView 中找到了如下代码。WindowManagerGlobal 提供与系统窗口管理器的低级别通信,用于与任何特定上下文无关的操作。

代码语言:javascript
复制
// WindowManagerGlobal.java
public void addView(View view, ViewGroup.LayoutParams params,
            Display display, Window parentWindow) {
        // ……
        ViewRootImpl root;
        // ……
        root = new ViewRootImpl(view.getContext(), display);
        view.setLayoutParams(wparams);

        mViews.add(view);
        mRoots.add(root);
        mParams.add(wparams);


        // do this last because it fires off messages to start doing things
        try {
            root.setView(view, wparams, panelParentView);
        } catch (RuntimeException e) {
            ...
            }
            throw e;
        }
}

原来 setView 在 WindowManagerGlobal 中被调用,而传入的 View 就是 DecorView。

ViewRootImpl 与 WindowManagerService 通讯分析

WindowManagerImpl 作为 WindowManagerGlobal的代理持有了WindowManagerGlobal对象。

代码语言:javascript
复制
public final class WindowManagerImpl implements WindowManager {
    private final WindowManagerGlobal mGlobal = WindowManagerGlobal.getInstance();

    @Override
    public void addView(@NonNull View view, @NonNull ViewGroup.LayoutParams params) {
        applyDefaultToken(params);
        mGlobal.addView(view, params, mDisplay, mParentWindow);
    }
}

继续跟踪 WindowManagerImpl 对象,发现其早已注册到 WindowManagerService 中。

代码语言:javascript
复制
// SystemServiceRegistry.java
registerService(Context.WINDOW_SERVICE, WindowManager.class,
                new CachedServiceFetcher<WindowManager>() {
    @Override
    public WindowManager createService(ContextImpl ctx) {
                return new WindowManagerImpl(ctx.getDisplay());
}});

在得知WindowManagerImpl与WindowManagerService有关联的情况下,第一时间去WindowManagerService中查找WindowManager对象。但搜索一番之后并没有发现WindowManager的实例,但是他们之前必然是有联系的。

既然没有表现的那么直白,那肯定是通过中介的形式转发了。而WindowManagerService又有着对 Window 的最终实现,于是乎我们重新回到 ViewRootImpl 中找到 setView中的代码片段。

代码语言:javascript
复制
// ViewRootImpl.java
final IWindowSession mWindowSession;

public void setView(View view, WindowManager.LayoutParams attrs, View panelParentView) {
    res = mWindowSession.addToDisplay(mWindow, mSeq, mWindowAttributes,
                            getHostVisibility(), mDisplay.getDisplayId(),
                            mAttachInfo.mContentInsets, mAttachInfo.mStableInsets,
                            mAttachInfo.mOutsets, mInputChannel);
}

mWindowSession 顾名思义应是两者之间的会话机制。

代码语言:javascript
复制
public interface IWindowSession extends android.os.IInterface {

   public static abstract class Stub extends android.os.Binder implements android.view.IWindowSession {
        ...
  }
}

而Session是IWindowSession.Stub的实现类,Session中也持有了WindowManagerService的实例。

代码语言:javascript
复制
final class Session extends IWindowSession.Stub
        implements IBinder.DeathRecipient {
    final WindowManagerService mService;

    @Override
    public int addToDisplay(IWindow window, int seq, WindowManager.LayoutParams attrs,
            int viewVisibility, int displayId, Rect outContentInsets, Rect outStableInsets,
            Rect outOutsets, InputChannel outInputChannel) {
        return mService.addWindow(this, window, seq, attrs, viewVisibility, displayId,
                outContentInsets, outStableInsets, outOutsets, outInputChannel);
    }
}

代码又回到 WindowManagerService 中,最后通过 window 的openInputChannel方法打开了与 ViewRootImpl 通信的渠道。最后是通过 InputManagerService 打开 InputChannel ,提供了通讯的环境。

代码语言:javascript
复制
// WindowServiceManagerImpl.java
public int addWindow(Session session, IWindow client, int seq,
            WindowManager.LayoutParams attrs, int viewVisibility, int displayId,
            Rect outContentInsets, Rect outStableInsets, Rect outOutsets,
            InputChannel outInputChannel) {


            WindowState win = new WindowState(this, session, client, token,
                    attachedWindow, appOp[0], seq, attrs, viewVisibility, displayContent);
            ...
            if  (openInputChannels) {
                win.openInputChannel(outInputChannel);
            }
            ...
}
代码语言:javascript
复制
// WindowState

    void openInputChannel(InputChannel outInputChannel) {
        if (mInputChannel != null) {
            throw new IllegalStateException("Window already has an input channel.");
        }
        String name = makeInputChannelName();
        InputChannel[] inputChannels = InputChannel.openInputChannelPair(name);
        mInputChannel = inputChannels[0];
        mClientChannel = inputChannels[1];
        mInputWindowHandle.inputChannel = inputChannels[0];
        if (outInputChannel != null) {
            mClientChannel.transferTo(outInputChannel);
            mClientChannel.dispose();
            mClientChannel = null;
        } else {
            // If the window died visible, we setup a dummy input channel, so that taps
            // can still detected by input monitor channel, and we can relaunch the app.
            // Create dummy event receiver that simply reports all events as handled.
            mDeadWindowEventReceiver = new DeadWindowEventReceiver(mClientChannel);
        }
        mService.mInputManager.registerInputChannel(mInputChannel, mInputWindowHandle);
    }

    void disposeInputChannel() {
        if (mDeadWindowEventReceiver != null) {
            mDeadWindowEventReceiver.dispose();
            mDeadWindowEventReceiver = null;
        }

        // unregister server channel first otherwise it complains about broken channel
        if (mInputChannel != null) {
            mService.mInputManager.unregisterInputChannel(mInputChannel);
            mInputChannel.dispose();
            mInputChannel = null;
        }
        if (mClientChannel != null) {
            mClientChannel.dispose();
            mClientChannel = null;
        }
        mInputWindowHandle.inputChannel = null;
    }

DecorView 的事件派发

代码语言:javascript
复制
    // View.java
    public final boolean dispatchPointerEvent(MotionEvent event) {
        if (event.isTouchEvent()) {
            return dispatchTouchEvent(event);
        } else {
            return dispatchGenericMotionEvent(event);
        }
    }
    // DecorView.java
    @Override
    public boolean dispatchTouchEvent(MotionEvent ev) {
        final Window.Callback cb = mWindow.getCallback();
        return cb != null && !mWindow.isDestroyed() && mFeatureId < 0
                ? cb.dispatchTouchEvent(ev) : super.dispatchTouchEvent(ev);
    }

当有 cb 对象时即可传递给 cb 对象去处理,否则交给 view 去处理。而 Activity 又实现了 cb 对象的接口。

  • 所以首次的dispatchTouchEvent 事件交给 Activity 去处理。
  • 接着在 Activity 处理时会再次将事件抛给 DecorView 的 superDispatchTouchEvent 方法。而 superDispatchTouchEvent 的方法就是 ViewGroup 的 dispatchTouchEvent 方法。
  • 经历了上述两步之后,ViewGroup 的事件分发也就真正意义上的开始了。
代码语言:javascript
复制
// Activity.java
  public boolean dispatchTouchEvent(MotionEvent ev) {
        if (ev.getAction() == MotionEvent.ACTION_DOWN) {
            onUserInteraction();
        }
        if (getWindow().superDispatchTouchEvent(ev)) {
            return true;
        }
        return onTouchEvent(ev);
    }

结束语

到此,事件从触发到分发的第一步已经分析透彻了,下一章将描述具体的分发过程。这也是大多博客反复写,且覆盖率相当高的一篇文章。倒不是执意要去造轮子,只是想通过自己对源码的分析加深对分发过程的理解。


[[Android中的dispatchTouchEvent()、onInterceptTouchEvent()和onTouchEvent()]:http://blog.csdn.net/xyz_lmn/article/details/12517911 [Android中的dispatchTouchEvent()、onInterceptTouchEvent()和onTouchEvent()]:http://blog.csdn.net/xyz_lmn/article/details/12517911

本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2017.03.02 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 大概
  • ViewRootImpl#setView 里的 View 是什么?
  • ViewRootImpl 与 WindowManagerService 通讯分析
  • DecorView 的事件派发
  • 结束语
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档