publicfinalclassActivityThreadextendsClientTransactionHandler{ /** Activity client record, used for bookkeeping for the real {@link Activity} instance. */ publicstaticfinalclassActivityClientRecord{ Activity activity; Window window; Activity parent; }
privatefinalbooleanattachApplicationLocked(IApplicationThread thread, int pid, int callingUid, long startSeq){ try { // AMS 通过 ApplicationThread 这个 AIDL Proxy 和 App 进程的 ActivityThread 通信 if (app.isolatedEntryPoint != null) { // This is an isolated process which should just call an entry point instead of being bound to an application. thread.runIsolatedEntryPoint(...); } elseif (instr2 != null) { thread.bindApplication(...); } else { thread.bindApplication(...); } } // 尝试启动 Activity // See if the top visible activity is waiting to run in this process... if (normalMode) { try { didSomething = mAtmInternal.attachApplication(app.getWindowProcessController()); } catch (Exception e) { Slog.wtf(TAG, "Exception thrown launching activities in " + app, e); badApp = true; } } } }
/** Initialize an instance with transaction handler, that will execute all requested actions. */ publicTransactionExecutor(ClientTransactionHandler clientTransactionHandler){ mTransactionHandler = clientTransactionHandler; }
/** Cycle through all states requested by callbacks and execute them at proper times. */ publicvoidexecuteCallbacks(ClientTransaction transaction){ // transaction.getCallbacks() 获取的 Callback 实际是之前 ActivityStackSupervisor#realStartActivityLocked 中, // ClientTransaction.addCallback(LaunchActivityItem) 传入的 LaunchActivityItem。 final List<ClientTransactionItem> callbacks = transaction.getCallbacks(); for (...) { final ClientTransactionItem item = callbacks.get(i); item.execute(mTransactionHandler, token, mPendingActions); item.postExecute(mTransactionHandler, token, mPendingActions); } }
/** Transition to the final state if requested by the transaction. */ privatevoidexecuteLifecycleState(ClientTransaction transaction){ final ActivityLifecycleItem lifecycleItem = transaction.getLifecycleStateRequest(); ...... lifecycleItem.execute(mTransactionHandler, token, mPendingActions); lifecycleItem.postExecute(mTransactionHandler, token, mPendingActions); } }
publicfinalclassActivityThreadextendsClientTransactionHandler{ /** * Extended implementation of activity launch. Used when server requests a launch or relaunch. */ @Override public Activity handleLaunchActivity(ActivityClientRecord r, PendingTransactionActions pendingActions, Intent customIntent){ ...... // 关键步骤 performLaunchActivity final Activity a = performLaunchActivity(r, customIntent); if (a != null) { ...... } else { // If there was an error, for any reason, tell the activity manager to stop us. try { ActivityTaskManager.getService().finishActivity(...); } catch (RemoteException ex) { throw ex.rethrowFromSystemServer(); } } } }
publicfinalclassActivityThreadextendsClientTransactionHandler{ @Override publicvoidhandleDestroyActivity(IBinder token, boolean finishing, int configChanges, boolean getNonConfigInstance, String reason){ ActivityClientRecord r = performDestroyActivity(...); if (r != null) { View v = r.activity.mDecor; if (v != null) { ...... if (r.activity.mWindowAdded) { if (r.mPreserveWindow) { // 核心逻辑: // Hold off on removing this until the new activity's // window is being added. r.mPendingRemoveWindow = r.window; r.mPendingRemoveWindowManager = wm; // We can only keep the part of the view hierarchy that we control, // everything else must be removed, because it might not be able to // behave properly when activity is relaunching. r.window.clearContentView(); } else { wm.removeViewImmediate(v); } } } } } }
publicclassPhoneWindowextendsWindowimplementsMenuBuilder.Callback{ /** * Constructor for main window of an activity. */ publicPhoneWindow(Context context, Window preservedWindow, ActivityConfigCallback activityConfigCallback){ // 注意这里的判断条件,是需要 preservedWindow != null 才去初始化 DecorView。 // 如果是新启动一个 Activity,传进来的 preservedWindow == null,是不会走这个逻辑的。 if (preservedWindow != null) { mDecor = (DecorView) preservedWindow.getDecorView(); mElevation = preservedWindow.getElevation(); mLoadElevation = false; mForceDecorInstall = true; // If we're preserving window, carry over the app token from the preserved // window, as we'll be skipping the addView in handleResumeActivity(), and // the token will not be updated as for a new window. getAttributes().token = preservedWindow.getAttributes().token; } ...... }
private TransactionExecutorHelper mHelper = new TransactionExecutorHelper();
publicvoidexecute(ClientTransaction transaction){ // 用于回调 onCreate() executeCallbacks(transaction); // 用于流转到 onStart(), onResume() executeLifecycleState(transaction); } /** Transition to the final state if requested by the transaction. */ privatevoidexecuteLifecycleState(ClientTransaction transaction){ final ActivityLifecycleItem lifecycleItem = transaction.getLifecycleStateRequest(); // 在生成 ClientTransaction 的方法 ActivityStackSupervisor#realStartActivityLocked 中, // andResume == true 时 lifecycleItem 时 ResumeActivityItem 类型, // 实际上 transaction 持有的 lifecycleItem 是 `ResumeActivityItem` 类型, // 因此 lifecycleItem.getTargetState() 返回的就是 ON_RESUME。 cycleToPath(r, lifecycleItem.getTargetState(), true/* excludeLastState */, transaction); // 这里传入的 mTransactionHandler 就是 ActivityThread lifecycleItem.execute(mTransactionHandler, token, mPendingActions); lifecycleItem.postExecute(mTransactionHandler, token, mPendingActions); } /** * Transition the client between states with an option not to perform the last hop in the * sequence. This is used when resolving lifecycle state request, when the last transition must * be performed with some specific parameters. */ privatevoidcycleToPath(ActivityClientRecord r, int finish, boolean excludeLastState, ClientTransaction transaction){ // 由于此前 Activity 刚完成 onCreate,所以 start == ON_CREATE, // executeLifecycleState(...) 方法中传入的 finish == ON_RESUME, // executeLifecycleState(...) 方法中传入的 excludeLastState == true。 finalint start = r.getLifecycleState(); final IntArray path = mHelper.getLifecyclePath(start, finish, excludeLastState); performLifecycleSequence(r, path, transaction); } /** Transition the client through previously initialized state sequence. */ privatevoidperformLifecycleSequence(ActivityClientRecord r, IntArray path, ClientTransaction transaction){ finalint size = path.size(); for (int i = 0, state; i < size; i++) { state = path.get(i); switch (state) { case ON_START: { mTransactionHandler.handleStartActivity(r, mPendingActions); break; } } } } }
publicclassTransactionExecutorHelper{ /** * Calculate the path through main lifecycle states for an activity and fill * @link #mLifecycleSequence} with values starting with the state that follows the initial * state. * <p>NOTE: The returned value is used internally in this class and is not a copy. It's contents * may change after calling other methods of this class.</p> */ @VisibleForTesting public IntArray getLifecyclePath(int start, int finish, boolean excludeLastState){ if (finish >= start) { for (int i = start + 1; 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; } }
publicclassInstrumentation{ /** * Perform calling of an activity's {@link Activity#onStart} * method. The default implementation simply calls through to that method. * * @param activity The activity being started. */ publicvoidcallActivityOnStart(Activity activity){ activity.onStart(); } }
/** * Retrieve the top-level window decor view (containing the standard * window frame/decorations and the client's content inside of that), which * can be added as a window to the window manager. * * <p><em>Note that calling this function for the first time "locks in" * various window characteristics as described in * {@link #setContentView(View, android.view.ViewGroup.LayoutParams)}.</em></p> * * @return Returns the top-level window decor view. */ publicfinal@NonNullView getDecorView(){ if (mDecor == null || mForceDecorInstall) { // 内部逻辑其实就是 new 出来一个 DecorView,并与当前 Window 绑定 installDecor(); } return mDecor; }
publicfinalclassActivityThreadextendsClientTransactionHandler{ final ArrayMap<IBinder, ActivityClientRecord> mActivities = new ArrayMap<>(); public ActivityClientRecord performResumeActivity(IBinder token, boolean finalStateRequest, String reason){ final ActivityClientRecord r = mActivities.get(token); try { r.activity.performResume(r.startsNotResumed, reason); r.state = null; r.persistentState = null; r.setState(ON_RESUME); } return r; } }
publicclassActivity{ finalvoidperformResume(boolean followedByPause, String reason){ dispatchActivityPreResumed(); performRestart(true/* start */, reason); // mResumed is set by the instrumentation mInstrumentation.callActivityOnResume(this); } }
classAppCompatDelegateImplextendsAppCompatDelegate{ privatevoidensureSubDecor(){ if (!mSubDecorInstalled) { // 真正的创建是这个方法 mSubDecor = createSubDecor();
// 可以看到在 setContentView(...) 内部加载了标题和 ActionBar // 这也是为什么在 Activity 中,对 ActionBar 或 Title 的修改必须放在 setContentView(...) 调用之前 // If a title was set before we installed the decor, propagate it now CharSequence title = getTitle(); if (!TextUtils.isEmpty(title)) { if (mDecorContentParent != null) { mDecorContentParent.setWindowTitle(title); } elseif (peekSupportActionBar() != null) { peekSupportActionBar().setWindowTitle(title); } elseif (mTitleView != null) { mTitleView.setText(title); } } mSubDecorInstalled = true; } } private ViewGroup createSubDecor(){ TypedArray a = mContext.obtainStyledAttributes(R.styleable.AppCompatTheme); // 这下面有一堆 if - else 都只是为了确定这个 Activity 对应 Window 的样式 if (...) {......} a.recycle();
// 先确保了 Window 已经初始化 // Now let's make sure that the Window has installed its decor by retrieving it ensureWindow(); // 从 Activity 存储的 PhoneWindow 中获取 DecorView,但并不是需要拿到 DecorView 实例, // 而是为了像上面 handleResumeActivity(...) 中的 r.activity.getWindow() 一样,确保 DecorView 已被创建 mWindow.getDecorView(); // 这个就是目标 subDecor ViewGroup subDecor = null;