0. 前言
Activity 组件的启动流程在 Android 8.0 版本以后得到了很大程度上的变更,很多类或方法已经废弃不用,本人参考最新源代码与指导书籍重新分析 Activity 启动流程,其中大都是自己的观点,如有错误,烦请不吝赐教。
1. 启动调用
作为android四大组件之一,同时也是唯一可被用户感知的部分, Activity 的作用和地位毋庸置疑,而实际开发中,我们要启动一个新的Activity的过程却不是很复杂。
由于android系统的良好封装,通过显式intent的方式,我们可以很方便地启动一个 Activity :
Intent intent = new Intent(this, TestActivity.class);
startActivity(iintent);
但我们不仅会想:
Activity 的 onCreate 方法是何时被回调的呢?新 Activity 对象是何时创建的呢?
很简单,我们需要分析源码,从源码中寻找答案。
2. 源码分析
2.1 分析环境
这里,我们通过 Chrome 浏览器 结合 Android 官方参考网站 ,
使用 Chrome 插件 Android SDK Search ,结合相关源码深入分析,
具体使用方法在这里不再赘述。
2.2 从 startActivityForResult 开始
参阅 Activity 源代码
startActivity有很多种重载方式,但最终它们都会调用startActivityForResult 方法:
public void startActivityForResult(@RequiresPermission Intent intent, int requestCode,
@Nullable Bundle options) {
if (mParent == null) {
options = transferSpringboardActivityOptions(options);
Instrumentation.ActivityResult ar =
mInstrumentation.execStartActivity(
this, mMainThread.getApplicationThread(), mToken, this,
intent, requestCode, options);
if (ar != null) {
mMainThread.sendActivityResult(
mToken, mEmbeddedID, requestCode, ar.getResultCode(),
ar.getResultData());
}
if (requestCode >= 0) {
// If this start is requesting a result, we can avoid making
// the activity visible until the result is received. Setting
// this code during onCreate(Bundle savedInstanceState) or onResume() will keep the
// activity hidden during this time, to avoid flickering.
// This can only be done when a result is requested because
// that guarantees we will get information back when the
// activity is finished, no matter what happens to it.
mStartedActivity = true;
}
cancelInputsAndStartExitTransition(options);
// TODO Consider clearing/flushing other event sources and events for child windows.
} else {
if (options != null) {
mParent.startActivityFromChild(this, intent, requestCode, options);
} else {
// Note we want to go through this method for compatibility with
// existing applications that may have overridden it.
mParent.startActivityFromChild(this, intent, requestCode);
}
}
}
这里只需要关注 mPa