延续上一篇文章(View·InputEvent事件投递源码分析(一))得出的结论,本文接着对 View、ViewGroup 的事件派发、拦截进行源码分析。
上一篇文章得到 View 的屏幕触摸事件的处理由 ViewPostImeInputStage 类进行处理。
// 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 的身份已经呼之欲出了。
但是在没有足够的证据(代码)说明之前,我们对结果仍保持怀疑。
// 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 提供与系统窗口管理器的低级别通信,用于与任何特定上下文无关的操作。
// 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。
WindowManagerImpl 作为 WindowManagerGlobal的代理持有了WindowManagerGlobal对象。
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 中。
// 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中的代码片段。
// 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 顾名思义应是两者之间的会话机制。
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的实例。
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 ,提供了通讯的环境。
// 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);
}
...
}
// 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;
}
// 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 对象的接口。
// 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