开篇
本篇以android-11.0.0_r25作为基础解析
上一篇文章 Android源码剖析 – Activity发动流程(中) 中,咱们剖析了App
进程的发动进程,包括Application
是怎样创立并履行onCreate
办法的,本篇文章咱们将会持续剖析App
进程发动、Application
创立完成后,Activity
是怎样发动的
两种途径发动Activity
咱们在 Android源码剖析 – Activity发动流程(上) 的结束剖析过,Activity
的发动存在两条途径
发动进程,然后发动Activity
这条途径便是咱们在上一篇文章 Android源码剖析 – Activity发动流程(中) 中剖析了前半部分:发动进程
当进程发动后,会履行到AMS.attachApplicationLocked
办法,在这个办法的最终,会有一段代码查看是否有Activity
等候发动
private boolean attachApplicationLocked(@NonNull IApplicationThread thread,
int pid, int callingUid, long startSeq) {
...
// See if the top visible activity is waiting to run in this process...
//查看是否有Activity等候发动
if (normalMode) {
try {
didSomething = mAtmInternal.attachApplication(app.getWindowProcessController());
} catch (Exception e) {
badApp = true;
}
}
...
return true;
}
然后调用ActivityTaskManagerInternal.attachApplication
,ActivityTaskManagerInternal
是一个抽象类,被ATMS
的内部类LocalService
完成
public boolean attachApplication(WindowProcessController wpc) throws RemoteException {
synchronized (mGlobalLockWithoutBoost) {
try {
return mRootWindowContainer.attachApplication(wpc);
} finally {
...
}
}
}
接着调用RootWindowContainer.attachApplication
boolean attachApplication(WindowProcessController app) throws RemoteException {
boolean didSomething = false;
for (int displayNdx = getChildCount() - 1; displayNdx >= 0; --displayNdx) {
mTmpRemoteException = null;
mTmpBoolean = false; // Set to true if an activity was started.
final DisplayContent display = getChildAt(displayNdx);
for (int areaNdx = display.getTaskDisplayAreaCount() - 1; areaNdx >= 0; --areaNdx) {
final TaskDisplayArea taskDisplayArea = display.getTaskDisplayAreaAt(areaNdx);
for (int taskNdx = taskDisplayArea.getStackCount() - 1; taskNdx >= 0; --taskNdx) {
final ActivityStack rootTask = taskDisplayArea.getStackAt(taskNdx);
if (rootTask.getVisibility(null /*starting*/) == STACK_VISIBILITY_INVISIBLE) {
break;
}
//遍历ActivityStack下的一切ActivityRecord,
//以其为参数调用startActivityForAttachedApplicationIfNeeded办法
final PooledFunction c = PooledLambda.obtainFunction(
RootWindowContainer::startActivityForAttachedApplicationIfNeeded, this,
PooledLambda.__(ActivityRecord.class), app,
rootTask.topRunningActivity());
rootTask.forAllActivities(c);
c.recycle();
if (mTmpRemoteException != null) {
throw mTmpRemoteException;
}
}
}
didSomething |= mTmpBoolean;
}
if (!didSomething) {
ensureActivitiesVisible(null, 0, false /* preserve_windows */);
}
return didSomething;
}
这儿有两层for
循环,能够看出来,这个办法遍历了一切可见的ActivityStack
,然后再对每个可见的ActivityStack
进行操作
其中,PooledLambda
这个类采用了池化技能,用于结构可收回复用的匿名函数,这儿PooledLambda.obtainFunction
办法得到的结果是一个Function<ActivityRecord, Boolean>
,forAllActivities
办法被界说在父类WindowContainer
中,便是遍历履行一切child
的forAllActivities
办法,而ActivityRecord
中重写了这个办法,直接用自身履行这个Function
简单来说,能够将这部分代码看作以下伪代码:
rootTask.forEachAllActivityRecord((activityRecord) -> {
startActivityForAttachedApplicationIfNeeded(activityRecord, app, rootTask.topRunningActivity())
})
接着咱们来调查startActivityForAttachedApplicationIfNeeded
办法
private boolean startActivityForAttachedApplicationIfNeeded(ActivityRecord r,
WindowProcessController app, ActivityRecord top) {
//Activity是否正在finish,是否应为当时用户显现Activity,忽略锁屏状况,此Activity是否可见
//比照Activity与建议进程的uid和进程名
if (r.finishing || !r.okToShowLocked() || !r.visibleIgnoringKeyguard || r.app != null
|| app.mUid != r.info.applicationInfo.uid || !app.mName.equals(r.processName)) {
return false;
}
try {
//发动Activity
if (mStackSupervisor.realStartActivityLocked(r, app,
top == r && r.isFocusable() /*andResume*/, true /*checkConfig*/)) {
mTmpBoolean = true;
}
} catch (RemoteException e) {
...
return true;
}
return false;
}
上面一系列的判别查看传入的ActivityRecord
所对应的Activity
是否需求发动,然后调用ActivityStackSupervisor.realStartActivityLocked
办法发动Activity
已有进程,直接发动Activity
这条途径我在 Android源码剖析 – Activity发动流程(上) 中的结束也剖析过,假如App
进程现已发动,则会调用ActivityStackSupervisor.startSpecificActivity
办法
void startSpecificActivity(ActivityRecord r, boolean andResume, boolean checkConfig) {
// Is this activity's application already running?
final WindowProcessController wpc =
mService.getProcessController(r.processName, r.info.applicationInfo.uid);
boolean knownToBeDead = false;
if (wpc != null && wpc.hasThread()) {
try {
//发动Activity
realStartActivityLocked(r, wpc, andResume, checkConfig);
return;
} catch (RemoteException e) {
Slog.w(TAG, "Exception when starting activity "
+ r.intent.getComponent().flattenToShortString(), e);
}
// If a dead object exception was thrown -- fall through to
// restart the application.
knownToBeDead = true;
}
//锁屏状况下发动Activity防闪耀机制
r.notifyUnknownVisibilityLaunchedForKeyguardTransition();
//呈现异常,重启进程
final boolean isTop = andResume && r.isTopRunningActivity();
mService.startProcessAsync(r, knownToBeDead, isTop, isTop ? "top-activity" : "activity");
}
能够看到,这儿也调用了ActivityStackSupervisor.realStartActivityLocked
办法发动Activity
realStartActivityLocked
终究两条途径都走到了ActivityStackSupervisor.realStartActivityLocked
办法中,那咱们就来看看这个办法做了什么
boolean realStartActivityLocked(ActivityRecord r, WindowProcessController proc,
boolean andResume, boolean checkConfig) throws RemoteException {
//保证一切Activity都已暂停
if (!mRootWindowContainer.allPausedActivitiesComplete()) {
// While there are activities pausing we skipping starting any new activities until
// pauses are complete. NOTE: that we also do this for activities that are starting in
// the paused state because they will first be resumed then paused on the client side.
return false;
}
final Task task = r.getTask();
final ActivityStack stack = task.getStack();
//推迟resume以避免重复resume
//经过设置符号位mDeferResumeCount,只要当其为0时才干履行resume
beginDeferResume();
try {
//冻住屏幕(不接纳输入、不履行动画,截取屏幕进行显现)
r.startFreezingScreenLocked(proc, 0);
// schedule launch ticks to collect information about slow apps.
//收集发动缓慢信息
r.startLaunchTickingLocked();
r.setProcess(proc);
// Ensure activity is allowed to be resumed after process has set.
//保证Activity允许被resume
if (andResume && !r.canResumeByCompat()) {
andResume = false;
}
//锁屏状况下发动Activity防闪耀机制
r.notifyUnknownVisibilityLaunchedForKeyguardTransition();
// Have the window manager re-evaluate the orientation of the screen based on the new
// activity order. Note that as a result of this, it can call back into the activity
// manager with a new orientation. We don't care about that, because the activity is
// not currently running so we are just restarting it anyway.
if (checkConfig) {
// Deferring resume here because we're going to launch new activity shortly.
// We don't want to perform a redundant launch of the same record while ensuring
// configurations and trying to resume top activity of focused stack.
//保证一切Activity的可见性、更新屏幕方向和装备
mRootWindowContainer.ensureVisibilityAndConfig(r, r.getDisplayId(),
false /* markFrozenIfConfigChanged */, true /* deferResume */);
}
//查看Activity是否在后台锁屏状况下发动
if (r.getRootTask().checkKeyguardVisibility(r, true /* shouldBeVisible */,
true /* isTop */) && r.allowMoveToFront()) {
// We only set the visibility to true if the activity is not being launched in
// background, and is allowed to be visible based on keyguard state. This avoids
// setting this into motion in window manager that is later cancelled due to later
// calls to ensure visible activities that set visibility back to false.
//只要Activity不是在后台发动,才将其可见性设置为true
r.setVisibility(true);
}
... //异常状况查看
r.launchCount++;
r.lastLaunchTime = SystemClock.uptimeMillis();
proc.setLastActivityLaunchTime(r.lastLaunchTime);
//屏幕固定功用
final LockTaskController lockTaskController = mService.getLockTaskController();
if (task.mLockTaskAuth == LOCK_TASK_AUTH_LAUNCHABLE
|| task.mLockTaskAuth == LOCK_TASK_AUTH_LAUNCHABLE_PRIV
|| (task.mLockTaskAuth == LOCK_TASK_AUTH_WHITELISTED
&& lockTaskController.getLockTaskModeState()
== LOCK_TASK_MODE_LOCKED)) {
lockTaskController.startLockTaskMode(task, false, 0 /* blank UID */);
}
try {
if (!proc.hasThread()) {
throw new RemoteException();
}
List<ResultInfo> results = null;
List<ReferrerIntent> newIntents = null;
if (andResume) {
// We don't need to deliver new intents and/or set results if activity is going
// to pause immediately after launch.
results = r.results;
newIntents = r.newIntents;
}
//假如是ACTIVITY_TYPE_HOME类型的应用(Launcher)
if (r.isActivityTypeHome()) {
// Home process is the root process of the task.
updateHomeProcess(task.getBottomMostActivity().app);
}
//信息记录
mService.getPackageManagerInternalLocked().notifyPackageUse(
r.intent.getComponent().getPackageName(), NOTIFY_PACKAGE_USE_ACTIVITY);
r.setSleeping(false);
r.forceNewConfig = false;
//假如有必要的话,显现一些App正告弹窗(不支持的CompileSdk、不支持的TargetSdk、不支持的显现巨细)
mService.getAppWarningsLocked().onStartActivity(r);
//兼容性信息
r.compat = mService.compatibilityInfoForPackageLocked(r.info.applicationInfo);
// Because we could be starting an Activity in the system process this may not go
// across a Binder interface which would create a new Configuration. Consequently
// we have to always create a new Configuration here.
final MergedConfiguration mergedConfiguration = new MergedConfiguration(
proc.getConfiguration(), r.getMergedOverrideConfiguration());
r.setLastReportedConfiguration(mergedConfiguration);
// Create activity launch transaction.
//创立或获取一个client业务
final ClientTransaction clientTransaction = ClientTransaction.obtain(
proc.getThread(), r.appToken);
final DisplayContent dc = r.getDisplay().mDisplayContent;
//增加一条Activity发动音讯
clientTransaction.addCallback(LaunchActivityItem.obtain(new Intent(r.intent),
System.identityHashCode(r), r.info,
// TODO: Have this take the merged configuration instead of separate global
// and override configs.
mergedConfiguration.getGlobalConfiguration(),
mergedConfiguration.getOverrideConfiguration(), r.compat,
r.launchedFromPackage, task.voiceInteractor, proc.getReportedProcState(),
r.getSavedState(), r.getPersistentSavedState(), results, newIntents,
dc.isNextTransitionForward(), proc.createProfilerInfoIfNeeded(),
r.assistToken, r.createFixedRotationAdjustmentsIfNeeded()));
// Set desired final state.
final ActivityLifecycleItem lifecycleItem;
if (andResume) {
lifecycleItem = ResumeActivityItem.obtain(dc.isNextTransitionForward());
} else {
lifecycleItem = PauseActivityItem.obtain();
}
//设置client履行业务后应处于的生命周期状况
clientTransaction.setLifecycleStateRequest(lifecycleItem);
// Schedule transaction.
//调度履行此业务,发动Activity
mService.getLifecycleManager().scheduleTransaction(clientTransaction);
//处理重量级进程
if ((proc.mInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_CANT_SAVE_STATE) != 0
&& mService.mHasHeavyWeightFeature) {
// This may be a heavy-weight process! Note that the package manager will ensure
// that only activity can run in the main process of the .apk, which is the only
// thing that will be considered heavy-weight.
if (proc.mName.equals(proc.mInfo.packageName)) {
if (mService.mHeavyWeightProcess != null
&& mService.mHeavyWeightProcess != proc) {
Slog.w(TAG, "Starting new heavy weight process " + proc
+ " when already running "
+ mService.mHeavyWeightProcess);
}
mService.setHeavyWeightProcess(r);
}
}
} catch (RemoteException e) {
if (r.launchFailed) {
// This is the second time we failed -- finish activity and give up.
//第二次发动失败,finish掉Activity并抛弃重试,直接回来false
Slog.e(TAG, "Second failure launching "
+ r.intent.getComponent().flattenToShortString() + ", giving up", e);
proc.appDied("2nd-crash");
r.finishIfPossible("2nd-crash", false /* oomAdj */);
return false;
}
// This is the first time we failed -- restart process and
// retry.
//第一次发动失败,测验重启进程并重试发动Activity
r.launchFailed = true;
proc.removeActivity(r);
throw e;
}
} finally {
endDeferResume();
}
r.launchFailed = false;
// TODO(lifecycler): Resume or pause requests are done as part of launch transaction,
// so updating the state should be done accordingly.
//更新生命周期状况
if (andResume && readyToResume()) {
// As part of the process of launching, ActivityThread also performs
// a resume.
stack.minimalResumeActivityLocked(r);
} else {
// This activity is not starting in the resumed state... which should look like we asked
// it to pause+stop (but remain visible), and it has done so and reported back the
// current icicle and other state.
r.setState(PAUSED, "realStartActivityLocked");
mRootWindowContainer.executeAppTransitionForAllDisplay();
}
// Perform OOM scoring after the activity state is set, so the process can be updated with
// the latest state.
//更新进程oom adj,更新进程状况
proc.onStartActivity(mService.mTopProcessState, r.info);
// Launch the new version setup screen if needed. We do this -after-
// launching the initial activity (that is, home), so that it can have
// a chance to initialize itself while in the background, making the
// switch back to it faster and look better.
if (mRootWindowContainer.isTopDisplayFocusedStack(stack)) {
mService.getActivityStartController().startSetupActivity();
}
// Update any services we are bound to that might care about whether
// their client may have activities.
//更新进程绑定的一切服务
if (r.app != null) {
r.app.updateServiceConnectionActivities();
}
return true;
}
这个办法中最关键的部分在于创立了ClientTransaction
业务,并向里增加了一条发动Activity
的音讯,然后调用ATMS.getLifecycleManager.scheduleTransaction
调度履行这个业务,发动Activity
ClientTransaction
咱们先来看看ClientTransaction
这个目标是怎样创立获取的,咱们首要调用了ClientTransaction.obtain
办法,并传入了一个ActivityThread
内部类ApplicationThread
的Binder
目标IApplicationThread
和一个ActivityRecord.Token
目标
public static ClientTransaction obtain(IApplicationThread client, IBinder activityToken) {
ClientTransaction instance = ObjectPool.obtain(ClientTransaction.class);
if (instance == null) {
instance = new ClientTransaction();
}
instance.mClient = client;
instance.mActivityToken = activityToken;
return instance;
}
这个办法很简单,从池子里拿一个实例,或许新创立一个实例目标,将这个实例目标的两个成员变量赋值后回来
然后咱们调用了ClientTransaction.addCallback
办法将ClientTransactionItem
加入到回调行列中,ClientTransactionItem
是一条能够被履行的生命周期回调音讯,它是一个抽象类,子类需求完成它的preExecute
、execute
、postExecute
办法
咱们这儿传入的是LaunchActivityItem
,这条音讯是用来发动Activity
的
然后咱们调用ClientTransaction.setLifecycleStateRequest
设置当业务履行完毕后,Activity
应该处在一个怎样的生命周期
最终调用ATMS.getLifecycleManager.scheduleTransaction
调度履行这个业务,ATMS.getLifecycleManager
取得的是一个ClientLifecycleManager
目标,咱们沿着这个办法持续往下看
void scheduleTransaction(ClientTransaction transaction) throws RemoteException {
final IApplicationThread client = transaction.getClient();
transaction.schedule();
if (!(client instanceof Binder)) {
// If client is not an instance of Binder - it's a remote call and at this point it is
// safe to recycle the object. All objects used for local calls will be recycled after
// the transaction is executed on client in ActivityThread.
transaction.recycle();
}
}
除了收回调用recycle
之外,咱们又回到了ClientTransaction
中,调用其schedule
办法
public void schedule() throws RemoteException {
mClient.scheduleTransaction(this);
}
这儿又跨进程回到了App
进程中,调用ApplicationThread.scheduleTransaction
public void scheduleTransaction(ClientTransaction transaction) throws RemoteException {
ActivityThread.this.scheduleTransaction(transaction);
}
最终调用ActivityThread.scheduleTransaction
履行业务,ActivityThread
继承自ClientTransactionHandler
,scheduleTransaction
办法是在这儿面界说的
void scheduleTransaction(ClientTransaction transaction) {
transaction.preExecute(this);
sendMessage(ActivityThread.H.EXECUTE_TRANSACTION, transaction);
}
首要,调用ClientTransaction.preExecute
办法,然后经过Handler
发送履行一条EXECUTE_TRANSACTION
音讯,咱们先看一下preExecute
public void preExecute(android.app.ClientTransactionHandler clientTransactionHandler) {
if (mActivityCallbacks != null) {
final int size = mActivityCallbacks.size();
for (int i = 0; i < size; ++i) {
mActivityCallbacks.get(i).preExecute(clientTransactionHandler, mActivityToken);
}
}
if (mLifecycleStateRequest != null) {
mLifecycleStateRequest.preExecute(clientTransactionHandler, mActivityToken);
}
}
能够看到,便是遍历整个callback
列表,履行preExecute
办法,最终再履行LifecycleStateRequest
的preExecute
办法,对应到Activity
发动流程中,便是先履行LaunchActivityItem.preExecute
,再履行ResumeActivityItem.preExecute
// LaunchActivityItem
public void preExecute(ClientTransactionHandler client, IBinder token) {
client.countLaunchingActivities(1);
client.updateProcessState(mProcState, false);
client.updatePendingConfiguration(mCurConfig);
}
// ResumeActivityItem
public void preExecute(ClientTransactionHandler client, IBinder token) {
//这儿mUpdateProcState为false,不履行
if (mUpdateProcState) {
client.updateProcessState(mProcState, false);
}
}
都是一些状况更新之类的东西,咱们就直接越过,然后咱们看ActivityThread
在收到EXECUTE_TRANSACTION
音讯后做了什么
public void handleMessage(Message msg) {
switch (msg.what) {
...
case EXECUTE_TRANSACTION:
final ClientTransaction transaction = (ClientTransaction) msg.obj;
mTransactionExecutor.execute(transaction);
...
break;
...
}
...
}
这儿能够看到,调用了TransactionExecutor
目标的execute
办法,TransactionExecutor
目标在ActivityThread
创立时便创立了,内部持有一个ClientTransactionHandler
引证,即ActivityThread
自身
public void execute(ClientTransaction transaction) {
final IBinder token = transaction.getActivityToken();
//处理需求毁掉的Activities
if (token != null) {
final Map<IBinder, ClientTransactionItem> activitiesToBeDestroyed =
mTransactionHandler.getActivitiesToBeDestroyed();
final ClientTransactionItem destroyItem = activitiesToBeDestroyed.get(token);
if (destroyItem != null) {
if (transaction.getLifecycleStateRequest() == destroyItem) {
// It is going to execute the transaction that will destroy activity with the
// token, so the corresponding to-be-destroyed record can be removed.
activitiesToBeDestroyed.remove(token);
}
if (mTransactionHandler.getActivityClient(token) == null) {
// The activity has not been created but has been requested to destroy, so all
// transactions for the token are just like being cancelled.
//Activity没有被创立就被请求destroy,直接撤销整个业务
Slog.w(TAG, tId(transaction) + "Skip pre-destroyed transaction:\n"
+ transactionToString(transaction, mTransactionHandler));
return;
}
}
}
executeCallbacks(transaction);
executeLifecycleState(transaction);
mPendingActions.clear();
}
处理需求毁掉的Activities
这儿咱们不重视,就直接越过,然后便是别离履行各个ClientTransactionItem
回调音讯,最终让其调度履行咱们设置的终究的生命周期
public void executeCallbacks(ClientTransaction transaction) {
final List<ClientTransactionItem> callbacks = transaction.getCallbacks();
if (callbacks == null || callbacks.isEmpty()) {
// No callbacks to execute, return early.
return;
}
final IBinder token = transaction.getActivityToken();
ActivityClientRecord r = mTransactionHandler.getActivityClient(token);
... //生命周期转化相关
final int size = callbacks.size();
for (int i = 0; i < size; ++i) {
final ClientTransactionItem item = callbacks.get(i);
... //生命周期转化,在Activity发动时不会走进这个case
item.execute(mTransactionHandler, token, mPendingActions);
item.postExecute(mTransactionHandler, token, mPendingActions);
if (r == null) {
// Launch activity request will create an activity record.
//在履行完发动Activity后会新建一个ActivityClientRecord,从头赋值
r = mTransactionHandler.getActivityClient(token);
}
... //生命周期转化,在Activity发动时不会走进这个case
}
}
关于生命周期转化,因为Activity
发动的当时阶段不会进入这些case,所以这儿就不提了
经过简化,实际上也就履行了LaunchActivityItem.execute
和LaunchActivityItem.postExecute
办法
public void execute(ClientTransactionHandler client, IBinder token,
PendingTransactionActions pendingActions) {
ActivityClientRecord r = new ActivityClientRecord(token, mIntent, mIdent, mInfo,
mOverrideConfig, mCompatInfo, mReferrer, mVoiceInteractor, mState, mPersistentState,
mPendingResults, mPendingNewIntents, mIsForward,
mProfilerInfo, client, mAssistToken, mFixedRotationAdjustments);
client.handleLaunchActivity(r, pendingActions, null /* customIntent */);
}
这儿运用之前在AMS
中创立LaunchActivityItem
所运用到的信息,创立了一个ActivityClientRecord
目标,接着回到ActivityThread
,调用其handleLaunchActivity
办法
handleLaunchActivity
public Activity handleLaunchActivity(ActivityClientRecord r,
PendingTransactionActions pendingActions, Intent customIntent) {
// If we are getting ready to gc after going to the background, well
// we are back active so skip it.
unscheduleGcIdler();
mSomeActivitiesChanged = true;
if (r.profilerInfo != null) {
mProfiler.setProfiler(r.profilerInfo);
mProfiler.startProfiling();
}
// Make sure we are running with the most recent config.
//保证Configuration为最新
handleConfigurationChanged(null, null);
// Initialize before creating the activity
//初始化硬件加速
if (!ThreadedRenderer.sRendererDisabled
&& (r.activityInfo.flags & ActivityInfo.FLAG_HARDWARE_ACCELERATED) != 0) {
HardwareRenderer.preload();
}
//保证WMS被初始化
WindowManagerGlobal.initialize();
// Hint the GraphicsEnvironment that an activity is launching on the process.
//通知有Activity发动
GraphicsEnvironment.hintActivityLaunch();
//履行发动Activity
final Activity a = performLaunchActivity(r, customIntent);
if (a != null) {
//设置Configuration
r.createdConfig = new Configuration(mConfiguration);
reportSizeConfigurations(r);
//设置一些推迟履行的动作(效果域到整个ClientTransaction完毕)
if (!r.activity.mFinished && pendingActions != null) {
pendingActions.setOldState(r.state);
//当Activity生命周期走到onStart前,会经过这儿设置的值
//判别是否需求履行onRestoreInstanceState、onPostCreate
pendingActions.setRestoreInstanceState(true);
pendingActions.setCallOnPostCreate(true);
}
} else {
// If there was an error, for any reason, tell the activity manager to stop us.
//呈现过错,中止发动Activity
try {
ActivityTaskManager.getService()
.finishActivity(r.token, Activity.RESULT_CANCELED, null,
Activity.DONT_FINISH_TASK_WITH_ACTIVITY);
} catch (RemoteException ex) {
throw ex.rethrowFromSystemServer();
}
}
return a;
}
这个办法中,最重要的莫过于performLaunchActivity
了,它是创立Activity
的核心办法
/** Core implementation of activity launch. */
private Activity performLaunchActivity(ActivityClientRecord r, Intent customIntent) {
ActivityInfo aInfo = r.activityInfo;
//设置LoadedApk
if (r.packageInfo == null) {
r.packageInfo = getPackageInfo(aInfo.applicationInfo, r.compatInfo,
Context.CONTEXT_INCLUDE_CODE);
}
ComponentName component = r.intent.getComponent();
if (component == null) {
component = r.intent.resolveActivity(
mInitialApplication.getPackageManager());
r.intent.setComponent(component);
}
//假如发动的Activity是一个activity-alias,将Component设置为真实的Activity组件
//详见:https://developer.android.com/guide/topics/manifest/activity-alias-element?hl=zh-cn
if (r.activityInfo.targetActivity != null) {
component = new ComponentName(r.activityInfo.packageName,
r.activityInfo.targetActivity);
}
//为Activity创立BaseContext
ContextImpl appContext = createBaseContextForActivity(r);
Activity activity = null;
try {
java.lang.ClassLoader cl = appContext.getClassLoader();
//实例化Activity
activity = mInstrumentation.newActivity(
cl, component.getClassName(), r.intent);
StrictMode.incrementExpectedActivityCount(activity.getClass());
r.intent.setExtrasClassLoader(cl);
r.intent.prepareToEnterProcess();
if (r.state != null) {
r.state.setClassLoader(cl);
}
} catch (Exception e) {
...
}
try {
//创立或获取Application
//假如该Activity指定在其他的一个新的进程中发动(设置了android:process特点),则会新创立Application
//正常不涉及多进程,都是直接获取之前创立好的Application
Application app = r.packageInfo.makeApplication(false, mInstrumentation);
if (activity != null) {
//Manifest中Activity标签下的label特点
CharSequence title = r.activityInfo.loadLabel(appContext.getPackageManager());
//预备Configuration
Configuration config = new Configuration(mCompatConfiguration);
if (r.overrideConfig != null) {
config.updateFrom(r.overrideConfig);
}
Window window = null;
//当relaunch Activity的时分mPreserveWindow才会为true(比如说调用Activity.recreate办法)
if (r.mPendingRemoveWindow != null && r.mPreserveWindow) {
window = r.mPendingRemoveWindow;
r.mPendingRemoveWindow = null;
r.mPendingRemoveWindowManager = null;
}
// Activity resources must be initialized with the same loaders as the
// application context.
//设置Activity Resource的Loaders与Application Resource的Loaders一致
appContext.getResources().addLoaders(
app.getResources().getLoaders().toArray(new ResourcesLoader[0]));
appContext.setOuterContext(activity);
//重要:绑定BaseContext、创立PhoneWindow等一系列初始化工作
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);
if (customIntent != null) {
activity.mIntent = customIntent;
}
r.lastNonConfigurationInstances = null;
//更新网络状况
checkAndBlockForNetworkAccess();
activity.mStartedActivity = false;
//设置主题
int theme = r.activityInfo.getThemeResource();
if (theme != 0) {
activity.setTheme(theme);
}
activity.mCalled = false;
//调用Activity的onCreate办法
if (r.isPersistable()) {
mInstrumentation.callActivityOnCreate(activity, r.state, r.persistentState);
} else {
mInstrumentation.callActivityOnCreate(activity, r.state);
}
if (!activity.mCalled) {
//在履行完super.onCreate办法后,mCalled会被置为true
//假如mCalled为false,说明没有履行super.onCreate办法
throw new SuperNotCalledException(
"Activity " + r.intent.getComponent().toShortString() +
" did not call through to super.onCreate()");
}
r.activity = activity;
mLastReportedWindowingMode.put(activity.getActivityToken(),
config.windowConfiguration.getWindowingMode());
}
//设置生命周期状况为onCreate
r.setState(ON_CREATE);
// updatePendingActivityConfiguration() reads from mActivities to update
// ActivityClientRecord which runs in a different thread. Protect modifications to
// mActivities to avoid race.
//将新建的ActivityClientRecord增加到mActivities中
synchronized (mResourcesManager) {
mActivities.put(r.token, r);
}
} catch (SuperNotCalledException e) {
throw e;
} catch (Exception e) {
...
}
return activity;
}
这个办法首要做了以下几个工作:
-
预备创立
Activity
所必要的信息,譬如类名等 -
为
Activity
创立BaseContext
-
经过
Instrumentation
实例化Activity
-
创立或获取
Activity
进程所对应的Application
-
初始化
Activity
,履行各种绑定工作,创立PhoneWindow
等 -
履行
Activity
的onCreate
生命周期办法 -
将
ActivityClientRecord
生命周期状况设置为onCreate
咱们要点看一下最首要的实例化、attach
和onCreate
这三点
Instrumentation.newActivity
咱们在 Android源码剖析 – Activity发动流程(中) 中剖析了,Application
是怎样经过Instrumentation
创立的,Activity
的创立和它相似
public Activity newActivity(ClassLoader cl, String className,
Intent intent)
throws InstantiationException, IllegalAccessException,
ClassNotFoundException {
String pkg = intent != null && intent.getComponent() != null
? intent.getComponent().getPackageName() : null;
return getFactory(pkg).instantiateActivity(cl, className, intent);
}
相同的运用了AppComponentFactory
创立,咱们仍是去看一下它的默许完成
public @NonNull Activity instantiateActivity(@NonNull ClassLoader cl, @NonNull String className,
@Nullable Intent intent)
throws InstantiationException, IllegalAccessException, ClassNotFoundException {
return (Activity) cl.loadClass(className).newInstance();
}
相同的,也是经过类名反射创立一个Activity
的实例
Activity.attach
紧接着,咱们来看Activity.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, IBinder assistToken) {
//绑定BaseContext
attachBaseContext(context);
//初始化Fragment控制器
mFragments.attachHost(null /*parent*/);
//创立并设置Window用于显现界面
mWindow = new PhoneWindow(this, window, activityConfigCallback);
mWindow.setWindowControllerCallback(mWindowControllerCallback);
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);
}
//各成员变量初始化
mUiThread = Thread.currentThread();
mMainThread = aThread;
mInstrumentation = instr;
mToken = token;
mAssistToken = assistToken;
mIdent = ident;
mApplication = application;
mIntent = intent;
mReferrer = referrer;
mComponent = intent.getComponent();
mActivityInfo = info;
mTitle = title;
mParent = parent;
mEmbeddedID = id;
mLastNonConfigurationInstances = lastNonConfigurationInstances;
if (voiceInteractor != null) {
if (lastNonConfigurationInstances != null) {
mVoiceInteractor = lastNonConfigurationInstances.voiceInteractor;
} else {
mVoiceInteractor = new VoiceInteractor(voiceInteractor, this, this,
Looper.myLooper());
}
}
//设置WindowManager、ActivityRecordToken以及是否运用硬件加速
mWindow.setWindowManager(
(WindowManager)context.getSystemService(Context.WINDOW_SERVICE),
mToken, mComponent.flattenToString(),
(info.flags & ActivityInfo.FLAG_HARDWARE_ACCELERATED) != 0);
if (mParent != null) {
mWindow.setContainer(mParent.getWindow());
}
mWindowManager = mWindow.getWindowManager();
mCurrentConfig = config;
mWindow.setColorMode(info.colorMode);
mWindow.setPreferMinimalPostProcessing(
(info.flags & ActivityInfo.FLAG_PREFER_MINIMAL_POST_PROCESSING) != 0);
//设置主动填充选项
setAutofillOptions(application.getAutofillOptions());
//设置内容捕获功用
setContentCaptureOptions(application.getContentCaptureOptions());
}
这儿能够看到,attach
办法首要做了以下几件事:
-
绑定
BaseContext
-
初始化
Fragment
控制器 -
创立并设置
Window
-
各种成员变量及其他特点初始化
看完这个办法,咱们能够发现,本来Activity
的Window
是在这个时分创立的,并且Window
的详细完成类为PhoneWindow
再然后便是经过Instrumentation
履行Activity
的onCreate
生命周期办法了
public void callActivityOnCreate(Activity activity, Bundle icicle) {
prePerformCreate(activity);
activity.performCreate(icicle);
postPerformCreate(activity);
}
其中prePerformCreate
和postPerformCreate
似乎只要在单元测验和CTS测验下才会发生实质性的影响,在正常状况下咱们就当作它们不存在,咱们接着看performCreate
办法
Activity.performCreate
final void performCreate(Bundle icicle) {
performCreate(icicle, null);
}
final void performCreate(Bundle icicle, PersistableBundle persistentState) {
//分发PreCreated事情,履行一切注册的ActivityLifecycleCallbacks的onActivityPreCreated回调
dispatchActivityPreCreated(icicle);
mCanEnterPictureInPicture = true;
// initialize mIsInMultiWindowMode and mIsInPictureInPictureMode before onCreate
final int windowingMode = getResources().getConfiguration().windowConfiguration
.getWindowingMode();
//多窗口方式
mIsInMultiWindowMode = inMultiWindowMode(windowingMode);
//画中画方式(小窗播映视频等场景)
mIsInPictureInPictureMode = windowingMode == WINDOWING_MODE_PINNED;
//康复请求权限中的标志位
restoreHasCurrentPermissionRequest(icicle);
//履行onCreate生命周期办法
if (persistentState != null) {
onCreate(icicle, persistentState);
} else {
onCreate(icicle);
}
//同享元素动画相关
mActivityTransitionState.readState(icicle);
mVisibleFromClient = !mWindow.getWindowStyle().getBoolean(
com.android.internal.R.styleable.Window_windowNoDisplay, false);
//FragmentManager分发ACTIVITY_CREATED状况
mFragments.dispatchActivityCreated();
//同享元素动画相关
mActivityTransitionState.setEnterActivityOptions(this, getActivityOptions());
//分发PostCreated事情,履行一切注册的ActivityLifecycleCallbacks的onActivityPostCreated回调
dispatchActivityPostCreated(icicle);
}
其中的参数icicle
便是咱们平时重写Activity.onCreate
办法时的第一个入参savedInstanceState
,假如Activity
发生了重建之类的状况,它会保存一些状况数据,第一次发动Activity
时为null
不管persistentState
是否为null
,终究都会进入到单个参数的onCreate
办法中
protected void onCreate(@Nullable Bundle savedInstanceState) {
//康复LoaderManager
if (mLastNonConfigurationInstances != null) {
mFragments.restoreLoaderNonConfig(mLastNonConfigurationInstances.loaders);
}
//ActionBar
if (mActivityInfo.parentActivityName != null) {
if (mActionBar == null) {
mEnableDefaultActionBarUp = true;
} else {
mActionBar.setDefaultDisplayHomeAsUpEnabled(true);
}
}
if (savedInstanceState != null) {
//主动填充功用
mAutoFillResetNeeded = savedInstanceState.getBoolean(AUTOFILL_RESET_NEEDED, false);
mLastAutofillId = savedInstanceState.getInt(LAST_AUTOFILL_ID,
View.LAST_APP_AUTOFILL_ID);
if (mAutoFillResetNeeded) {
getAutofillManager().onCreate(savedInstanceState);
}
//康复FragmentManager状况
Parcelable p = savedInstanceState.getParcelable(FRAGMENTS_TAG);
mFragments.restoreAllState(p, mLastNonConfigurationInstances != null
? mLastNonConfigurationInstances.fragments : null);
}
//FragmentManager分发CREATED状况,履行内部Fragment的生命周期
mFragments.dispatchCreate();
//分发Created事情,履行一切注册的ActivityLifecycleCallbacks的onActivityCreated回调
dispatchActivityCreated(savedInstanceState);
//语音交互功用
if (mVoiceInteractor != null) {
mVoiceInteractor.attachActivity(this);
}
mRestoredFromBundle = savedInstanceState != null;
//这儿表示已调用过super.onCreate办法
mCalled = true;
}
到这儿,Activity
的onCreate
生命周期就走完了,咱们也能够从这整个流程中得到一些新的收获,比如说,本来注册在Application
中的ActivityLifecycleCallbacks
回调是在这儿触发的,FragmentManager
状况分发的次序是这样的,为什么有必要要调用super.onCreate
办法等等
接着,咱们再回到TransactionExecutor
中,它接下来履行的是LaunchActivityItem.postExecute
public void postExecute(ClientTransactionHandler client, IBinder token,
PendingTransactionActions pendingActions) {
client.countLaunchingActivities(-1);
}
这儿就非常简单了,计数器减一
postExecute
履行完后,整个LaunchActivityItem
的工作就完成了,接下来履行的是TransactionExecutor.executeLifecycleState
办法
private void executeLifecycleState(ClientTransaction transaction) {
final ActivityLifecycleItem lifecycleItem = transaction.getLifecycleStateRequest();
if (lifecycleItem == null) {
// No lifecycle request, return early.
return;
}
final IBinder token = transaction.getActivityToken();
final ActivityClientRecord r = mTransactionHandler.getActivityClient(token);
if (r == null) {
// Ignore requests for non-existent client records for now.
return;
}
// Cycle to the state right before the final requested state.
//excludeLastState为true的状况下,推动生命周期直到终究生命周期的上一个生命周期
//excludeLastState为false的状况下,推动生命周期直到终究生命周期
cycleToPath(r, lifecycleItem.getTargetState(), true /* excludeLastState */, transaction);
// Execute the final transition with proper parameters.
//履行终究的生命周期业务
lifecycleItem.execute(mTransactionHandler, token, mPendingActions);
lifecycleItem.postExecute(mTransactionHandler, token, mPendingActions);
}
咱们现在处在的生命周期为ON_CREATE
终究目标要到达的生命周期为ON_RESUME
,cycleToPath
办法会帮助咱们把生命周期推动到ON_RESUME
的上一个生命周期也便是ON_START
private void cycleToPath(ActivityClientRecord r, int finish, boolean excludeLastState,
ClientTransaction transaction) {
final int start = r.getLifecycleState();
final IntArray path = mHelper.getLifecyclePath(start, finish, excludeLastState);
performLifecycleSequence(r, path, transaction);
}
TransactionExecutorHelper.getLifecyclePath
办法会帮咱们计算出一个剩下要经过的生命周期路线的一个有序数组
public IntArray getLifecyclePath(int start, int finish, boolean excludeLastState) {
... //过错判别
mLifecycleSequence.clear();
if (finish >= start) {
if (start == ON_START && finish == ON_STOP) {
// A case when we from start to stop state soon, we don't need to go
// through the resumed, paused state.
mLifecycleSequence.add(ON_STOP);
} else {
// just go there
//按次序增加生命周期
for (int i = start + 1; i <= finish; i++) {
mLifecycleSequence.add(i);
}
}
} else { // finish < start, can't just cycle down
if (start == ON_PAUSE && finish == ON_RESUME) {
// Special case when we can just directly go to resumed state.
mLifecycleSequence.add(ON_RESUME);
} else if (start <= ON_STOP && finish >= ON_START) {
// Restart and go to required state.
// Go to stopped state first.
for (int i = start + 1; i <= ON_STOP; i++) {
mLifecycleSequence.add(i);
}
// Restart
mLifecycleSequence.add(ON_RESTART);
// Go to required state
for (int i = ON_START; i <= finish; i++) {
mLifecycleSequence.add(i);
}
} else {
// Relaunch and go to required state
// Go to destroyed state first.
for (int i = start + 1; i <= ON_DESTROY; i++) {
mLifecycleSequence.add(i);
}
// Go to required state
for (int i = ON_CREATE; i <= finish; i++) {
mLifecycleSequence.add(i);
}
}
}
// Remove last transition in case we want to perform it with some specific params.
if (excludeLastState && mLifecycleSequence.size() != 0) {
mLifecycleSequence.remove(mLifecycleSequence.size() - 1);
}
return mLifecycleSequence;
}
其实从这个办法,咱们就能看出Activity
生命周期是怎样设计的,代码很简单,我就不解释了
public static final int UNDEFINED = -1;
public static final int PRE_ON_CREATE = 0;
public static final int ON_CREATE = 1;
public static final int ON_START = 2;
public static final int ON_RESUME = 3;
public static final int ON_PAUSE = 4;
public static final int ON_STOP = 5;
public static final int ON_DESTROY = 6;
public static final int ON_RESTART = 7;
咱们结合这上面这个生命周期巨细来看,start
为ON_CREATE
,finish
为ON_RESUME
,excludeLastState
为true
移除最终一个生命周期,得出的结果便是[ON_START]
,然后调用performLifecycleSequence
办法履行生命周期
private void performLifecycleSequence(ActivityClientRecord r, IntArray path,
ClientTransaction transaction) {
final int size = path.size();
for (int i = 0, state; i < size; i++) {
state = path.get(i);
switch (state) {
case ON_CREATE:
mTransactionHandler.handleLaunchActivity(r, mPendingActions,
null /* customIntent */);
break;
case ON_START:
mTransactionHandler.handleStartActivity(r, mPendingActions,
null /* activityOptions */);
break;
case ON_RESUME:
mTransactionHandler.handleResumeActivity(r, false /* finalStateRequest */,
r.isForward, "LIFECYCLER_RESUME_ACTIVITY");
break;
case ON_PAUSE:
mTransactionHandler.handlePauseActivity(r, false /* finished */,
false /* userLeaving */, 0 /* configChanges */,
false /* autoEnteringPip */, mPendingActions,
"LIFECYCLER_PAUSE_ACTIVITY");
break;
case ON_STOP:
mTransactionHandler.handleStopActivity(r, 0 /* configChanges */,
mPendingActions, false /* finalStateRequest */,
"LIFECYCLER_STOP_ACTIVITY");
break;
case ON_DESTROY:
mTransactionHandler.handleDestroyActivity(r, false /* finishing */,
0 /* configChanges */, false /* getNonConfigInstance */,
"performLifecycleSequence. cycling to:" + path.get(size - 1));
break;
case ON_RESTART:
mTransactionHandler.performRestartActivity(r, false /* start */);
break;
default:
throw new IllegalArgumentException("Unexpected lifecycle state: " + state);
}
}
}
这个办法很简单啊,便是遍历这个数组,依次履行生命周期,结合咱们传入的数组[ON_START]
,最终便是调用ActivityThread.handleStartActivity
办法
handleStartActivity
public void handleStartActivity(IBinder token, PendingTransactionActions pendingActions) {
final ActivityClientRecord r = mActivities.get(token);
final Activity activity = r.activity;
... //查看
unscheduleGcIdler();
// Start
//履行onStart生命周期
activity.performStart("handleStartActivity");
//设置生命周期状况为onStart
r.setState(ON_START);
if (pendingActions == null) {
// No more work to do.
return;
}
// Restore instance state
//之前在handleLaunchActivity办法中设置了pendingActions.setRestoreInstanceState(true)
//这儿便会判别是否需求并履行Activity.onRestoreInstanceState
if (pendingActions.shouldRestoreInstanceState()) {
if (r.isPersistable()) {
if (r.state != null || r.persistentState != null) {
mInstrumentation.callActivityOnRestoreInstanceState(activity, r.state,
r.persistentState);
}
} else if (r.state != null) {
mInstrumentation.callActivityOnRestoreInstanceState(activity, r.state);
}
}
// Call postOnCreate()
//之前在handleLaunchActivity办法中设置了pendingActions.setCallOnPostCreate(true)
//这儿便会履行Activity.onPostCreate,假如不是从onCreate转到onStart,不会进入此case
if (pendingActions.shouldCallOnPostCreate()) {
activity.mCalled = false;
//调用Activity.onPostCreate
if (r.isPersistable()) {
mInstrumentation.callActivityOnPostCreate(activity, r.state,
r.persistentState);
} else {
mInstrumentation.callActivityOnPostCreate(activity, r.state);
}
if (!activity.mCalled) {
//和onCreate相同,onPostCreate也有必要要调用super.onPostCreate
throw new SuperNotCalledException(
"Activity " + r.intent.getComponent().toShortString()
+ " did not call through to super.onPostCreate()");
}
}
//更新可见性
//Activity发动时,因为此刻mDecor还未赋值,所以不会发生影响
updateVisibility(r, true /* show */);
mSomeActivitiesChanged = true;
}
这儿有一点需求留意,咱们一般重写Activity
的onCreate
办法,在其中调用setContentView
办法,此刻DecorView
虽然被创立出来了,但是只在PhoneWindow
中持有,没有给Activity.mDecor
赋值,所以此刻调用updateVisibility
办法并不会将DecorView
加入到WindowManager
中,也便是现在界面还没有可见
另外,咱们能够留意到,performStart
是先于callActivityOnPostCreate
,所以Activity
中的生命周期回调onPostCreate
是在onStart
之后触发的,各位在开发App的时分不要弄错了这一点
其他的当地注释都写的都很理解了哈,也没什么必要再看performStart
了,无非也就和performCreate
相同,履行ActivityLifecycleCallbacks
回调,FragmentManager
分发STARTED
状况,调用onStart
办法等
接下来咱们再回到TransactionExecutor
中,后边便是履行ResumeActivityItem
的execute
和postExecute
办法了
public void execute(ClientTransactionHandler client, ActivityClientRecord r,
PendingTransactionActions pendingActions) {
client.handleResumeActivity(r, true /* finalStateRequest */, mIsForward,
"RESUME_ACTIVITY");
}
能够看到,又履行了ActivityThread.handleResumeActivity
办法
handleResumeActivity
public void handleResumeActivity(IBinder token, boolean finalStateRequest, boolean isForward,
String reason) {
// If we are getting ready to gc after going to the background, well
// we are back active so skip it.
unscheduleGcIdler();
mSomeActivitiesChanged = true;
// TODO Push resumeArgs into the activity for consideration
//履行onResume生命周期
final ActivityClientRecord r = performResumeActivity(token, finalStateRequest, reason);
if (r == null) {
// We didn't actually resume the activity, so skipping any follow-up actions.
return;
}
//假如Activity将被destroy,那就没必要再履行resume了,直接回来
if (mActivitiesToBeDestroyed.containsKey(token)) {
// Although the activity is resumed, it is going to be destroyed. So the following
// UI operations are unnecessary and also prevents exception because its token may
// be gone that window manager cannot recognize it. All necessary cleanup actions
// performed below will be done while handling destruction.
return;
}
final Activity a = r.activity;
final int forwardBit = isForward
? WindowManager.LayoutParams.SOFT_INPUT_IS_FORWARD_NAVIGATION : 0;
// If the window hasn't yet been added to the window manager,
// and this guy didn't finish itself or start another activity,
// then go ahead and add the window.
boolean willBeVisible = !a.mStartedActivity;
if (!willBeVisible) {
try {
willBeVisible = ActivityTaskManager.getService().willActivityBeVisible(
a.getActivityToken());
} catch (RemoteException e) {
throw e.rethrowFromSystemServer();
}
}
//设置Window
if (r.window == null && !a.mFinished && willBeVisible) {
r.window = r.activity.getWindow();
View decor = r.window.getDecorView();
//DecorView暂时不行见
decor.setVisibility(View.INVISIBLE);
ViewManager wm = a.getWindowManager();
WindowManager.LayoutParams l = r.window.getAttributes();
//给Activity的mDecor成员变量赋值
a.mDecor = decor;
l.type = WindowManager.LayoutParams.TYPE_BASE_APPLICATION;
l.softInputMode |= forwardBit;
if (r.mPreserveWindow) {
a.mWindowAdded = true;
r.mPreserveWindow = false;
// Normally the ViewRoot sets up callbacks with the Activity
// in addView->ViewRootImpl#setView. If we are instead reusing
// the decor view we have to notify the view root that the
// callbacks may have changed.
ViewRootImpl impl = decor.getViewRootImpl();
if (impl != null) {
impl.notifyChildRebuilt();
}
}
//假如DecorView没有增加到WindowManager中,将其增加进去,不然更新Window特点
//Activity发动进程中,第一次resume时,DecorView还没有增加至WindowManager,所以会走进上面这个case
//因为咱们之前将DecorView的Visibility设置成了INVISIBLE,所以此刻界面仍是不行见
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);
}
}
// If the window has already been added, but during resume
// we started another activity, then don't yet make the
// window visible.
} else if (!willBeVisible) {
r.hideForNow = true;
}
// Get rid of anything left hanging around.
//清除留传的东西
cleanUpPendingRemoveWindows(r, false /* force */);
// The window is now visible if it has been added, we are not
// simply finishing, and we are not starting another activity.
if (!r.activity.mFinished && willBeVisible && r.activity.mDecor != null && !r.hideForNow) {
//分发Configuration更新事情
if (r.newConfig != null) {
performConfigurationChangedForActivity(r, r.newConfig);
r.newConfig = null;
}
//当DecorView add进WindowManager后,ViewRootImpl被创立
ViewRootImpl impl = r.window.getDecorView().getViewRootImpl();
WindowManager.LayoutParams l = impl != null
? impl.mWindowAttributes : r.window.getAttributes();
... //软键盘相关
r.activity.mVisibleFromServer = true;
mNumVisibleActivities++;
//使DecorView可见
if (r.activity.mVisibleFromClient) {
r.activity.makeVisible();
}
}
//当空闲时,查看处理其他后台Activity状况
//对处在stopping或finishing的Activity履行onStop或onDestroy生命周期
r.nextIdle = mNewActivities;
mNewActivities = r;
Looper.myQueue().addIdleHandler(new Idler());
}
这儿有三个重要的当地需求留意:
-
履行
performResumeActivity
,这儿和之前剖析的两个生命周期相似,咱们后边再看 -
给
Activity
的mDecor
成员变量赋值,将DecorView
增加到WindowManager
中,使DecorView
可见 -
将上一个活动的
ActivityClientRecord
以链表的方式串在当时ActivityClientRecord
后边,向MessageQueue
增加一条闲时处理音讯Idler
,这条音讯会遍历ActivityClientRecord
的整条nextIdle
链,依次查看是否需求stop
或destroy
Activity
,这一点我会在后边关于Activity
其他生命周期的文章中再剖析
接下来咱们简单过一下performResumeActivity
吧
public ActivityClientRecord performResumeActivity(IBinder token, boolean finalStateRequest,
String reason) {
final ActivityClientRecord r = mActivities.get(token);
... //状况查看
//为终究生命周期状况
if (finalStateRequest) {
r.hideForNow = false;
r.activity.mStartedActivity = false;
}
try {
r.activity.onStateNotSaved();
//符号Fragments状况为未保存
r.activity.mFragments.noteStateNotSaved();
//更新网络状况
checkAndBlockForNetworkAccess();
if (r.pendingIntents != null) {
deliverNewIntents(r, r.pendingIntents);
r.pendingIntents = null;
}
if (r.pendingResults != null) {
deliverResults(r, r.pendingResults, reason);
r.pendingResults = null;
}
//履行Activity.onResume生命周期
r.activity.performResume(r.startsNotResumed, reason);
//将保存信息的savedInstanceState和persistentState重置为null
r.state = null;
r.persistentState = null;
//设置生命周期状况
r.setState(ON_RESUME);
//回调Activity.onTopResumedActivityChanged,陈述栈顶活动Activity发生变化
reportTopResumedActivityChanged(r, r.isTopResumedActivity, "topWhenResuming");
} catch (Exception e) {
...
}
return r;
}
final void performResume(boolean followedByPause, String reason) {
//回调ActivityLifecycleCallbacks.onActivityPreResumed
dispatchActivityPreResumed();
//履行onRestart生命周期
//内部会判别当时Activity是否为stop状况,是的话才会真实履行onRestart生命周期
//发动Activity第一次resume时不会进入onRestart生命周期
performRestart(true /* start */, reason);
mFragments.execPendingActions();
mLastNonConfigurationInstances = null;
... //主动填充功用
mCalled = false;
// mResumed is set by the instrumentation
//履行Activity.onResume回调
mInstrumentation.callActivityOnResume(this);
if (!mCalled) {
//有必要履行super.onResume办法
throw new SuperNotCalledException(
"Activity " + mComponent.toShortString() +
" did not call through to super.onResume()");
}
// invisible activities must be finished before onResume() completes
... //异常查看
// Now really resume, and install the current status bar and menu.
mCalled = false;
//FragmentManager分发resume状况
mFragments.dispatchResume();
mFragments.execPendingActions();
//履行onPostResume回调
onPostResume();
if (!mCalled) {
//有必要要履行super.onPostResume
throw new SuperNotCalledException(
"Activity " + mComponent.toShortString() +
" did not call through to super.onPostResume()");
}
//回调ActivityLifecycleCallbacks.onActivityPostResumed
dispatchActivityPostResumed();
}
protected void onResume() {
//回调ActivityLifecycleCallbacks.onActivityResumed
dispatchActivityResumed();
//同享元素动画
mActivityTransitionState.onResume(this);
... //主动填充功用
notifyContentCaptureManagerIfNeeded(CONTENT_CAPTURE_RESUME);
mCalled = true;
}
能够看到,基本上和之前的两个生命周期的履行是一个套路,唯一需求留意的是,在履行onResume
生命周期之前,会先查看Activity
是否处在stop
状况,假如是的话,则会先履行onRestart
生命周期,其他当地我在注释上标注的应该现已很理解了,这儿就不再多讲了
不要忘了,在TransactionExecutor
中还有最终一步ResumeActivityItem.postExecute
没做
public void postExecute(ClientTransactionHandler client, IBinder token,
PendingTransactionActions pendingActions) {
try {
// TODO(lifecycler): Use interface callback instead of AMS.
ActivityTaskManager.getService().activityResumed(token);
} catch (RemoteException ex) {
throw ex.rethrowFromSystemServer();
}
}
这儿经过Binder
又回到了体系进程调用了ATMS.activityResumed
办法
public final void activityResumed(IBinder token) {
final long origId = Binder.clearCallingIdentity();
synchronized (mGlobalLock) {
ActivityRecord.activityResumedLocked(token);
}
Binder.restoreCallingIdentity(origId);
}
static void activityResumedLocked(IBinder token, boolean handleSplashScreenExit) {
final ActivityRecord r = ActivityRecord.forTokenLocked(token);
if (r == null) {
// If an app reports resumed after a long delay, the record on server side might have
// been removed (e.g. destroy timeout), so the token could be null.
return;
}
//SplashScreen
r.setCustomizeSplashScreenExitAnimation(handleSplashScreenExit);
//重置savedState Bundle
r.setSavedState(null /* savedState */);
r.mDisplayContent.handleActivitySizeCompatModeIfNeeded(r);
//防闪耀功用
r.mDisplayContent.mUnknownAppVisibilityController.notifyAppResumedFinished(r);
}
能够看到,最终也就做了一些收尾工作,到这儿,整个Activity
的发动流程也就圆满完毕了
结束
至此为止,咱们Activity
发动流程三部连续剧终所以圆满完成了,历时整整半年的时间,我心里压着的这块石头也终所以落地了,后边我应该会再做一些关于Activity
其他生命周期变换的剖析,比如说Activity
是怎样毁掉的,欢迎感兴趣的小伙伴点赞、收藏、重视我