Window 、Activity、 View 三者关系

Activity activity = null;

java.lang.ClassLoader cl = appContext.getClassLoader();

//在内部是通过反射的方式来创建实例的

activity = mInstrumentation.newActivity(

cl, component.getClassName(), r.intent);

activity.attach(appContext, this, getInstrumentation(), r.token,

r.ident, app, r.intent, r.activityInfo, title, r.parent,

r.embeddedID, r.lastNonConfigurationInstances, config,

r.referrer, r.voiceInteractor, window, r.configCallback,

r.assistToken);

创建好了Activity之后,紧接着就调用了Activity的attach方法,传过去了很多东西进行初始化。

Window的创建

创建好Activity,马上就调用attach方法,Window就是在这个attach方法中被创建的。

final void attach(Context context, ActivityThread aThread,

Instrumentation instr, IBinder token, int ident,

Application application, Intent intent, ActivityInfo info,

CharSequence title, Activity parent, String id,

NonConfigurationInstances lastNonConfigurationInstances,

Configuration config, String referrer, IVoiceInteractor voiceInteractor,

Window window, ActivityConfigCallback activityConfigCallback) {

mWindow = new PhoneWindow(this, window, activityConfigCallback);

mWindow.setWindowControllerCallback(this);

//设置了一个Callback,后面会用到

mWindow.setCallback(this);

mWindow.setOnWindowDismissedCallback(this);

mWindow.getLayoutInflater().setPrivateFactory(this);

if (info.softInputMode != WindowManager.LayoutParams.SOFT_INPUT_STATE_UNSPECIFIED) {

mWindow.setSoftInputMode(info.softInputMode);

}

if (info.uiOptions != 0) {

mWindow.setUiOptions(info.uiOptions);

}

mWindow.setWindowManager(

(WindowManager)context.getSystemService(Context.WINDOW_SERVICE),

mToken, mComponent.flattenToString(),

(info.flags & ActivityInfo.FLAG_HARDWARE_ACCELERATED) != 0);

mWindowManager = mWindow.getWindowManager();

}

可以看到,创建出来的Window其实是PhoneWindow实例,并且创建之后马上设置了一个回调setCallback(this),这个有点用处,后面会讲到。

注意到在最后那里,mWindow.setWindowManager()设置了一个WindowManager。

//Window.java

public void setWindowManager(WindowManager wm, IBinder appToken, String appName,

boolean hardwareAccelerated) {

mAppToken = appToken;

mAppName = appName;

mHardwareAccelerated = hardwareAccelerated;

if (wm == null) {

wm = (WindowManager)mContext.getSystemService(Context.WINDOW_SERVICE);

}

mWindowManager = ((WindowManagerImpl)wm).createLocalWindowManager(this);

}

//WindowManagerImpl.java

public WindowManagerImpl createLocalWindowManager(Window parentWindow) {

return new WindowManagerImpl(mContext, parentWindow);

}

这样一来,Window中就持有了一个WindowManagerImpl的引用。

View的创建

Activity所对应的视图其实是在其对应的PhoneWindow中管理着的,它就是鼎鼎大名的DecorView。它是什么时候创建的呢?平时我们使用Activity时,设置一个布局是通过setContentView来完成的,它内部代码如下:

public void setContentView(@LayoutRes int layoutResID) {

getWindow().setContentView(layoutResID);

initWindowDecorActionBar();

}

public Window getWindow() {

return mWindow;

}

设置进来一个布局的id,然后交给PhoneWindow去处理,Activity自己啥事没干。然后在PhoneWindow的setContentView()中会调用installDecor()方法进行DecorView的初始化

private DecorView mDecor;

private void installDecor() {

if (mDecor == null) {

mDecor = generateDecor(-1);

mDecor.setDescendantFocusability(ViewGroup.FOCUS_AFTER_DESCENDANTS);

mDecor.setIsRootNamespace(true);

}

}

protected DecorView generateDecor(int featureId) {

return new DecorView(context, featureId, this, getAttributes());

}

现在DecorView是创建好了,但是还没有跟Activity建立任何联系,也没有被绘制到界面上进行展示。那到底DecorView是什么时候绘制到屏幕上的呢?

WindowManager的addView

在Activity的生命周期过程中,我们知道onCreate时界面是不可见的,要等到onResume时Activity的内容才可见。究其原因是因为onCreate中仅是创建了DecorView,并没有将其展示出来。而到onResume中,才真正去将PhoneWindow中的DecorView绘制到屏幕上。onResume是在ActivityThread的handleResumeActivity()方法开始执行的。

@Override

public void handleResumeActivity(IBinder token, boolean finalStateRequest, boolean isForward,

String reason) {

//执行Activity的onResume回调

final ActivityClientRecord r = performResumeActivity(token, finalStateRequest, reason);

final Activity a = r.activity;

if (r.window == null && !a.mFinished && willBeVisible) {

r.window = r.activity.getWindow();

//将创建好的DecorView取出来

View decor = r.window.getDecorView();

decor.setVisibility(View.INVISIBLE);

//从Activity中将WindowManager取出来,这个WindowManager是在Activity的attach方法中就初始化好了的,它是WindowManagerImpl

ViewManager wm = a.getWindowManager();

WindowManager.LayoutParams l = r.window.getAttributes();

a.mDecor = decor;

l.type = WindowManager.LayoutParams.TYPE_BASE_APPLICATION;

l.softInputMode |= forwardBit;

if (a.mVisibleFromClient) {

if (!a.mWindowAdded) {

a.mWindowAdded = true;

//将DecorView交给WindowManagerImpl中进行添加View操作

wm.addView(decor, l);

} else {

a.onWindowAttributesChanged(l);

}

}

}

}

在handleResumeActivity最后,将DecorView交给了WindowManager的实现类WindowManagerImpl进行处理。WindowManager的addView结果有两个:

  1. DecorView被渲染绘制到屏幕上显示

  2. DecorView可以接收屏幕触摸事件

//WindowManagerImpl.java

//WindowManagerGlobal是一个单例

private final WindowManagerGlobal mGlobal = WindowManagerGlobal.getInstance();

@Override

public void addView(@NonNull View view, @NonNull ViewGroup.LayoutParams params) {

applyDefaultToken(params);

mGlobal.addView(view, params, mContext.getDisplay(), mParentWindow);

}

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

}

}

WindowManagerImpl自己并没有执行任何操作,转手就把addView的工作交给了单例WindowManagerGlobal进行处理,这是典型的桥接模式。在addView方法中,创建出了一个非常重要的类:ViewRootImpl,它是WindowManager和DecorView之间的桥梁,View的三大流程(测量,布局,绘制)都是通过ViewRootImpl来完成的。

ViewRootImpl的setView

ViewRootImpl的setView方法最终会将View添加到WindowManagerService中,下面我们来看一下具体细节:

/**

  • We have one child

*/

public void setView(View view, WindowManager.LayoutParams attrs, View panelParentView) {

synchronized (this) {

if (mView == null) {

mView = view;

mAdded = true;

int res; /* = WindowManagerImpl.ADD_OKAY; */

// Schedule the first layout -before- adding to the window

// manager, to make sure we do the relayout before receiving

// any other events from the system.

//注释1 开始绘制布局那套流程

requestLayout();

if ((mWindowAttributes.inputFeatures

& WindowManager.LayoutParams.INPUT_FEATURE_NO_INPUT_CHANNEL) == 0) {

//注释2 创建InputChannel

mInputChannel = new InputChannel();

}

try {

//注释3 添加View到WindowManagerService

res = mWindowSession.addToDisplay(mWindow, mSeq, mWindowAttributes,

getHostVisibility(), mDisplay.getDisplayId(), mWinFrame,

mAttachInfo.mContentInsets, mAttachInfo.mStableInsets,

mAttachInfo.mOutsets, mAttachInfo.mDisplayCutout, mInputChannel);

} catch (RemoteException e) {

mAdded = false;

mView = null;

mAttachInfo.mRootView = null;

mInputChannel = null;

mFallbackEventHandler.setView(null);

unscheduleTraversals();

setAccessibilityFocus(null, null);

throw new RuntimeException(“Adding window failed”, e);

} finally {

}

}

}

}

在ViewRootImpl的setView中做了很多事情:

  • 注释1 : 通过requestLayout开始performTraversals那套测量、布局、绘制流程,这会让关联的View也执行了measure、layout、draw流程。

  • 注释2 : 创建InputChannel,在注释3中将InputChannel添加到WindowManagerService中创建socketpair(一对socket)用于发送和接收事件

  • 注释3 : 添加View到WindowManagerService,这里是通过mWindowSession来完成的,它的定义是final IWindowSession mWindowSession;,它其实是WindowManagerGlobal中的单例对象,初始化代码如下:

public static IWindowSession getWindowSession() {

synchronized (WindowManagerGlobal.class) {

if (sWindowSession == null) {

try {

InputMethodManager imm = InputMethodManager.getInstance();

IWindowManager windowManager = getWindowManagerService();

sWindowSession = windowManager.openSession(

new IWindowSessionCallback.Stub() {

@Override

public void onAnimatorScaleChanged(float scale) {

ValueAnimator.setDurationScale(scale);

}

},

imm.getClient(), imm.getInputContext());

} catch (RemoteException e) {

throw e.rethrowFromSystemServer();

}

}

return sWindowSession;

}

}

从这里可以看出,mWindowSession是一个Binder代理对象,它引用了运行在WindowManagerService中的一个类型为Session的Binder本地对象,通过mWindowSession就向WindowManagerService中添加了一个View。mWindowSession的真正实现是在System进程中的Session对象,通过addToDisplay就将View传递给了WindowManagerService。

//Session.java

final WindowManagerService mService;

@Override

public int addToDisplay(IWindow window, int seq, WindowManager.LayoutParams attrs,

int viewVisibility, int displayId, Rect outFrame, Rect outContentInsets,

Rect outStableInsets,

DisplayCutout.ParcelableWrapper outDisplayCutout, InputChannel outInputChannel,

InsetsState outInsetsState, InsetsSourceControl[] outActiveControls) {

return mService.addWindow(this, window, seq, attrs, viewVisibility, displayId, outFrame,

outContentInsets, outStableInsets, outDisplayCutout, outInputChannel,

outInsetsState, outActiveControls, UserHandle.getUserId(mUid));

}

在System进程中,Session调用了WindowManagerService的addWindow,window被传递给了WindowManagerService,剩下的工作就全交给WindowManagerService来完成了。

触摸事件的接收

当触摸事件发生后,Touch事件首先是被传入到Activity,然后被下发到布局中的ViewGroup或View。Touch事件是如何传递到Activity上的?

在ViewRootImpl中的setView方法的最后,设置了一系列输入管道。一个触摸事件的发生是由屏幕发起,然后经过驱动层一系列的优化计算通过Socket跨进程通知Android Framework层(实际是WMS),最终屏幕的触摸事件会被发送到下面的输入管道中。

public void setView(View view, WindowManager.LayoutParams attrs, View panelParentView) {

// Set up the input pipeline.

//注释4 输入管道

CharSequence counterSuffix = attrs.getTitle();

总结

最后小编想说:不论以后选择什么方向发展,目前重要的是把Android方面的技术学好,毕竟其实对于程序员来说,要学习的知识内容、技术有太多太多,要想不被环境淘汰就只有不断提升自己,从来都是我们去适应环境,而不是环境来适应我们!

这里附上我整理的几十套腾讯、字节跳动,京东,小米,头条、阿里、美团等公司19年的Android面试题。把技术点整理成了视频和PDF(实际上比预期多花了不少精力),包含知识脉络 + 诸多细节。

由于篇幅有限,这里以图片的形式给大家展示一小部分。

网上学习 Android的资料一大堆,但如果学到的知识不成体系,遇到问题时只是浅尝辄止,不再深入研究,那么很难做到真正的技术提升。希望这份系统化的技术体系对大家有一个方向参考。

技术进阶之路很漫长,一起共勉吧~
《Android学习笔记总结+移动架构视频+大厂面试真题+项目实战源码》点击传送门,即可获取!
{

// Set up the input pipeline.

//注释4 输入管道

CharSequence counterSuffix = attrs.getTitle();

总结

最后小编想说:不论以后选择什么方向发展,目前重要的是把Android方面的技术学好,毕竟其实对于程序员来说,要学习的知识内容、技术有太多太多,要想不被环境淘汰就只有不断提升自己,从来都是我们去适应环境,而不是环境来适应我们!

这里附上我整理的几十套腾讯、字节跳动,京东,小米,头条、阿里、美团等公司19年的Android面试题。把技术点整理成了视频和PDF(实际上比预期多花了不少精力),包含知识脉络 + 诸多细节。

由于篇幅有限,这里以图片的形式给大家展示一小部分。

[外链图片转存中…(img-7uxTP2j7-1715756682051)]

网上学习 Android的资料一大堆,但如果学到的知识不成体系,遇到问题时只是浅尝辄止,不再深入研究,那么很难做到真正的技术提升。希望这份系统化的技术体系对大家有一个方向参考。

技术进阶之路很漫长,一起共勉吧~
《Android学习笔记总结+移动架构视频+大厂面试真题+项目实战源码》点击传送门,即可获取!

  • 5
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值