解析Activity启动-生命周期角度
-
书接上回,在 AMS侧解析Activity启动 篇章中,我们大致梳理了 Activity 启动过程中涉及到堆栈的整体流程,本篇再让我们从 Activity 生命周期的角度来梳理整个流程 -
顺着上一篇 解析Activity启动-堆栈篇 的流程,在启动Activity时,会在 resumeTopActivityInnerLocked() 函数中调用 startPausingLocked() 函数对发起者Activity触发 Pause 动作,那么我们就按照启动顺序,进行逐一分析
① onPause
- 在前一篇文章中,我们也有涉及
startPausingLocked() 函数的分析,但是并没有特别细致和深入,那么在此处,我们顺着该函数,较为细致的解析一下
1.1 resumeTopActivityInnerLocked()
frameworks\base\services\core\java\com\android\server\am\ActivityStack.java
@GuardedBy("mService")
private boolean resumeTopActivityInnerLocked(ActivityRecord prev, ActivityOptions options) {
...
if (mResumedActivity != null) {
if (DEBUG_STATES)
Slog.d(TAG_STATES,
"resumeTopActivityLocked: Pausing " + mResumedActivity);
pausing |= startPausingLocked(userLeaving, false, next, false);
}
...
}
- 首先是调用起点,剔除与Pause流程无关的代码;可以看到,只有在对应 stack中存在
mResumedActivity 时,才会去触发进行Pause流程,很好理解,如果对应stack中并不存在Resume状态的Activity,那也就不存在Activity需要进行Pause,此处也重点关注一下传入的参数
1.2 startPausingLocked()
frameworks\base\services\core\java\com\android\server\am\ActivityStack.java
final boolean startPausingLocked(boolean userLeaving, boolean uiSleeping,
ActivityRecord resuming, boolean pauseImmediately) {
if (mPausingActivity != null) {
if (!shouldSleepActivities()) {
completePauseLocked(false, resuming);
}
}
ActivityRecord prev = mResumedActivity;
if (prev == null) {
...
return false;
}
if (prev == resuming) {
return false;
}
mPausingActivity = prev;
mLastPausedActivity = prev;
mLastNoHistoryActivity = (prev.intent.getFlags() & Intent.FLAG_ACTIVITY_NO_HISTORY) != 0
|| (prev.info.flags & ActivityInfo.FLAG_NO_HISTORY) != 0 ? prev : null;
prev.setState(PAUSING, "startPausingLocked");
...
if (prev.app != null && prev.app.thread != null) {
try {
...
mService.getLifecycleManager().scheduleTransaction(prev.app.thread, prev.appToken,
PauseActivityItem.obtain(prev.finishing, userLeaving,
prev.configChangeFlags, pauseImmediately));
} catch (Exception e) {
mPausingActivity = null;
mLastPausedActivity = null;
mLastNoHistoryActivity = null;
}
} else {
mPausingActivity = null;
mLastPausedActivity = null;
mLastNoHistoryActivity = null;
}
if (!uiSleeping && !mService.isSleepingOrShuttingDownLocked()) {
mStackSupervisor.acquireLaunchWakelock();
}
if (mPausingActivity != null) {
if (!uiSleeping) {
prev.pauseKeyDispatchingLocked();
} else if (DEBUG_PAUSE) {
Slog.v(TAG_PAUSE, "Key dispatch not paused for screen off");
}
if (pauseImmediately) {
completePauseLocked(false, resuming);
return false;
} else {
schedulePauseTimeout(prev);
return true;
}
} else {
...
}
}
- 解析该函数,除去执行条件判断,主要完成了如下的动作:
- 用
mPausingActivity 和 mLastPausedActivity 保存下待Pause的Activity,也就是 mResumedActivity ;根据 mResumedActivity 中相关标志位(FLAG_ACTIVITY_NO_HISTORY\FLAG_NO_HISTORY)判断是否需要将其保存到 mLastNoHistoryActivity 中代表不需要将该Activity保存到历史堆栈中 - 将
mResumedActivity 的生命周期设置为 PAUSING 状态 - 构建
PauseActivityItem 对象去执行 Pause 流程 - 根据传入的
pauseImmediately 参数,决定是否立即执行 completePauseLocked() 函数,在当前流程中是会延迟去complete,也就是在当前流程中调用的是 schedulePauseTimeout() 函数 - 在以上流程中,我们重点关注的是第三步和第四步,接下来就逐一分析
1.2.1 PauseActivityItem
-
ClientLifecycleManager.scheduleTransaction()
frameworks\base\services\core\java\com\android\server\am\ClientLifecycleManager.java
void scheduleTransaction(@NonNull IApplicationThread client, @NonNull IBinder activityToken,
@NonNull ActivityLifecycleItem stateRequest) throws RemoteException {
final ClientTransaction clientTransaction = transactionWithState(client, activityToken,
stateRequest);
scheduleTransaction(clientTransaction);
}
void scheduleTransaction(ClientTransaction transaction) throws RemoteException {
final IApplicationThread client = transaction.getClient();
transaction.schedule();
if (!(client instanceof Binder)) {
transaction.recycle();
}
}
- 可以看到在
scheduleTransaction() 函数中,先根据入参构建出了 ClientTransaction 对象;然后调用重载函数,调用到 ClientTransaction.schedule() 函数 -
ClientTransaction.schedule()
frameworks\base\core\java\android\app\servertransaction\ClientTransaction.java
public void schedule() throws RemoteException {
mClient.scheduleTransaction(this);
}
mClient 就是mResumedActivity 对应的ActivityThread 中的内部类 ApplicationThread -
ActivityThread$ApplicationThread.scheduleTransaction()
frameworks\base\core\java\android\app\ActivityThread.java
@Override
public void scheduleTransaction(ClientTransaction transaction) throws RemoteException {
ActivityThread.this.scheduleTransaction(transaction);
}
- 这里就是调用到外部类,也就是
ActivityThread.scheduleTransaction() 函数中,本质是调用到 ActivityThread 的父类 ClientTransactionHandler 中 -
ClientTransactionHandler.scheduleTransaction()
frameworks\base\core\java\android\app\ClientTransactionHandler.java
void scheduleTransaction(ClientTransaction transaction) {
transaction.preExecute(this);
sendMessage(ActivityThread.H.EXECUTE_TRANSACTION, transaction);
}
- 可以看到先去执行了
ClientTransaction.preExecute() 函数,在当前流程中,preExecute() 没有执行任何动作,在此处先不做分析,在后续create\resume 流程中再去细说;再通过Handle,发送 EXECUTE_TRANSACTION 进行下一步处理 -
handleMessage()
frameworks\base\core\java\android\app\ActivityThread.java
public void handleMessage(Message msg) {
...
switch (msg.what) {
...
case EXECUTE_TRANSACTION:
final ClientTransaction transaction = (ClientTransaction) msg.obj;
mTransactionExecutor.execute(transaction);
if (isSystem()) {
transaction.recycle();
}
break;
...
}
...
}
- 在handle中又会借助
TransactionExecutor 对象去触发执行 ClientTransaction -
TransactionExecutor.execute()
frameworks\base\core\java\android\app\servertransaction\TransactionExecutor.java
public void execute(ClientTransaction transaction) {
executeCallbacks(transaction);
executeLifecycleState(transaction);
mPendingActions.clear();
}
- 可以看到在
TransactionExecutor.execute() 中,会先去触发执行 callback 中的流程,而因为当前流程下,没有callback对象,所以跳过callback步骤,直接看 executeLifecycleState() 函数 -
TransactionExecutor.executeLifecycleState()
frameworks\base\core\java\android\app\servertransaction\TransactionExecutor.java
- 在这之前先说明一下
ClientTransaction 中保存的相关成员变量,具体的流程可以自行分析 ClientTransaction 的构建
mClient :mResumedActivity 对应的ActivityThread中的内部类 ApplicationThreadmActivityToken :mResumedActivity 中的 appToken 成员变量mLifecycleStateRequest :构建的 PauseActivityItem 对象 private void executeLifecycleState(ClientTransaction transaction) {
final ActivityLifecycleItem lifecycleItem = transaction.getLifecycleStateRequest();
...
final IBinder token = transaction.getActivityToken();
final ActivityClientRecord r = mTransactionHandler.getActivityClient(token);
...
cycleToPath(r, lifecycleItem.getTargetState(), true );
lifecycleItem.execute(mTransactionHandler, token, mPendingActions);
lifecycleItem.postExecute(mTransactionHandler, token, mPendingActions);
}
- 抛开对应变量的获取,在该函数中就是在去执行
PauseActivityItem.execute() 和 PauseActivityItem.postExecute() ;其中的 cycleToPath() 函数因为当前流程中并没有涉及,我们放到后面 ON_START 流程中进行解析 -
PauseActivityItem.execute()
frameworks\base\core\java\android\app\servertransaction\PauseActivityItem.java
public void execute(ClientTransactionHandler client, IBinder token,
PendingTransactionActions pendingActions) {
Trace.traceBegin(TRACE_TAG_ACTIVITY_MANAGER, "activityPause");
client.handlePauseActivity(token, mFinished, mUserLeaving, mConfigChanges, pendingActions,
"PAUSE_ACTIVITY_ITEM");
Trace.traceEnd(TRACE_TAG_ACTIVITY_MANAGER);
}
- 这里也就又走到了
mResumedActivity 的 ActivityThread 中了 -
ActivityThread.handlePauseActivity()
frameworks\base\core\java\android\app\ActivityThread.java
@Override
public void handlePauseActivity(IBinder token, boolean finished, boolean userLeaving,
int configChanges, PendingTransactionActions pendingActions, String reason) {
ActivityClientRecord r = mActivities.get(token);
if (r != null) {
if (userLeaving) {
performUserLeavingActivity(r);
}
r.activity.mConfigChangeFlags |= configChanges;
performPauseActivity(r, finished, reason, pendingActions);
if (r.isPreHoneycomb()) {
QueuedWork.waitToFinish();
}
mSomeActivitiesChanged = true;
}
}
- 该函数中完成的操作也比较一目了然,顺着流程,调用到
performPauseActivity() -
ActivityThread.performPauseActivity()
frameworks\base\core\java\android\app\ActivityThread.java
private Bundle performPauseActivity(ActivityClientRecord r, boolean finished, String reason,
PendingTransactionActions pendingActions) {
if (r.paused) {
...
}
if (finished) {
r.activity.mFinished = true;
}
...
performPauseActivityIfNeeded(r, reason);
ArrayList<OnActivityPausedListener> listeners;
synchronized (mOnPauseListeners) {
listeners = mOnPauseListeners.remove(r.activity);
}
int size = (listeners != null ? listeners.size() : 0);
for (int i = 0; i < size; i++) {
listeners.get(i).onPaused(r.activity);
}
...
return shouldSaveState ? r.state : null;
}
- 同样继续调用
performPauseActivityIfNeeded() 完成Pause操作 -
ActivityThread.performPauseActivityIfNeeded()
frameworks\base\core\java\android\app\ActivityThread.java
private void performPauseActivityIfNeeded(ActivityClientRecord r, String reason) {
if (r.paused) {
return;
}
try {
r.activity.mCalled = false;
mInstrumentation.callActivityOnPause(r.activity);
if (!r.activity.mCalled) {
throw new SuperNotCalledException("Activity " + safeToComponentShortString(r.intent)
+ " did not call through to super.onPause()");
}
} catch (SuperNotCalledException e) {
throw e;
} catch (Exception e) {
...
}
r.setState(ON_PAUSE);
}
- 接下来就是借助
Instrumentation 再调用到 Activity 中的 onPause() 方法中,后续流程比较简单,就不做展开分析 -
ActivityStack.activityPausedLocked()
frameworks\base\services\core\java\com\android\server\am\ActivityStack.java
- 在前面我们还留了个小尾巴,就是
PauseActivityItem.postExecute() 方法,在该方法中最后会调用到 AMS.activityPaused() 中,然后又会调用到 mResumedActivity 所属的Stack中的 activityPausedLocked() 方法中,接下来再看一下该函数 final void activityPausedLocked(IBinder token, boolean timeout) {
final ActivityRecord r = isInStackLocked(token);
if (r != null) {
mHandler.removeMessages(PAUSE_TIMEOUT_MSG, r);
if (mPausingActivity == r) {
mService.mWindowManager.deferSurfaceLayout();
try {
completePauseLocked(true , null );
} finally {
mService.mWindowManager.continueSurfaceLayout();
}
return;
} else {
if (r.isState(PAUSING)) {
r.setState(PAUSED, "activityPausedLocked");
if (r.finishing) {
finishCurrentActivityLocked(r, FINISH_AFTER_VISIBLE, false,
"activityPausedLocked");
}
}
}
}
mStackSupervisor.ensureActivitiesVisibleLocked(null, 0, !PRESERVE_WINDOWS);
}
- 在该函数中,首先会判断能够根据传入的
ActivityRecord.appToken 在对应的 stack 和 Task 中获取到对应的 ActivityRecord 对象,在可以获取到并且系统中的 mPausingActivity 就是当前获取到的 ActivityRecord 时,会接着去调用 completePauseLocked() 去完成 Pause 操作,并且根据此处传参 resumeNext = true ,还会去 Resume 对应 stack 最顶部的Activity -
ActivityStack.completePauseLocked()
frameworks\base\services\core\java\com\android\server\am\ActivityStack.java
private void completePauseLocked(boolean resumeNext, ActivityRecord resuming) {
ActivityRecord prev = mPausingActivity;
if (DEBUG_PAUSE)
Slog.v(TAG_PAUSE, "Complete pause: " + prev);
if (prev != null) {
prev.setWillCloseOrEnterPip(false);
final boolean wasStopping = prev.isState(STOPPING);
prev.setState(PAUSED, "completePausedLocked");
if (prev.finishing) {
if (DEBUG_PAUSE)
Slog.v(TAG_PAUSE, "Executing finish of activity: " + prev);
prev = finishCurrentActivityLocked(prev, FINISH_AFTER_VISIBLE, false,
"completedPausedLocked");
} else if (prev.app != null) {
if (DEBUG_PAUSE)
Slog.v(TAG_PAUSE, "Enqueue pending stop if needed: " + prev
+ " wasStopping=" + wasStopping + " visible=" + prev.visible);
if (mStackSupervisor.mActivitiesWaitingForVisibleActivity.remove(prev)) {
if (DEBUG_SWITCH || DEBUG_PAUSE)
Slog.v(TAG_PAUSE,
"Complete pause, no longer waiting: " + prev);
}
if (prev.deferRelaunchUntilPaused) {
prev.relaunchActivityLocked(false ,
prev.preserveWindowOnDeferredRelaunch);
} else if (wasStopping) {
prev.setState(STOPPING, "completePausedLocked");
} else if (!prev.visible || shouldSleepOrShutDownActivities()) {
prev.setDeferHidingClient(false);
addToStopping(prev, true , false );
}
} else {
prev = null;
}
...
mPausingActivity = null;
}
if (resumeNext) {
final ActivityStack topStack = mStackSupervisor.getFocusedStack();
if (!topStack.shouldSleepOrShutDownActivities()) {
mStackSupervisor.resumeFocusedStackTopActivityLocked(topStack, prev, null);
} else {
checkReadyForSleep();
ActivityRecord top = topStack.topRunningActivityLocked();
if (top == null || (prev != null && top != prev)) {
mStackSupervisor.resumeFocusedStackTopActivityLocked();
}
}
}
if (prev != null) {
...
}
if (mStackSupervisor.mAppVisibilitiesChangedSinceLastPause
|| getDisplay().hasPinnedStack()) {
mService.mTaskChangeNotificationController.notifyTaskStackChanged();
mStackSupervisor.mAppVisibilitiesChangedSinceLastPause = false;
}
mStackSupervisor.ensureActivitiesVisibleLocked(resuming, 0, !PRESERVE_WINDOWS);
}
- 在该函数中,就会去将
mPausingActivity 的生命周期设置为 PAUSED,并且将 mPausingActivity 置空,代表 Pause 完成,然后根据传入的 resumeNext 参数决定是否需要在此处触发 resume Activity 的动作,最后会去校正 系统中Activity的可见性
- 至此
PauseActivityItem 对象下的 Pause 流程就全部梳理完毕了
1.2.2 schedulePauseTimeout()
-
schedulePauseTimeout() 流程较为简单,其实就是通过 Handle 延迟500ms后再去调用 activityPausedLocked() ,之后和上面的流程基本相同,此处就不展开分析了 -
从目前来看,此时的 mPausingActivity.visible 还是等于 true 的 -
ActivityStack.resumeTopActivityInnerLocked() 中的 startPausingLocked() 中调用 onPaused()
-
mService.getLifecycleManager().scheduleTransaction(prev.app.thread, prev.appToken, PauseActivityItem.obtain(prev.finishing, userLeaving, prev.configChangeFlags, pauseImmediately)); -
PauseActivityItem.execute()
client.handlePauseActivity(token, mFinished, mUserLeaving, mConfigChanges, pendingActions, "PAUSE_ACTIVITY_ITEM");
-
这个client就是 scheduleTransaction(prev.app.thread…)中的 prev.app.thread 也就是prev的线程中去调用的 -
token 就是 prev.appToken -
mFinished 就是 prev.finishing -
mUserLeaving 就是 userLeaving -
mConfigChanges 就是 prev.configChangeFlags
performPauseActivity()
performPauseActivityIfNeeded()
mInstrumentation.callActivityOnPause()
② oncreate
- 根据上篇文章的分析,可以知道
onCreate() 流程的起点是在 realStartActivityLocked() 中进入的,我们就从该函数关键代码处开始解析
2.1 realStartActivityLocked()
frameworks\base\services\core\java\com\android\server\am\ActivityStackSupervisor.java
final boolean realStartActivityLocked(ActivityRecord r, ProcessRecord app,
boolean andResume, boolean checkConfig) throws RemoteException {
...
final ClientTransaction clientTransaction = ClientTransaction.obtain(app.thread,
r.appToken);
clientTransaction.addCallback(LaunchActivityItem.obtain(new Intent(r.intent),
System.identityHashCode(r), r.info,
mergedConfiguration.getGlobalConfiguration(),
mergedConfiguration.getOverrideConfiguration(), r.compat,
r.launchedFromPackage, task.voiceInteractor, app.repProcState, r.icicle,
r.persistentState, results, newIntents, mService.isNextTransitionForward(),
profilerInfo));
final ActivityLifecycleItem lifecycleItem;
if (andResume) {
lifecycleItem = ResumeActivityItem.obtain(mService.isNextTransitionForward());
} else {
lifecycleItem = PauseActivityItem.obtain();
}
clientTransaction.setLifecycleStateRequest(lifecycleItem);
mService.getLifecycleManager().scheduleTransaction(clientTransaction);
...
}
- 排除掉与当前主题无关的代码,可以看到在该函数中,同样构建了
clientTransaction 对象 和 LaunchActivityItem 对象,不过和 [onPause](① onPause) 流程不同的是 在当前流程中,LaunchActivityItem 对象是作为 callback 被添加到 clientTransaction 对象中,最后同样调用 scheduleTransaction() 触发,这部分流程和上面并无差异,也不再详细解析,直接看最后的执行流程
2.2 TransactionExecutor.executeCallbacks()
frameworks\base\core\java\android\app\servertransaction\TransactionExecutor.java
@VisibleForTesting
public void executeCallbacks(ClientTransaction transaction) {
final List<ClientTransactionItem> callbacks = transaction.getCallbacks();
if (callbacks == null) {
return;
}
log("Resolving callbacks");
final IBinder token = transaction.getActivityToken();
ActivityClientRecord r = mTransactionHandler.getActivityClient(token);
...
final int size = callbacks.size();
for (int i = 0; i < size; ++i) {
...
item.execute(mTransactionHandler, token, mPendingActions);
item.postExecute(mTransactionHandler, token, mPendingActions);
...
}
}
- 其实和上面的流程很类似,同样是调用到
callback.execute() 和 callback.postExecute() ,而当前流程下就是调用 LaunchActivityItem.execute() 和 LaunchActivityItem.postExecute() ,而针对 LaunchActivityItem 对象来说, postExecute() 函数是未实现的,所以无需关心,只关注 execute() 函数即可
2.3 LaunchActivityItem.execute()
frameworks\base\core\java\android\app\servertransaction\LaunchActivityItem.java
@Override
public void execute(ClientTransactionHandler client, IBinder token,
PendingTransactionActions pendingActions) {
Trace.traceBegin(TRACE_TAG_ACTIVITY_MANAGER, "activityStart");
ActivityClientRecord r = new ActivityClientRecord(token, mIntent, mIdent, mInfo,
mOverrideConfig, mCompatInfo, mReferrer, mVoiceInteractor, mState, mPersistentState,
mPendingResults, mPendingNewIntents, mIsForward,
mProfilerInfo, client);
client.handleLaunchActivity(r, pendingActions, null );
Trace.traceEnd(TRACE_TAG_ACTIVITY_MANAGER);
}
- 可以看到,针对经历完整生命周期启动的Activity,其对应的
ActivityClientRecord 对象是在 LaunchActivityItem 对象中进行创建的,后续继续调用其 ActivityThread.handleLaunchActivity() 函数去继续启动
2.4 ActivityThread.handleLaunchActivity()
frameworks\base\core\java\android\app\ActivityThread.java
@Override
public Activity handleLaunchActivity(ActivityClientRecord r,
PendingTransactionActions pendingActions, Intent customIntent) {
unscheduleGcIdler();
mSomeActivitiesChanged = true;
if (r.profilerInfo != null) {
mProfiler.setProfiler(r.profilerInfo);
mProfiler.startProfiling();
}
handleConfigurationChanged(null, null);
if (!ThreadedRenderer.sRendererDisabled) {
GraphicsEnvironment.earlyInitEGL();
}
WindowManagerGlobal.initialize();
final Activity a = performLaunchActivity(r, customIntent);
if (a != null) {
r.createdConfig = new Configuration(mConfiguration);
reportSizeConfigurations(r);
if (!r.activity.mFinished && pendingActions != null) {
pendingActions.setOldState(r.state);
pendingActions.setRestoreInstanceState(true);
pendingActions.setCallOnPostCreate(true);
}
} else {
try {
ActivityManager.getService()
.finishActivity(r.token, Activity.RESULT_CANCELED, null,
Activity.DONT_FINISH_TASK_WITH_ACTIVITY);
} catch (RemoteException ex) {
throw ex.rethrowFromSystemServer();
}
}
return a;
}
- 在该函数中,会进行新启动Activity的一些初始环境准备,然后就会调用
performLaunchActivity() 函数根据传入的 ActivityClientRecord 对象去构建出 Activity 对象
2.5 ActivityThread.performLaunchActivity()
frameworks\base\core\java\android\app\ActivityThread.java
private Activity performLaunchActivity(ActivityClientRecord r, Intent customIntent) {
ActivityInfo aInfo = r.activityInfo;
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);
}
if (r.activityInfo.targetActivity != null) {
component = new ComponentName(r.activityInfo.packageName,
r.activityInfo.targetActivity);
}
ContextImpl appContext = createBaseContextForActivity(r);
Activity activity = null;
try {
java.lang.ClassLoader cl = appContext.getClassLoader();
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 app = r.packageInfo.makeApplication(false, mInstrumentation);
if (activity != null) {
CharSequence title = r.activityInfo.loadLabel(appContext.getPackageManager());
Configuration config = new Configuration(mCompatConfiguration);
if (r.overrideConfig != null) {
config.updateFrom(r.overrideConfig);
}
if (DEBUG_CONFIGURATION) Slog.v(TAG, "Launching activity "
+ r.activityInfo.name + " with config " + config);
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 (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;
if (r.isPersistable()) {
mInstrumentation.callActivityOnCreate(activity, r.state, r.persistentState);
} else {
mInstrumentation.callActivityOnCreate(activity, r.state);
}
if (!activity.mCalled) {
throw new SuperNotCalledException(
"Activity " + r.intent.getComponent().toShortString() +
" did not call through to super.onCreate()");
}
r.activity = activity;
}
r.setState(ON_CREATE);
mActivities.put(r.token, r);
} catch (SuperNotCalledException e) {
throw e;
} catch (Exception e) {
...
}
return activity;
}
③ onstart
- onStart流程作为一个中间过渡状态,并不如 上面几个流程一样,有对应的
ActivityLifecycleItem 对象进行触发,他是在执行完 onCreate() 之后,嵌入在 TransactionExecutor.execute() 函数中的,接下来让我们继续解析
3.1 TransactionExecutor.execute()
frameworks\base\core\java\android\app\servertransaction\TransactionExecutor.java
public void execute(ClientTransaction transaction) {
final IBinder token = transaction.getActivityToken();
log("Start resolving transaction for client: " + mTransactionHandler + ", token: " + token);
executeCallbacks(transaction);
executeLifecycleState(transaction);
mPendingActions.clear();
log("End resolving transaction");
}
- 通过上面的分析,我们知道在
executeCallbacks() 函数中完成了 onCreate() 流程,接下来就是 executeLifecycleState() 函数
3.2 TransactionExecutor.executeLifecycleState()
frameworks\base\core\java\android\app\servertransaction\TransactionExecutor.java
private void executeLifecycleState(ClientTransaction transaction) {
final ActivityLifecycleItem lifecycleItem = transaction.getLifecycleStateRequest();
if (lifecycleItem == null) {
return;
}
final IBinder token = transaction.getActivityToken();
final ActivityClientRecord r = mTransactionHandler.getActivityClient(token);
if (r == null) {
return;
}
cycleToPath(r, lifecycleItem.getTargetState(), true );
lifecycleItem.execute(mTransactionHandler, token, mPendingActions);
lifecycleItem.postExecute(mTransactionHandler, token, mPendingActions);
}
- 在该函数中,会先去获取
ClientTransaction 对象中的 ActivityLifecycleItem 对象,而该对象,根据 onCreate 流程中的分析,我们可以知道就是 ResumeActivityItem 对象,那么接下去就是去执行 cycleToPath() 函数
3.3 TransactionExecutor.cycleToPath()
frameworks\base\core\java\android\app\servertransaction\TransactionExecutor.java
private void cycleToPath(ActivityClientRecord r, int finish,
boolean excludeLastState) {
final int start = r.getLifecycleState();
log("Cycle from: " + start + " to: " + finish + " excludeLastState:" + excludeLastState);
final IntArray path = mHelper.getLifecyclePath(start, finish, excludeLastState);
performLifecycleSequence(r, path);
}
- 该函数中会去拿当前还需要执行的中间状态,该函数也比较简单
frameworks\base\core\java\android\app\servertransaction\TransactionExecutorHelper.java
@VisibleForTesting
public IntArray getLifecyclePath(int start, int finish, boolean excludeLastState) {
if (start == UNDEFINED || finish == UNDEFINED) {
throw new IllegalArgumentException("Can't resolve lifecycle path for undefined state");
}
if (start == ON_RESTART || finish == ON_RESTART) {
throw new IllegalArgumentException(
"Can't start or finish in intermittent RESTART state");
}
if (finish == PRE_ON_CREATE && start != finish) {
throw new IllegalArgumentException("Can only start in pre-onCreate state");
}
mLifecycleSequence.clear();
if (finish >= start) {
for (int i = start + 1; i <= finish; i++) {
mLifecycleSequence.add(i);
}
} else {
if (start == ON_PAUSE && finish == ON_RESUME) {
mLifecycleSequence.add(ON_RESUME);
} else if (start <= ON_STOP && finish >= ON_START) {
for (int i = start + 1; i <= ON_STOP; i++) {
mLifecycleSequence.add(i);
}
mLifecycleSequence.add(ON_RESTART);
for (int i = ON_START; i <= finish; i++) {
mLifecycleSequence.add(i);
}
} else {
for (int i = start + 1; i <= ON_DESTROY; i++) {
mLifecycleSequence.add(i);
}
for (int i = ON_CREATE; i <= finish; i++) {
mLifecycleSequence.add(i);
}
}
}
if (excludeLastState && mLifecycleSequence.size() != 0) {
mLifecycleSequence.remove(mLifecycleSequence.size() - 1);
}
return mLifecycleSequence;
}
? 其实就是根据Activity当前的状态和最终的状态进行判断,取出两者之间的中间状态,记录到 mLifecycleSequence 返回
3.4 TransactionExecutor.performLifecycleSequence()
frameworks\base\core\java\android\app\servertransaction\TransactionExecutorHelper.java
private void performLifecycleSequence(ActivityClientRecord r, IntArray path) {
final int size = path.size();
for (int i = 0, state; i < size; i++) {
state = path.get(i);
log("Transitioning to state: " + state);
switch (state) {
...
case ON_START:
mTransactionHandler.handleStartActivity(r, mPendingActions);
break;
...
}
}
}
- 根据上一步拿到的中间状态,匹配对应的流程,当前流程下只有一个
ON_START 状态,所以最后就是去执行正启动Activity的 ActivityThread.handleStartActivity() 函数
3.5 ActivityThread.handleStartActivity()
frameworks\base\core\java\android\app\ActivityThread.java
@Override
public void handleStartActivity(ActivityClientRecord r,
PendingTransactionActions pendingActions) {
final Activity activity = r.activity;
if (r.activity == null) {
return;
}
if (!r.stopped) {
throw new IllegalStateException("Can't start activity that is not stopped.");
}
if (r.activity.mFinished) {
return;
}
activity.performStart("handleStartActivity");
r.setState(ON_START);
...
}
- 后面的流程就相对比较简单,调用链就是:
Activity.performStart() --> mInstrumentation.callActivityOnStart() --> activity.onStart() ,这些流程也不再赘述了
④ onresume
- 继续顺着流程往下梳理,我们已经完成了中间状态
onStart() ,接下来就是该走到正在启动Activity的最终状态,也就是 TransactionExecutor.executeLifecycleState() 中的 lifecycleItem.execute() 和 lifecycleItem.postExecute() ,在当前流程下,就是 ResumeActivityItem.execute() 和 ResumeActivityItem.postExecute() ,该段代码可见 [onstart](3.2 TransactionExecutor.executeLifecycleState() ) 中的解析
4.1.1 ResumeActivityItem.execute()
frameworks\base\core\java\android\app\servertransaction\ResumeActivityItem.java
@Override
public void execute(ClientTransactionHandler client, IBinder token,
PendingTransactionActions pendingActions) {
Trace.traceBegin(TRACE_TAG_ACTIVITY_MANAGER, "activityResume");
client.handleResumeActivity(token, true , mIsForward,
"RESUME_ACTIVITY");
Trace.traceEnd(TRACE_TAG_ACTIVITY_MANAGER);
}
- 调用流程都类似,也是走到了正在启动的Activity的ActivityThread中去
4.1.2 ActivityThread.handleResumeActivity()
1
@Override
public void handleResumeActivity(IBinder token, boolean finalStateRequest, boolean isForward,
String reason) {
unscheduleGcIdler();
mSomeActivitiesChanged = true;
final ActivityClientRecord r = performResumeActivity(token, finalStateRequest, reason);
...
}
- 移除与当前流程无关的代码,我们可以看到其实很相似的,调用链是:
ActivityThread.handleResumeActivity() --> ActivityThread.performResumeActivity() --> Activity.performResume() --> Instrumetation.callActivityOnResume() --> Activity.onResume() 后续流程也比较简单,就不做展开分析了
4.2.1 ResumeActivityItem.postExecute()
frameworks\base\core\java\android\app\servertransaction\ResumeActivityItem.java
@Override
public void postExecute(ClientTransactionHandler client, IBinder token,
PendingTransactionActions pendingActions) {
try {
ActivityManager.getService().activityResumed(token);
} catch (RemoteException ex) {
throw ex.rethrowFromSystemServer();
}
}
4.2.2 ActivityManagerService.activityResumed()
frameworks\base\services\core\java\com\android\server\am\ActivityManagerService.java
@Override
public final void activityResumed(IBinder token) {
final long origId = Binder.clearCallingIdentity();
synchronized(this) {
ActivityRecord.activityResumedLocked(token);
mWindowManager.notifyAppResumedFinished(token);
}
Binder.restoreCallingIdentity(origId);
}
⑤ onstop
- 接下来让我们分析一下 onStop 流程,onStop 的流程入口是在 onResume 之后,具体是在
ActivityThread.handleResumeActivity() 函数中
5.1 ActivityThread.handleResumeActivity()
frameworks\base\core\java\android\app\ActivityThread.java
@Override
public void handleResumeActivity(IBinder token, boolean finalStateRequest, boolean isForward,
String reason) {
...
r.nextIdle = mNewActivities;
mNewActivities = r;
if (localLOGV) Slog.v(TAG, "Scheduling idle handler for " + r);
Looper.myQueue().addIdleHandler(new Idler());
}
public void addIdleHandler(@NonNull IdleHandler handler) {
if (handler == null) {
throw new NullPointerException("Can't add a null IdleHandler");
}
synchronized (this) {
mIdleHandlers.add(handler);
}
}
- 可以看到是将 Idler 对象添加到了
MessageQueue.mIdleHandlers 中,而在当前ActivityThread正式开始运行后,会在looper中进行message的处理
5.2 MessageQueue.next()
frameworks\base\core\java\android\os\MessageQueue.java
Message next() {
...
for (;;) {
if (nextPollTimeoutMillis != 0) {
Binder.flushPendingCommands();
}
nativePollOnce(ptr, nextPollTimeoutMillis);
...
if (pendingIdleHandlerCount < 0
&& (mMessages == null || now < mMessages.when)) {
pendingIdleHandlerCount = mIdleHandlers.size();
}
if (pendingIdleHandlerCount <= 0) {
mBlocked = true;
continue;
}
if (mPendingIdleHandlers == null) {
mPendingIdleHandlers = new IdleHandler[Math.max(pendingIdleHandlerCount, 4)];
}
mPendingIdleHandlers = mIdleHandlers.toArray(mPendingIdleHandlers);
}
for (int i = 0; i < pendingIdleHandlerCount; i++) {
final IdleHandler idler = mPendingIdleHandlers[i];
mPendingIdleHandlers[i] = null;
boolean keep = false;
try {
keep = idler.queueIdle();
} catch (Throwable t) {
Log.wtf(TAG, "IdleHandler threw exception", t);
}
if (!keep) {
synchronized (this) {
mIdleHandlers.remove(idler);
}
}
}
pendingIdleHandlerCount = 0;
...
}
}
- 可以看到,当 MessageQueue中没有待处理消息后,会去尝试获取
mIdleHandlers 中的对象,进行处理,而此时很显然 mIdleHandlers 中是存在数据的,即会调用到 idler.queueIdle() 函数
5.3 Idler.queueIdle()
frameworks\base\core\java\android\app\ActivityThread.java
public final boolean queueIdle() {
ActivityClientRecord a = mNewActivities;
boolean stopProfiling = false;
if (mBoundApplication != null && mProfiler.profileFd != null
&& mProfiler.autoStopProfiler) {
stopProfiling = true;
}
if (a != null) {
mNewActivities = null;
IActivityManager am = ActivityManager.getService();
ActivityClientRecord prev;
do {
if (localLOGV) Slog.v(
TAG, "Reporting idle of " + a +
" finished=" +
(a.activity != null && a.activity.mFinished));
if (a.activity != null && !a.activity.mFinished) {
try {
am.activityIdle(a.token, a.createdConfig, stopProfiling);
a.createdConfig = null;
} catch (RemoteException ex) {
throw ex.rethrowFromSystemServer();
}
}
prev = a;
a = a.nextIdle;
prev.nextIdle = null;
} while (a != null);
}
if (stopProfiling) {
mProfiler.stopProfiling();
}
ensureJitEnabled();
return false;
}
- 在该函数中,就会去遍历取出存入的需要处理的Activity,借助 AMS进行处理
5.4 ActivityManagerService.activityIdle()
frameworks\base\services\core\java\com\android\server\am\ActivityManagerService.java
@Override
public final void activityIdle(IBinder token, Configuration config, boolean stopProfiling) {
final long origId = Binder.clearCallingIdentity();
synchronized (this) {
ActivityStack stack = ActivityRecord.getStackLocked(token);
if (stack != null) {
ActivityRecord r =
mStackSupervisor.activityIdleInternalLocked(token, false ,
false , config);
if (stopProfiling) {
if ((mProfileProc == r.app) && mProfilerInfo != null) {
clearProfilerLocked();
}
}
}
}
Binder.restoreCallingIdentity(origId);
}
- 继续调用
activityIdleInternalLocked() 进行处理
5.5 ActivityStackSupervisor.activityIdleInternalLocked()
frameworks\base\services\core\java\com\android\server\am\ActivityStackSupervisor.java
@GuardedBy("mService")
final ActivityRecord activityIdleInternalLocked(final IBinder token, boolean fromTimeout,
boolean processPausingActivities, Configuration config) {
if (DEBUG_ALL) Slog.v(TAG, "Activity idle: " + token);
ArrayList<ActivityRecord> finishes = null;
ArrayList<UserState> startingUsers = null;
int NS = 0;
int NF = 0;
boolean booting = false;
boolean activityRemoved = false;
ActivityRecord r = ActivityRecord.forTokenLocked(token);
if (r != null) {
if (DEBUG_IDLE) Slog.d(TAG_IDLE, "activityIdleInternalLocked: Callers="
+ Debug.getCallers(4));
mHandler.removeMessages(IDLE_TIMEOUT_MSG, r);
r.finishLaunchTickingLocked();
if (fromTimeout) {
reportActivityLaunchedLocked(fromTimeout, r, -1, -1);
}
if (config != null) {
r.setLastReportedGlobalConfiguration(config);
}
r.idle = true;
if (isFocusedStack(r.getStack()) || fromTimeout) {
booting = checkFinishBootingLocked();
}
}
if (allResumedActivitiesIdle()) {
if (r != null) {
mService.scheduleAppGcsLocked();
}
if (mLaunchingActivity.isHeld()) {
mHandler.removeMessages(LAUNCH_TIMEOUT_MSG);
if (VALIDATE_WAKE_LOCK_CALLER &&
Binder.getCallingUid() != Process.myUid()) {
throw new IllegalStateException("Calling must be system uid");
}
mLaunchingActivity.release();
}
ensureActivitiesVisibleLocked(null, 0, !PRESERVE_WINDOWS);
}
final ArrayList<ActivityRecord> stops = processStoppingActivitiesLocked(r,
true , processPausingActivities);
NS = stops != null ? stops.size() : 0;
if ((NF = mFinishingActivities.size()) > 0) {
finishes = new ArrayList<>(mFinishingActivities);
mFinishingActivities.clear();
}
if (mStartingUsers.size() > 0) {
startingUsers = new ArrayList<>(mStartingUsers);
mStartingUsers.clear();
}
for (int i = 0; i < NS; i++) {
r = stops.get(i);
final ActivityStack stack = r.getStack();
if (stack != null) {
if (r.finishing) {
stack.finishCurrentActivityLocked(r, ActivityStack.FINISH_IMMEDIATELY, false,
"activityIdleInternalLocked");
} else {
stack.stopActivityLocked(r);
}
}
}
for (int i = 0; i < NF; i++) {
r = finishes.get(i);
final ActivityStack stack = r.getStack();
if (stack != null) {
activityRemoved |= stack.destroyActivityLocked(r, true, "finish-idle");
}
}
if (!booting) {
if (startingUsers != null) {
for (int i = 0; i < startingUsers.size(); i++) {
mService.mUserController.finishUserSwitch(startingUsers.get(i));
}
}
}
mService.trimApplications();
if (activityRemoved) {
resumeFocusedStackTopActivityLocked();
}
return r;
}
5.5.1 ActivityStackSupervisor.processStoppingActivitiesLocked()
frameworks\base\services\core\java\com\android\server\am\ActivityStackSupervisor.java
final ArrayList<ActivityRecord> processStoppingActivitiesLocked(ActivityRecord idleActivity,
boolean remove, boolean processPausingActivities) {
ArrayList<ActivityRecord> stops = null;
final boolean nowVisible = allResumedActivitiesVisible();
for (int activityNdx = mStoppingActivities.size() - 1; activityNdx >= 0; --activityNdx) {
ActivityRecord s = mStoppingActivities.get(activityNdx);
boolean waitingVisible = mActivitiesWaitingForVisibleActivity.contains(s);
if (DEBUG_STATES) Slog.v(TAG, "Stopping " + s + ": nowVisible=" + nowVisible
+ " waitingVisible=" + waitingVisible + " finishing=" + s.finishing);
if (waitingVisible && nowVisible) {
mActivitiesWaitingForVisibleActivity.remove(s);
waitingVisible = false;
if (s.finishing) {
if (DEBUG_STATES) Slog.v(TAG, "Before stopping, can hide: " + s);
s.setVisibility(false);
}
}
if (remove) {
final ActivityStack stack = s.getStack();
final boolean shouldSleepOrShutDown = stack != null
? stack.shouldSleepOrShutDownActivities()
: mService.isSleepingOrShuttingDownLocked();
if (!waitingVisible || shouldSleepOrShutDown) {
if (!processPausingActivities && s.isState(PAUSING)) {
removeTimeoutsForActivityLocked(idleActivity);
scheduleIdleTimeoutLocked(idleActivity);
continue;
}
if (DEBUG_STATES) Slog.v(TAG, "Ready to stop: " + s);
if (stops == null) {
stops = new ArrayList<>();
}
stops.add(s);
mActivitiesWaitingForVisibleActivity.remove(s);
mStoppingActivities.remove(activityNdx);
}
}
}
return stops;
}
-
可以看到,该函数中其中就是对 mStoppingActivities 列表中的Activity对象做了二次判断,符合要求的才会添加到返回列表中进行后续操作,那么 mStoppingActivities 列表又是在何处进行添加的呢?回头查阅 [Pause](① onPause) 流程可以看到在 completePauseLocked() 函数中,有这么一段: private void completePauseLocked(boolean resumeNext, ActivityRecord resuming) {
ActivityRecord prev = mPausingActivity;
if (DEBUG_PAUSE)
Slog.v(TAG_PAUSE, "Complete pause: " + prev);
if (prev != null) {
...
if (prev.finishing) {
...
} else if (prev.app != null) {
...
if (prev.deferRelaunchUntilPaused) {
...
} else if (wasStopping) {
...
} else if (!prev.visible || shouldSleepOrShutDownActivities()) {
prev.setDeferHidingClient(false);
addToStopping(prev, true , false );
}
}
...
}
...
}
可以看到,当prev.visible 为 false的时候,即prev不可见的时候,会将其添加到 mStoppingActivities 列表中
5.5.2 ActivityStack.stopActivityLocked()
frameworks\base\services\core\java\com\android\server\am\ActivityStack.java
final void stopActivityLocked(ActivityRecord r) {
...
if (r.app != null && r.app.thread != null) {
adjustFocusedActivityStack(r, "stopActivity");
r.resumeKeyDispatchingLocked();
try {
r.stopped = false;
if (DEBUG_STATES)
Slog.v(TAG_STATES,
"Moving to STOPPING: " + r + " (stop requested)");
r.setState(STOPPING, "stopActivityLocked");
if (DEBUG_VISIBILITY)
Slog.v(TAG_VISIBILITY,
"Stopping visible=" + r.visible + " for " + r);
if (!r.visible) {
r.setVisible(false);
}
EventLogTags.writeAmStopActivity(
r.userId, System.identityHashCode(r), r.shortComponentName);
mService.getLifecycleManager().scheduleTransaction(r.app.thread, r.appToken,
StopActivityItem.obtain(r.visible, r.configChangeFlags));
if (shouldSleepOrShutDownActivities()) {
r.setSleeping(true);
}
Message msg = mHandler.obtainMessage(STOP_TIMEOUT_MSG, r);
mHandler.sendMessageDelayed(msg, STOP_TIMEOUT);
} catch (Exception e) {
...
}
}
}
- 在该函数中就会去构建出
StopActivityItem 对象,并触发执行,并且延迟 STOP_TIMEOUT 时间后发送 STOP_TIMEOUT_MSG 消息触发 ActivityRecordactivityStoppedLocked() 函数的执行 - 在
StopActivityItem 对象中,和之前几个生命周期中执行相似,流程就是 : ActivityThread.handleStopActivity() --> ActivityThread.performStopActivityInner() -(ActivityRecord.visible == false )-> ActivityThread.callActivityOnStop() --> Activity.performStop() --> Instrumentation.callActivityOnStop() --> Activity.onStop()
疑问:
-
梳理完这五个生命周期,可以发现,只有在 ActivityRecord.visible 值为false,即Activity不可见的时候,才会进行 stop,那么这个visible的值究竟是在何处进行变化的呢?
- 其实在解析整体流程时,我们能反复看到
ensureActivitiesVisibleLocked() 函数,从函数名称其实也可以看得出来,该函数中会进行Activity可见性的判断,那么接下来我们深入解析一下该函数,直接看 ActivityStack.ensureActivitiesVisibleLocked() 函数 -
ActivityStack.ensureActivitiesVisibleLocked()
frameworks\base\services\core\java\com\android\server\am\ActivityStack.java
final void ensureActivitiesVisibleLocked(ActivityRecord starting, int configChanges,
boolean preserveWindows, boolean notifyClients) {
...
try {
ActivityRecord top = topRunningActivityLocked();
...
boolean aboveTop = top != null;
final boolean stackShouldBeVisible = shouldBeVisible(starting);
boolean behindFullscreenActivity = !stackShouldBeVisible;
boolean resumeNextActivity = mStackSupervisor.isFocusedStack(this)
&& (isInStackLocked(starting) == null);
final boolean isTopNotPinnedStack = isAttached() && getDisplay().isTopNotPinnedStack(this);
for (int taskNdx = mTaskHistory.size() - 1; taskNdx >= 0; --taskNdx) {
final TaskRecord task = mTaskHistory.get(taskNdx);
final ArrayList<ActivityRecord> activities = task.mActivities;
for (int activityNdx = activities.size() - 1; activityNdx >= 0; --activityNdx) {
final ActivityRecord r = activities.get(activityNdx);
if (r.finishing) {
continue;
}
final boolean isTop = r == top;
if (aboveTop && !isTop) {
continue;
}
aboveTop = false;
final boolean visibleIgnoringKeyguard = r.shouldBeVisibleIgnoringKeyguard(
behindFullscreenActivity);
r.visibleIgnoringKeyguard = visibleIgnoringKeyguard;
final boolean reallyVisible = checkKeyguardVisibility(r,
visibleIgnoringKeyguard, isTop && isTopNotPinnedStack);
if (visibleIgnoringKeyguard) {
behindFullscreenActivity = updateBehindFullscreen(!stackShouldBeVisible,
behindFullscreenActivity, r);
}
if (reallyVisible) {
...
} else {
makeInvisible(r);
}
}
...
}
...
}
...
}
-
ActivityStack.shouldBeVisible()
boolean shouldBeVisible(ActivityRecord starting) {
if (!isAttached() || mForceHidden) {
return false;
}
if (mStackSupervisor.isFocusedStack(this)) {
return true;
}
final ActivityRecord top = topRunningActivityLocked();
if (top == null && isInStackLocked(starting) == null && !isTopStackOnDisplay()) {
return false;
}
final ActivityDisplay display = getDisplay();
boolean gotSplitScreenStack = false;
boolean gotOpaqueSplitScreenPrimary = false;
boolean gotOpaqueSplitScreenSecondary = false;
final int windowingMode = getWindowingMode();
final boolean isAssistantType = isActivityTypeAssistant();
for (int i = display.getChildCount() - 1; i >= 0; --i) {
final ActivityStack other = display.getChildAt(i);
if (other == this) {
return true;
}
final int otherWindowingMode = other.getWindowingMode();
if (otherWindowingMode == WINDOWING_MODE_FULLSCREEN) {
final int activityType = other.getActivityType();
if (windowingMode == WINDOWING_MODE_SPLIT_SCREEN_PRIMARY) {
if (activityType == ACTIVITY_TYPE_HOME
|| (activityType == ACTIVITY_TYPE_ASSISTANT
&& mWindowManager.getRecentsAnimationController() != null)) {
return true;
}
}
if (other.isStackTranslucent(starting)) {
continue;
}
return false;
} else if (otherWindowingMode == WINDOWING_MODE_SPLIT_SCREEN_PRIMARY
&& !gotOpaqueSplitScreenPrimary) {
gotSplitScreenStack = true;
gotOpaqueSplitScreenPrimary = !other.isStackTranslucent(starting);
if (windowingMode == WINDOWING_MODE_SPLIT_SCREEN_PRIMARY
&& gotOpaqueSplitScreenPrimary) {
return false;
}
} else if (otherWindowingMode == WINDOWING_MODE_SPLIT_SCREEN_SECONDARY
&& !gotOpaqueSplitScreenSecondary) {
gotSplitScreenStack = true;
gotOpaqueSplitScreenSecondary = !other.isStackTranslucent(starting);
if (windowingMode == WINDOWING_MODE_SPLIT_SCREEN_SECONDARY
&& gotOpaqueSplitScreenSecondary) {
return false;
}
}
if (gotOpaqueSplitScreenPrimary && gotOpaqueSplitScreenSecondary) {
return false;
}
if (isAssistantType && gotSplitScreenStack) {
return false;
}
}
return true;
}
- 首先判断当前stack是否是可见,根据我们假设的前提,当前stack就是
mFocusedStack ,此处判断出来是可见的,即当前 stackShouldBeVisible = true ,而 behindFullscreenActivity = false -
ActivityRecord.shouldBeVisibleIgnoringKeyguard(false) boolean shouldBeVisibleIgnoringKeyguard(boolean behindFullscreenActivity) {
if (!okToShowLocked()) {
return false;
}
return !behindFullscreenActivity || mLaunchTaskBehind;
}
- 可以看到,在
shouldBeVisibleIgnoringKeyguard() 中,确保Activity可展示的前提下,会根据 传入的 behindFullscreenActivity 或者 mLaunchTaskBehind 来确定是否可见,而我们当下传入的 behindFullscreenActivity = false ,所以此时肯定返回的是true,即 visibleIgnoringKeyguard = true -
ActivityStack.checkKeyguardVisibility(r, true, true)
boolean checkKeyguardVisibility(ActivityRecord r, boolean shouldBeVisible, boolean isTop) {
final int displayId = mDisplayId != INVALID_DISPLAY ? mDisplayId : DEFAULT_DISPLAY;
final boolean keyguardOrAodShowing = mStackSupervisor.getKeyguardController()
.isKeyguardOrAodShowing(displayId);
final boolean keyguardLocked = mStackSupervisor.getKeyguardController().isKeyguardLocked();
final boolean showWhenLocked = r.canShowWhenLocked();
final boolean dismissKeyguard = r.hasDismissKeyguardWindows();
if (shouldBeVisible) {
if (dismissKeyguard && mTopDismissingKeyguardActivity == null) {
mTopDismissingKeyguardActivity = r;
}
if (isTop) {
mTopActivityOccludesKeyguard |= showWhenLocked;
}
final boolean canShowWithKeyguard = canShowWithInsecureKeyguard()
&& mStackSupervisor.getKeyguardController().canDismissKeyguard();
if (canShowWithKeyguard) {
return true;
}
}
if (keyguardOrAodShowing) {
return shouldBeVisible && mStackSupervisor.getKeyguardController()
.canShowActivityWhileKeyguardShowing(r, dismissKeyguard);
} else if (keyguardLocked) {
return shouldBeVisible && mStackSupervisor.getKeyguardController().canShowWhileOccluded(
dismissKeyguard, showWhenLocked);
} else {
return shouldBeVisible;
}
}
- 在该函数中,会根据是否显示 keyguard 或者 AOD 来判断该Activity是否真的可见,如果当前没有显示 keyguard 或者 AOD,那么就直接以传入的
shouldBeVisible 为准,此时就是直接返回 shouldBeVisible ,也就是 reallyVisible?=?true -
ActivityStack.updateBehindFullscreen(false, false, r) private boolean updateBehindFullscreen(boolean stackInvisible, boolean behindFullscreenActivity,
ActivityRecord r) {
if (r.fullscreen) {
behindFullscreenActivity = true;
}
return behindFullscreenActivity;
}
- 可以看到,如果前一个传入的Activity是fullscreen的,即全屏显示的,那么就会设置
behindFullscreenActivity = true ,即代表在该Activity下面的Activity都是处于被盖住显示的状态 - 针对当前的Activity,
reallyVisible = true 也就是可见的,那么在 ensureActivitiesVisibleLocked() 函数中,会命中 if (reallyVisible){...} ,接下来会循环判断下一个 Activity 的可见性,此时 behindFullscreenActivity 是为 true -
ActivityRecord.shouldBeVisibleIgnoringKeyguard(true)
- 由于此时传入的
behindFullscreenActivity 是为 true,进入判断后返回则为false,即 visibleIgnoringKeyguard = false -
ActivityStack.checkKeyguardVisibility(r, false, false)
- 由于此时传入的
visibleIgnoringKeyguard = false ,所以此时判断返回的 reallyVisible = false ,即当前的Activity是不可见的,那么接下来就会命中 makeInvisible(r) ,也就会设置当前的 Activity 为 Invisible,并且在这之中,还会根据当前Activity的状态,决定是否将其添加到 mStoppingActivities 列表中,方便后续进行stop该Activity
|