privatebooleanattachApplicationLocked(@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; } }
//确保所有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. returnfalse; }
final Task task = r.getTask(); final ActivityStack stack = task.getStack();
// 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; }
// 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); }
try { if (!proc.hasThread()) { thrownew 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);
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);
//处理重量级进程 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 */); returnfalse; }
// 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(); }
voidscheduleTransaction(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(); } }
publicvoidexecute(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; } } }
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(); } }
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]));
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方法 thrownew 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); }
privatevoidexecuteLifecycleState(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); }
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); } elseif (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); }
publicvoidhandleResumeActivity(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; }
// 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. } elseif (!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();
public ActivityClientRecord performResumeActivity(IBinder token, boolean finalStateRequest, String reason){ final ActivityClientRecord r = mActivities.get(token);
mCalled = false; // mResumed is set by the instrumentation //执行Activity.onResume回调 mInstrumentation.callActivityOnResume(this); if (!mCalled) { //必须执行super.onResume方法 thrownew 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;
//执行onPostResume回调 onPostResume(); if (!mCalled) { //必须要执行super.onPostResume thrownew SuperNotCalledException( "Activity " + mComponent.toShortString() + " did not call through to super.onPostResume()"); } //回调ActivityLifecycleCallbacks.onActivityPostResumed dispatchActivityPostResumed(); }
staticvoidactivityResumedLocked(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 */);