Android源码解析系列1——Activity启动和界面加载(1)

// 省略部分代码
} catch (Exception e) { /* 省略部分代码 */ }

try {
Application app = r.packageInfo.makeApplication(false, mInstrumentation);
// 省略部分代码

if (activity != null) {
// 省略部分代码

Window window = null;
if (r.mPendingRemoveWindow != null && r.mPreserveWindow) {
window = r.mPendingRemoveWindow;
r.mPendingRemoveWindow = null;
r.mPendingRemoveWindowManager = null;
}
appContext.setOuterContext(activity);
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);
// 省略部分代码

if (r.isPersistable()) {
mInstrumentation.callActivityOnCreate(activity, r.state, r.persistentState);
} else {
mInstrumentation.callActivityOnCreate(activity, r.state);
}
// 省略部分代码

if (!r.activity.mFinished) {
activity.performStart();
r.stopped = false;
}
if (!r.activity.mFinished) {
activity.mCalled = false;
if (r.isPersistable()) {
mInstrumentation.callActivityOnPostCreate(activity, r.state,
r.persistentState);
} else {
mInstrumentation.callActivityOnPostCreate(activity, r.state);
}
// 省略部分代码
}
}
r.paused = true;

// 保存ActivityClientRecord
mActivities.put(r.token, r);

} catch { /* 省略catch相关代码 */ }

return activity;
}

上述代码主要执行了以下操作:

  1. 创建Activity对象

调用InstrumentationnewActivity方法,通过反射创建Activity对象。

  1. 初始化Activity

调用Activity对象的attach方法,用于初始化Activity的一些数据,同时会为Activity设置Window对象。 注意:Activity的Window对象,与传入的Window对象不是同一个对象。这也意味着:每个Activity都有各自的Window对象

public class Activity extends … {
// 省略部分代码
private Window mWindow;
private WindowManager mWindowManager;

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) {
attachBaseContext(context);

mFragments.attachHost(null /parent/);

mWindow = new PhoneWindow(this, window, activityConfigCallback);
// 省略部分代码

mWindow.setWindowManager(
(WindowManager)context.getSystemService(Context.WINDOW_SERVICE),
mToken, mComponent.flattenToString(),
(info.flags & ActivityInfo.FLAG_HARDWARE_ACCELERATED) != 0);
// 省略部分代码

mWindowManager = mWindow.getWindowManager();
// 省略部分代码
}
// 省略部分代码
}

  1. 调用3个生命周期方法

1、Instrumentation.callActivityOnCreate方法,该方法中会调用activity.performCreate()方法。
2、activity.performStart()方法。
3、Instrumentation.callActivityOnPostCreate方法,该方法中会调用activity.onPostCreate()方法。

查看里面的源码,确实依次调用了onCreateonStartonPostCreate方法,验证了我们之前对performLaunchActivity的猜想。

总结一下

handleLaunchActivity方法里,会回调以下生命周期:

onCreate() -> onStart() -> onPostCreate() -> onResume()

注意:如果ActivityClientRecord.startsNotResumed = true时,生命周期流程将会变为:

onCreate() -> onStart() -> onPostCreate() -> onResume() -> onPause()


二、界面加载

通过上节内容的介绍,我们知道在handleLaunchActivity方法里,会回调Activity的onCreate()生命周期方法。

而一般我们在创建Activity时,会在onCreate()中调用setContentView来设置布局文件。

下面,我们开始分析,我们自定义的布局文件是如何被加载出来的。

2.1、设置布局

首先分析Activity中的setContentView方法的源码。

public class Activity extends … {
// 省略部分代码

public void setContentView(@LayoutRes int layoutResID) {
getWindow().setContentView(layoutResID);
initWindowDecorActionBar();
}
// 省略部分代码
}

根据前面的分析可知,这里的getWindow()方法返回的是该Activity所特有的Window对象,它在attach方法中被赋值。

而Window是一个抽象类,通过查看类上的注解可知,它只有一个名为PhoneWindow的子类,所以我们直接看PhoneWindow的setContentView方法。

public class PhoneWindow extends Window implements MenuBuilder.Callback {
// 省略部分代码
ViewGroup mContentParent;

@Override
public void setContentView(int layoutResID) {
// Note: FEATURE_CONTENT_TRANSITIONS may be set in the process of installing the window
// decor, when theme attributes and the like are crystalized. Do not check the feature
// before this happens.
if (mContentParent == null) {
installDecor();
} else if (!hasFeature(FEATURE_CONTENT_TRANSITIONS)) {
mContentParent.removeAllViews();
}

if (hasFeature(FEATURE_CONTENT_TRANSITIONS)) {
final Scene newScene = Scene.getSceneForLayout(mContentParent, layoutResID,
getContext());
transitionTo(newScene);
} else {
mLayoutInflater.inflate(layoutResID, mContentParent);
}
mContentParent.requestApplyInsets();
final Callback cb = getCallback();
if (cb != null && !isDestroyed()) {
cb.onContentChanged();
}
mContentParentExplicitlySet = true;
}
// 省略部分代码
}

代码还是比较清楚的,如果mContentParent == null,调用installDecor()方法,后续将传入的布局资源,加载到mContentParent中。

所以这里可以肯定:installDecor()方法,主要作用就是为了创建mContentParent对象。

public class PhoneWindow extends Window implements MenuBuilder.Callback {
// 省略部分代码
private DecorView mDecor;
ViewGroup mContentParent;

private void installDecor() {
mForceDecorInstall = false;
if (mDecor == null) {
mDecor = generateDecor(-1);
// 省略部分代码
} else {
mDecor.setWindow(this);
}
if (mContentParent == null) {
mContentParent = generateLayout(mDecor);
// 省略后续设置icon、title等代码
}
}
}

嗯,这里确实通过generateLayout方法创建了mContentParent对象,但在创建之前,先创建了一个DecorView对象,并将其作为参数传入generateLayout方法里。

DecorView,我们只需要知道它继承至FrameLayout即可,因为此时分析它的细节,对于我们并没太大帮助。

那我们分析generateLayout做了什么:

public class PhoneWindow extends Window implements MenuBuilder.Callback {
// 省略部分代码
public static final int ID_ANDROID_CONTENT = com.android.internal.R.id.content;

protected ViewGroup generateLayout(DecorView decor) {
// Apply data from current theme.

// 省略部分代码:从主题文件中读取内容,并设置对应的Flag

// Inflate the window decor.

int layoutResource;
int features = getLocalFeatures();
//省略部分代码:通过features,为layoutResource设置不同布局资源id

mDecor.startChanging();
mDecor.onResourcesLoaded(mLayoutInflater, layoutResource);

ViewGroup contentParent = (ViewGroup)findViewById(ID_ANDROID_CONTENT);
//省略部分代码:为mDecor设置background、elevation、title、titleColor等数据

mDecor.finishChanging();

return contentParent;
}
}

主要做了以下内容:

  1. 从主题中获取数据,并应用到当前Window中。
  2. 根据features,让mDecor加载不同的布局文件。
  3. 获得mContentParent对象(id为com.android.internal.R.id.content)。

这里我们可以得出以下信息:

  1. 不同的主题会让Window加载不同的布局到DecorView中。
  2. setContentView方法,实际是将自定义的布局文件,加载到mContentParent中。

至此,我们可以简单总结一下setContentView的流程:

1、首先,Activity中的Window对象会创建一个DecorView
2、然后根据不同的主题,让DecorView加载不同的布局资源。
3、获取这些布局资源中的mContentParent,它的id为com.android.internal.R.id.content
4、最后将自定义的布局加载到mContentParent中。

2.2、渲染布局

在上述setContentView的流程中,所有的布局资源都已加载完毕,而布局的加载又会涉及到addView方法。

一般来说,调用addView方法,都会间接调用到requestLayout()invalidate(true)方法,造成界面重新布局和刷新。

而我们也知道:

Activity在onCreate时,界面并不会被加载出来。

这里仿佛出现了矛盾,那我们再分析分析,看看为什么调用了addView方法后,界面却没有被加载出来。

public abstract class ViewGroup extends View implements ViewParent, ViewManager {
// 省略部分代码

public void addView(View child, int index, LayoutParams params) {
// 省略部分代码
requestLayout();
invalidate(true);
addViewInner(child, index, params, false);
}
// 省略部分代码
}

public class View implements … {
// 省略部分代码

public void requestLayout() {
// 省略部分代码
if (mParent != null && !mParent.isLayoutRequested()) {
mParent.requestLayout();
}
// 省略部分代码
}

public void invalidate(boolean invalidateCache) {
invalidateInternal(0, 0, mRight - mLeft, mBottom - mTop, invalidateCache, true);
}

void invalidateInternal(int l, int t, int r, int b, boolean invalidateCache,
boolean fullInvalidate) {
// 省略部分代码
if (skipInvalidate()) {
return;
}
// 省略后续代码
}

private boolean skipInvalidate() {
return (mViewFlags & VISIBILITY_MASK) != VISIBLE && mCurrentAnimation == null &&
(!(mParent instanceof ViewGroup) ||
!((ViewGroup) mParent).isViewTransitioning(this));
}
// 省略部分代码
}

哦,原来此时DecorView没有父容器,导致这里只会执行添加操作,而不会去重新布局和刷新。


那什么时候,界面才会被加载出来呢?

只要学过Android生命周期的人,都知道:

当Activity处于onCreate时,是不可见的。
当Activity处于onStart时,可见,但不可交互。
当Activity处于onResume时,才是可见可交互的。

那我们看看ActivityperformStart方法实现:

public class Activity extends … {
// 省略部分代码

final void performStart() {
mActivityTransitionState.setEnterActivityOptions(this, getActivityOptions());
mFragments.noteStateNotSaved();
mCalled = false;
mFragments.execPendingActions();
mInstrumentation.callActivityOnStart(this);
if (!mCalled) {
throw new SuperNotCalledException(
“Activity " + mComponent.toShortString() +
" did not call through to super.onStart()”);
}
mFragments.dispatchStart();
mFragments.reportLoaderStart();

// 省略部分代码

mActivityTransitionState.enterReady(this);
}

这里只要调用了InstrumentationcallActivityOnStart方法,而callActivityOnStart方法内部的实现,只是简单调用了传入的Activity对象的onStart()方法。

emmmmm…好像有点不对啊,performStart方法里好像也没做什么操作啊,难不成界面渲染是在onResume()里?

带着疑惑,我们一起来看看handleResumeActivity方法:

public final class ActivityThread {
// 省略部分代码

final void handleResumeActivity(IBinder token,
boolean clearHide, boolean isForward, boolean reallyResume, int seq, String reason) {
ActivityClientRecord r = mActivities.get(token);
// 省略部分代码

// TODO Push resumeArgs into the activity for consideration
r = performResumeActivity(token, clearHide, reason);

if (r != null) {
final Activity a = r.activity;
// 省略部分代码

if (r.window == null && !a.mFinished && willBeVisible) {
r.window = r.activity.getWindow();
View decor = r.window.getDecorView();
decor.setVisibility(View.INVISIBLE);
ViewManager wm = a.getWindowManager();
WindowManager.LayoutParams l = r.window.getAttributes();
a.mDecor = decor;
// 省略部分代码

if (a.mVisibleFromClient) {
if (!a.mWindowAdded) {
a.mWindowAdded = true;
wm.addView(decor, l);
} else {
// The activity will get a callback for this {@link LayoutParams} change
// earlier. However, at that time the decor will not be set (this is set
// in this method), so no action will be taken. This call ensures the
// callback occurs with the decor set.
a.onWindowAttributesChanged(l);
}
}
// 省略后续代码
}
}
}
}

其中performResumeActivity也没做过多操作,只是调用了Activity的performResume()方法,间接调用到onResume,我们就不过多分析了。

这里比较核心的是,将DecorView添加到ViewManager中,这里间接调用到WindowManagerGlobaladdView方法,它是一个单例对象,注意这里的判定条件,可以看出,一个ActivityClientRecord对象,之后执行一次。

public final class WindowManagerGlobal {
// 省略部分代码
private final ArrayList mViews = new ArrayList();
private final ArrayList mRoots = new ArrayList();
private final ArrayList<WindowManager.LayoutParams> mParams = new ArrayList<WindowManager.LayoutParams>();

public void addView(View view, ViewGroup.LayoutParams params,
Display display, Window parentWindow) {
// 省略部分代码

final WindowManager.LayoutParams wparams = (WindowManager.LayoutParams) params;

ViewRootImpl root;
View panelParentView = null;

synchronized (mLock) {
// 省略部分代码

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) {
// BadTokenException or InvalidDisplayException, clean up.
if (index >= 0) {
removeViewLocked(index, true);
}
throw e;
}
}
}
// 省略部分代码
}

最后

感觉现在好多人都在说什么安卓快凉了,工作越来越难找了。又是说什么程序员中年危机啥的,为啥我这年近30的老农根本没有这种感觉,反倒觉得那些贩卖焦虑的都是瞎j8扯谈。当然,职业危机意识确实是要有的,但根本没到那种草木皆兵的地步好吗?

Android凉了都是弱者的借口和说辞。虽然 Android 没有前几年火热了,已经过去了会四大组件就能找到高薪职位的时代了。这只能说明 Android 中级以下的岗位饱和了,现在高级工程师还是比较缺少的,很多高级职位给的薪资真的特别高(钱多也不一定能找到合适的),所以努力让自己成为高级工程师才是最重要的。

所以,最后这里放上我耗时两个月,将自己8年Android开发的知识笔记整理成的Android开发者必知必会系统学习资料笔记,上述知识点在笔记中都有详细的解读,里面还包含了腾讯、字节跳动、阿里、百度2019-2021面试真题解析,并且把每个技术点整理成了视频和PDF(知识脉络 + 诸多细节)。

以上全套学习笔记面试宝典,吃透一半保你可以吊打面试官,只有自己真正强大了,有核心竞争力,你才有拒绝offer的权力,所以,奋斗吧!骚年们!千里之行,始于足下。种下一颗树最好的时间是十年前,其次,就是现在。

最后,赠与大家一句诗,共勉!

不驰于空想,不骛于虚声。不忘初心,方得始终。
《Android学习笔记总结+移动架构视频+大厂面试真题+项目实战源码》点击传送门,即可获取!
找到合适的),所以努力让自己成为高级工程师才是最重要的。

所以,最后这里放上我耗时两个月,将自己8年Android开发的知识笔记整理成的Android开发者必知必会系统学习资料笔记,上述知识点在笔记中都有详细的解读,里面还包含了腾讯、字节跳动、阿里、百度2019-2021面试真题解析,并且把每个技术点整理成了视频和PDF(知识脉络 + 诸多细节)。

[外链图片转存中…(img-IPBb6MvL-1714555909701)]

以上全套学习笔记面试宝典,吃透一半保你可以吊打面试官,只有自己真正强大了,有核心竞争力,你才有拒绝offer的权力,所以,奋斗吧!骚年们!千里之行,始于足下。种下一颗树最好的时间是十年前,其次,就是现在。

最后,赠与大家一句诗,共勉!

不驰于空想,不骛于虚声。不忘初心,方得始终。
《Android学习笔记总结+移动架构视频+大厂面试真题+项目实战源码》点击传送门,即可获取!

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值