Activity的工作原理-android9.0
-
startActivityForResult 方法
當(dāng)開(kāi)啟一個(gè)頁(yè)面的時(shí)候需要調(diào)用Activity的startActivity的方法。最終調(diào)用到了其內(nèi)部的 startActivityForResult 方法宏邮。在 startActivityForResult 方法中 execStartActivity 方法的第二個(gè)參數(shù)mMainThread.getApplicationThread() 几晤,mMainThread是 ActivityThread的實(shí)例,mMainThread.getApplicationThread() 返回 ApplicationThread 而昨,ApplicationThread繼承了 IApplicationThread.Stub,說(shuō)明 ApplicationThread 是ActivityThread的一個(gè)內(nèi)部的Binder 類。
public void startActivityForResult(@RequiresPermission Intent intent, int requestCode, @Nullable Bundle options) { if (mParent == null) { ... Instrumentation.ActivityResult ar = mInstrumentation.execStartActivity( this, mMainThread.getApplicationThread(), mToken, this, intent, requestCode, options); .... } else { if (options != null) { mParent.startActivityFromChild(this, intent, requestCode, options); } else { // Note we want to go through this method for compatibility with // existing applications that may have overridden it. mParent.startActivityFromChild(this, intent, requestCode); } } }
-
執(zhí)行 Instrumentation 的 execStartActivity 的方法镀钓。
public ActivityResult execStartActivity( Context who, IBinder contextThread, IBinder token, Activity target, Intent intent, int requestCode, Bundle options) { IApplicationThread whoThread = (IApplicationThread) contextThread; ... try { intent.migrateExtraStreamToClipData(); intent.prepareToLeaveProcess(who); //通過(guò)ActivityManager.getService()獲取到ActivityManagerService(AMS)居灯,并執(zhí)行其祭务,內(nèi)部的startActivity() int result = ActivityManager.getService() .startActivity(whoThread, who.getBasePackageName(), intent, intent.resolveTypeIfNeeded(who.getContentResolver()), token, target != null ? target.mEmbeddedID : null, requestCode, 0, null, options); checkStartActivityResult(result, intent); } catch (RemoteException e) { throw new RuntimeException("Failure from system", e); } return null; }
在該方法中 ,啟動(dòng)Activity實(shí)際由ActivityManager.getService()返回的值啟動(dòng)怪嫌,ActivityManager.getService()實(shí)際返回的 IActivityManager义锥,IActivityManager是一個(gè)Binder對(duì)象,對(duì)應(yīng)的實(shí)現(xiàn)ActivityManagerService岩灭。Singleton是一個(gè)封裝的單例對(duì)象拌倍,當(dāng)調(diào)用get方法時(shí),會(huì)通過(guò)create方法獲取IActivityManager。ActivityManager.getService()代碼如下:
/** * @hide */ public static IActivityManager getService() { return IActivityManagerSingleton.get(); } private static final Singleton<IActivityManager> IActivityManagerSingleton = new Singleton<IActivityManager>() { @Override protected IActivityManager create() { final IBinder b = ServiceManager.getService(Context.ACTIVITY_SERVICE); final IActivityManager am = IActivityManager.Stub.asInterface(b); return am; } };
checkStartActivityResult 方法主要對(duì)結(jié)果進(jìn)行校驗(yàn)柱恤。例如:當(dāng)返回的結(jié)果是ActivityManager.START_INTENT_NOT_RESOLVED或者 ActivityManager.START_CLASS_NOT_FOUND時(shí)数初,則拋出常見(jiàn)的未在清單文件中注冊(cè)的異常。實(shí)現(xiàn)如下:
public static void checkStartActivityResult(int res, Object intent) { if (!ActivityManager.isStartResultFatalError(res)) { return; } switch (res) { case ActivityManager.START_INTENT_NOT_RESOLVED: case ActivityManager.START_CLASS_NOT_FOUND: if (intent instanceof Intent && ((Intent)intent).getComponent() != null) throw new ActivityNotFoundException( "Unable to find explicit activity class " + ((Intent)intent).getComponent().toShortString() + "; have you declared this activity in your AndroidManifest.xml?"); throw new ActivityNotFoundException( "No Activity found to handle " + intent); case ActivityManager.START_PERMISSION_DENIED: throw new SecurityException("Not allowed to start activity " + intent); case ActivityManager.START_FORWARD_AND_REQUEST_CONFLICT: throw new AndroidRuntimeException( "FORWARD_RESULT_FLAG used while also requesting a result"); case ActivityManager.START_NOT_ACTIVITY: throw new IllegalArgumentException( "PendingIntent is not an activity"); case ActivityManager.START_NOT_VOICE_COMPATIBLE: throw new SecurityException( "Starting under voice control not allowed for: " + intent); case ActivityManager.START_VOICE_NOT_ACTIVE_SESSION: throw new IllegalStateException( "Session calling startVoiceActivity does not match active session"); case ActivityManager.START_VOICE_HIDDEN_SESSION: throw new IllegalStateException( "Cannot start voice activity on a hidden session"); case ActivityManager.START_ASSISTANT_NOT_ACTIVE_SESSION: throw new IllegalStateException( "Session calling startAssistantActivity does not match active session"); case ActivityManager.START_ASSISTANT_HIDDEN_SESSION: throw new IllegalStateException( "Cannot start assistant activity on a hidden session"); case ActivityManager.START_CANCELED: throw new AndroidRuntimeException("Activity could not be started for " + intent); default: throw new AndroidRuntimeException("Unknown error code " + res + " when starting " + intent); } }
-
ActivityManagerService的startActivity
執(zhí)行ActivityManagerService中的startActivity梗顺,最終會(huì)調(diào)用 startActivityAsCaller泡孩,在這個(gè)方法內(nèi),通過(guò)ActivityStartController的 obtainStarter方法獲取到 ActivityStarter,用過(guò)ActivityStarter設(shè)置執(zhí)行需要的值寺谤,代碼如下:
public final int startActivityAsUser(IApplicationThread caller, String callingPackage, Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode, int startFlags, ProfilerInfo profilerInfo, Bundle bOptions, int userId, boolean validateIncomingUser) { ...... // TODO: Switch to user app stacks here. return mActivityStartController.obtainStarter(intent, "startActivityAsUser") .setCaller(caller) .setCallingPackage(callingPackage) .setResolvedType(resolvedType) .setResultTo(resultTo) .setResultWho(resultWho) .setRequestCode(requestCode) .setStartFlags(startFlags) .setProfilerInfo(profilerInfo) .setActivityOptions(bOptions) .setMayWait(userId) .execute(); }
ActivityStarter最后執(zhí)行execute()方法仑鸥,在ActivityStarter調(diào)用setMayWait時(shí)會(huì)將mayWait設(shè)置為true。
setMayWait方法內(nèi)部實(shí)現(xiàn):
ActivityStarter setMayWait(int userId) { mRequest.mayWait = true; mRequest.userId = userId; return this; }
execute()方法內(nèi)部實(shí)現(xiàn):
int execute() { try { // TODO(b/64750076): Look into passing request directly to these methods to allow // for transactional diffs and preprocessing. if (mRequest.mayWait) { return startActivityMayWait(mRequest.caller, mRequest.callingUid, mRequest.callingPackage, mRequest.intent, mRequest.resolvedType, mRequest.voiceSession, mRequest.voiceInteractor, mRequest.resultTo, mRequest.resultWho, mRequest.requestCode, mRequest.startFlags, mRequest.profilerInfo, mRequest.waitResult, mRequest.globalConfig, mRequest.activityOptions, mRequest.ignoreTargetSecurity, mRequest.userId, mRequest.inTask, mRequest.reason, mRequest.allowPendingRemoteAnimationRegistryLookup); } else { return startActivity(mRequest.caller, mRequest.intent, mRequest.ephemeralIntent, mRequest.resolvedType, mRequest.activityInfo, mRequest.resolveInfo, mRequest.voiceSession, mRequest.voiceInteractor, mRequest.resultTo, mRequest.resultWho, mRequest.requestCode, mRequest.callingPid, mRequest.callingUid, mRequest.callingPackage, mRequest.realCallingPid, mRequest.realCallingUid, mRequest.startFlags, mRequest.activityOptions, mRequest.ignoreTargetSecurity, mRequest.componentSpecified, mRequest.outActivity, mRequest.inTask, mRequest.reason, mRequest.allowPendingRemoteAnimationRegistryLookup); } } finally { onExecutionComplete(); } }
接著調(diào)用startActivityMayWait方法直到調(diào)用到內(nèi)部的startActivity方法,接著調(diào)用到 \startActivityUnchecked方法 变屁,startActivity方法代碼如下:
private int startActivity(final ActivityRecord r, ActivityRecord sourceRecord, IVoiceInteractionSession voiceSession, IVoiceInteractor voiceInteractor, int startFlags, boolean doResume, ActivityOptions options, TaskRecord inTask, ActivityRecord[] outActivity) { int result = START_CANCELED; try { mService.mWindowManager.deferSurfaceLayout(); //調(diào)用到 startActivityUnchecked result = startActivityUnchecked(r, sourceRecord, voiceSession, voiceInteractor, startFlags, doResume, options, inTask, outActivity); } finally { .... } postStartActivityProcessing(r, result, mTargetStack); return result; }
startActivityUnchecked方法內(nèi)部眼俊,通過(guò)啟動(dòng)的標(biāo)志位及啟動(dòng)模式?jīng)Q定一個(gè)Activity的啟動(dòng),最終都會(huì)調(diào)用 ActivityStackSupervisor的resumeFocusedStackTopActivityLocked()粟关,startActivityUnchecked方法如下:
private int startActivityUnchecked(final ActivityRecord r, ActivityRecord sourceRecord, IVoiceInteractionSession voiceSession, IVoiceInteractor voiceInteractor, int startFlags, boolean doResume, ActivityOptions options, TaskRecord inTask, ActivityRecord[] outActivity) { .... //通過(guò)啟動(dòng)的標(biāo)志位及啟動(dòng)模式?jīng)Q定一個(gè)Activity的啟動(dòng)疮胖。 final boolean dontStart = top != null && mStartActivity.resultTo == null && top.realActivity.equals(mStartActivity.realActivity) && top.userId == mStartActivity.userId && top.app != null && top.app.thread != null && ((mLaunchFlags & FLAG_ACTIVITY_SINGLE_TOP) != 0 || isLaunchModeOneOf(LAUNCH_SINGLE_TOP, LAUNCH_SINGLE_TASK)); if (dontStart) { // For paranoia, make sure we have correctly resumed the top activity. topStack.mLastPausedActivity = null; if (mDoResume) { mSupervisor.resumeFocusedStackTopActivityLocked(); } .... deliverNewIntent(top); return START_DELIVERED_TO_TOP; } if (mDoResume) { final ActivityRecord topTaskActivity = mStartActivity.getTask().topRunningActivityLocked(); if (!mTargetStack.isFocusable() || (topTaskActivity != null && topTaskActivity.mTaskOverlay && mStartActivity != topTaskActivity)) { mSupervisor.resumeFocusedStackTopActivityLocked(mTargetStack, mStartActivity, mOptions); } } else if (mStartActivity != null) { mSupervisor.mRecentTasks.add(mStartActivity.getTask()); } return START_SUCCESS; }
-
ActivityStackSupervisor的resumeFocusedStackTopActivityLocked()
resumeFocusedStackTopActivityLocked方法內(nèi)部最終會(huì)調(diào)用ActivityStack的resumeTopActivityUncheckedLocked()方法。
boolean resumeFocusedStackTopActivityLocked() { return resumeFocusedStackTopActivityLocked(null, null, null); } boolean resumeFocusedStackTopActivityLocked( ActivityStack targetStack, ActivityRecord target, ActivityOptions targetOptions) { if (!readyToResume()) { return false; } if (targetStack != null && isFocusedStack(targetStack)) { return targetStack.resumeTopActivityUncheckedLocked(target, targetOptions); } final ActivityRecord r = mFocusedStack.topRunningActivityLocked(); if (r == null || !r.isState(RESUMED)) { mFocusedStack.resumeTopActivityUncheckedLocked(null, null); } else if (r.isState(RESUMED)) { // Kick off any lingering app transitions form the MoveTaskToFront operation. mFocusedStack.executeAppTransition(targetOptions); } return false; }
-
ActivityStack的resumeTopActivityUncheckedLocked()
resumeTopActivityUncheckedLocked方法內(nèi)部調(diào)用了resumeTopActivityInnerLocked誊役,在resumeTopActivityInnerLocked方法內(nèi)部會(huì)判斷是否有處在onResume狀態(tài)的Activity,若有先調(diào)用startPausingLocked改變Activity的狀態(tài)获列。接著調(diào)用ActivityStackSupervisor 的startSpecificActivityLocked方法
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); } .... mStackSupervisor.startSpecificActivityLocked(next, true, false); }
Activity的暫停
-
分析startPausingLocked方法
在 startPausingLocked方法內(nèi)部 調(diào)用AMS的 getLifecycleManager()獲取到ClientLifecycleManager,該類是客戶端生命周期的管理類蛔垢,接著調(diào)用ClientLifecycleManager的 scheduleTransaction方法击孩,該方法的第二個(gè)參數(shù) 傳遞了PauseActivityItem,該參數(shù)是Activity對(duì)應(yīng)的onPause狀態(tài)的類鹏漆,繼承自 ActivityLifecycleItem巩梢。
final boolean startPausingLocked(boolean userLeaving, boolean uiSleeping, ActivityRecord resuming, boolean pauseImmediately) { .... if (prev.app != null && prev.app.thread != null) { if (DEBUG_PAUSE) Slog.v(TAG_PAUSE, "Enqueueing pending pause: " + prev); try { EventLogTags.writeAmPauseActivity(prev.userId, System.identityHashCode(prev), prev.shortComponentName, "userLeaving=" + userLeaving); mService.updateUsageStats(prev, false); mService.getLifecycleManager().scheduleTransaction(prev.app.thread, prev.appToken, PauseActivityItem.obtain(prev.finishing, userLeaving, prev.configChangeFlags, pauseImmediately)); } catch (Exception e) { // Ignore exception, if process died other code will cleanup. Slog.w(TAG, "Exception thrown during pause", e); mPausingActivity = null; mLastPausedActivity = null; mLastNoHistoryActivity = null; } } else { mPausingActivity = null; mLastPausedActivity = null; mLastNoHistoryActivity = null; } ....... }
-
ClientLifecycleManager的scheduleTransaction方法
該方法調(diào)用 最終調(diào)用 ClientTransaction的schedule方法。
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)) { // 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(); } }
-
ClientTransaction的schedule
該方法中艺玲,mClient是IApplicationThread的對(duì)象括蝠,由于 IApplicationThread是一個(gè)Binder類型的對(duì)象,它的實(shí)現(xiàn)是ActivityThread中的 ApplicationThread饭聚,最終調(diào)用的是 ApplicationThread的 scheduleTransaction
public void schedule() throws RemoteException { mClient.scheduleTransaction(this); }
-
ApplicationThread的 scheduleTransaction
該方法中忌警,調(diào)用ActivityThread的scheduleTransaction,由于ActivityThread中并未實(shí)現(xiàn)該方法因此秒梳,具體實(shí)現(xiàn)在其ClientTransactionHandler類中
@Override public void scheduleTransaction(ClientTransaction transaction) throws RemoteException { ActivityThread.this.scheduleTransaction(transaction); }
-
ClientTransactionHandler的scheduleTransaction
在該方法調(diào)用sendMessage方法法绵,由于sendMessage是抽象的所以具體實(shí)現(xiàn)是在ActivityThread中
void scheduleTransaction(ClientTransaction transaction) { transaction.preExecute(this); sendMessage(ActivityThread.H.EXECUTE_TRANSACTION, transaction); }
-
ActivityThread的sendMessage
在實(shí)現(xiàn)的sendMessage中,最終通過(guò)mH即內(nèi)部的H繼承的Handler發(fā)送消息酪碘,最終調(diào)用handleMessage方法朋譬。
void sendMessage(int what, Object obj) { sendMessage(what, obj, 0, 0, false); } private void sendMessage(int what, Object obj, int arg1, int arg2, boolean async) { if (DEBUG_MESSAGES) Slog.v( TAG, "SCHEDULE " + what + " " + mH.codeToString(what) + ": " + arg1 + " / " + obj); Message msg = Message.obtain(); msg.what = what; msg.obj = obj; msg.arg1 = arg1; msg.arg2 = arg2; if (async) { msg.setAsynchronous(true); } mH.sendMessage(msg); }
在handleMessage中有這樣一段處理代碼,調(diào)用TransactionExecutor的execute處理消息半沽。
case EXECUTE_TRANSACTION: final ClientTransaction transaction = (ClientTransaction) msg.obj; mTransactionExecutor.execute(transaction); if (isSystem()) { // Client transactions inside system process are recycled on the client side // instead of ClientLifecycleManager to avoid being cleared before this // message is handled. transaction.recycle(); } // TODO(lifecycler): Recycle locally scheduled transactions. break;
-
TransactionExecutor的execute
該方法中調(diào)用executeCallbacks和executeLifecycleState方法梳毙。
*/ 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方法:由于未設(shè)置callbacks,直接返回涉枫。
public void executeCallbacks(ClientTransaction transaction) { final List<ClientTransactionItem> callbacks = transaction.getCallbacks(); if (callbacks == null) { // No callbacks to execute, return early. return; } ..... }
executeLifecycleState方法:
該方法中調(diào)用 lifecycleItem.execute方法,lifecycleItem是PauseActivityItem的實(shí)例狡赐,因此直接查看PauseActivityItem中的execute方法窑业。
/** Transition to the final state if requested by the transaction. */ private void executeLifecycleState(ClientTransaction transaction) { final ActivityLifecycleItem lifecycleItem = transaction.getLifecycleStateRequest(); if (lifecycleItem == null) { // No lifecycle request, return early. return; } log("Resolving lifecycle state: " + lifecycleItem); 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. cycleToPath(r, lifecycleItem.getTargetState(), true /* excludeLastState */); // Execute the final transition with proper parameters. lifecycleItem.execute(mTransactionHandler, token, mPendingActions); lifecycleItem.postExecute(mTransactionHandler, token, mPendingActions); }
-
PauseActivityItem中的execute方法
該方法中調(diào)用 client.handlePauseActivity方法,client是ClientTransactionHandler阴汇。由于ClientTransactionHandler中的handlePauseActivity是一個(gè)抽象方法数冬,因此需要查看ActivityThread的handlePauseActivity节槐。
@Override 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); }
-
ActivityThread的handlePauseActivity
在該方法中調(diào)用了performPauseActivity方法搀庶。然后調(diào)用performPauseActivityIfNeeded方法,在performPauseActivityIfNeeded方法中調(diào)用了mInstrumentation.callActivityOnPause(r.activity)的方法铜异。
@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); // Make sure any pending writes are now committed. if (r.isPreHoneycomb()) { QueuedWork.waitToFinish(); } mSomeActivitiesChanged = true; } }
-
Instrumentation的callActivityOnPause
最終調(diào)用activity.performPause();
public void callActivityOnPause(Activity activity) { activity.performPause(); }
-
Activity的performPause
在performPause方法中最終調(diào)用了 onPause()方法哥倔。
final void performPause() { .... onPause(); ... }
到這里,當(dāng)啟動(dòng)一個(gè)Activity時(shí)揍庄,上一個(gè)activity的從onResume狀態(tài)編程onpasue狀態(tài)分析完畢咆蒿。接下來(lái)分析Activity的啟動(dòng)。
應(yīng)用已經(jīng)啟動(dòng)的條件下Activity的啟動(dòng)蚂子。
在上一個(gè)Activity狀態(tài)變成暫停之后沃测,會(huì)調(diào)用ActivityStackSupervisor的startSpecificActivityLocked方法繼續(xù)執(zhí)行Activity啟動(dòng)的流程。
-
ActivityStackSupervisor 的startSpecificActivityLocked
在該方法中食茎,會(huì)判斷application是否已經(jīng)啟動(dòng)蒂破,若啟動(dòng)調(diào)用realStartActivityLocked,若未啟動(dòng)調(diào)用AMS的startProcessLocked方法别渔。
void startSpecificActivityLocked(ActivityRecord r, boolean andResume, boolean checkConfig) { // Is this activity's application already running? ProcessRecord app = mService.getProcessRecordLocked(r.processName, r.info.applicationInfo.uid, true); getLaunchTimeTracker().setLaunchTime(r); //application已經(jīng)啟動(dòng) if (app != null && app.thread != null) { try { if ((r.info.flags&ActivityInfo.FLAG_MULTIPROCESS) == 0 || !"android".equals(r.info.packageName)) { // Don't add this if it is a platform component that is marked // to run in multiple processes, because this is actually // part of the framework so doesn't make sense to track as a // separate apk in the process. app.addPackage(r.info.packageName, r.info.applicationInfo.longVersionCode, mService.mProcessStats); } //調(diào)用該方法執(zhí)行application已經(jīng)啟動(dòng)的條件下的Activity啟動(dòng)流程附迷。 realStartActivityLocked(r, app, 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. } //調(diào)用該方法執(zhí)行application未啟動(dòng)的條件下的Activity啟動(dòng)流程。 mService.startProcessLocked(r.processName, r.info.applicationInfo, true, 0, "activity", r.intent.getComponent(), false, false, true); }
realStartActivityLocked方法中,獲取了ClientTransaction對(duì)象哎媚,并在addCallback方法中添加了LaunchActivityItem喇伯,與之前說(shuō)過(guò)的PauseActivityItem一樣,對(duì)應(yīng)處理啟動(dòng)Activity的邏輯處理拨与,最后調(diào)用了mService.getLifecycleManager().scheduleTransaction的方法稻据,mService.getLifecycleManager()獲取的是ClientLifecycleManager,調(diào)用ClientLifecycleManager的scheduleTransaction买喧。
final boolean realStartActivityLocked(ActivityRecord r, ProcessRecord app, boolean andResume, boolean checkConfig) throws RemoteException { ... // Create activity launch transaction. final ClientTransaction clientTransaction = ClientTransaction.obtain(app.thread, r.appToken); 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, app.repProcState, r.icicle, r.persistentState, results, newIntents, mService.isNextTransitionForward(), profilerInfo)); // Set desired final state. final ActivityLifecycleItem lifecycleItem; if (andResume) { lifecycleItem = ResumeActivityItem.obtain(mService.isNextTransitionForward()); } else { lifecycleItem = PauseActivityItem.obtain(); } clientTransaction.setLifecycleStateRequest(lifecycleItem); // Schedule transaction. mService.getLifecycleManager().scheduleTransaction(clientTransaction); .... }
-
ClientLifecycleManager的scheduleTransaction
與暫停的邏輯處理基本一致,調(diào)用ClientTransaction的schedule方法
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(); } }
-
ClientTransaction的schedule
在該方法中捻悯,mClient是IApplicationThread,IApplicationThread是一個(gè)Binder類型的類岗喉,具體實(shí)現(xiàn)是ActivityThread中的ApplicationThread秋度,執(zhí)行ApplicationThread的scheduleTransaction
public void schedule() throws RemoteException { mClient.scheduleTransaction(this); }
-
ApplicationThread的scheduleTransaction
在該方法中執(zhí)行了 ActivityThread中的scheduleTransaction,由于ActivityThread中并未實(shí)現(xiàn)該方法钱床,所以具體的實(shí)現(xiàn)是在父類ClientTransactionHandler中荚斯,執(zhí)行ClientTransactionHandler的scheduleTransaction方法。
@Override public void scheduleTransaction(ClientTransaction transaction) throws RemoteException { ActivityThread.this.scheduleTransaction(transaction); }
-
ClientTransactionHandler的scheduleTransaction
該方法中調(diào)用了內(nèi)部的抽象方法sendMessage,ActivityThread.H是Activity內(nèi)部的一個(gè)Handler類事期,Activity的狀態(tài)都由該Handler處理滥壕。然后執(zhí)行ClientTransactionHandler的子類中的sendMessage的具體實(shí)現(xiàn)。
void scheduleTransaction(ClientTransaction transaction) { transaction.preExecute(this); sendMessage(ActivityThread.H.EXECUTE_TRANSACTION, transaction); }
-
ActivityThread的sendMessage
該方法最終調(diào)用它的重載方法兽泣,然后在重載方法中調(diào)用 mH.sendMessage(msg);mH是ActivityThread的Handler類绎橘。調(diào)用handler的sendMessage之后,具體的處理在mH(Handler)的handleMessage方法
private void sendMessage(int what, Object obj, int arg1, int arg2, boolean async) { if (DEBUG_MESSAGES) Slog.v( TAG, "SCHEDULE " + what + " " + mH.codeToString(what) + ": " + arg1 + " / " + obj); Message msg = Message.obtain(); msg.what = what; msg.obj = obj; msg.arg1 = arg1; msg.arg2 = arg2; if (async) { msg.setAsynchronous(true); } mH.sendMessage(msg); }
-
mH(Handler)的handleMessage方法
執(zhí)行EXECUTE_TRANSACTION狀態(tài)的方法唠倦,最終執(zhí)行TransactionExecutor的execute(transaction)的方法称鳞。
case EXECUTE_TRANSACTION: final ClientTransaction transaction = (ClientTransaction) msg.obj; mTransactionExecutor.execute(transaction); if (isSystem()) { // Client transactions inside system process are recycled on the client side // instead of ClientLifecycleManager to avoid being cleared before this // message is handled. transaction.recycle(); } // TODO(lifecycler): Recycle locally scheduled transactions. break;
-
TransactionExecutor的execute方法
在方法內(nèi),最終執(zhí)行executeLifecycleState(transaction)稠鼻,執(zhí)行生命周期狀態(tài)方法冈止。
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"); }
executeLifecycleState方法,在該方法內(nèi)最終執(zhí)行ActivityLifecycleItem的execute(mTransactionHandler, token, mPendingActions)方法候齿。ActivityLifecycleItem的具體實(shí)現(xiàn)就是上文中傳入的LanuchActivityItem對(duì)象熙暴。
/** Transition to the final state if requested by the transaction. */ private void executeLifecycleState(ClientTransaction transaction) { final ActivityLifecycleItem lifecycleItem = transaction.getLifecycleStateRequest(); if (lifecycleItem == null) { // No lifecycle request, return early. return; } log("Resolving lifecycle state: " + lifecycleItem); 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. cycleToPath(r, lifecycleItem.getTargetState(), true /* excludeLastState */); // Execute the final transition with proper parameters. lifecycleItem.execute(mTransactionHandler, token, mPendingActions); lifecycleItem.postExecute(mTransactionHandler, token, mPendingActions); }
-
LaunchActivityItem的execute
在該方法內(nèi)部調(diào)用client.handleLaunchActivity方法。client是ClientTransactionHandler的對(duì)象慌盯,ClientTransactionHandler是一個(gè)抽象類周霉,handleLaunchActivity方法具體的實(shí)現(xiàn)是在ActviityThread類中。
@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 /* customIntent */); Trace.traceEnd(TRACE_TAG_ACTIVITY_MANAGER); }
-
ActviityThread的handleLaunchActivity
在方法中亚皂,調(diào)用performLaunchActivity方法
@Override public Activity handleLaunchActivity(ActivityClientRecord r, PendingTransactionActions pendingActions, Intent customIntent) { ..... 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 { // If there was an error, for any reason, tell the activity manager to stop us. try { ActivityManager.getService() .finishActivity(r.token, Activity.RESULT_CANCELED, null, Activity.DONT_FINISH_TASK_WITH_ACTIVITY); } catch (RemoteException ex) { throw ex.rethrowFromSystemServer(); } } return a; }
performLaunchActivity方法俱箱,在該方法中,主要做了幾件事孕讳,設(shè)置組件名稱匠楚,創(chuàng)建Context,創(chuàng)建Activity的實(shí)例厂财,并將Context和Application與Activity關(guān)聯(lián)芋簿。最終調(diào)用Instrumentation的callActivityOnCreate方法。
/** Core implementation of activity launch. */ private Activity performLaunchActivity(ActivityClientRecord r, Intent customIntent) { ... //設(shè)置組件名稱 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); } //創(chuàng)建一個(gè)Context ContextImpl appContext = createBaseContextForActivity(r); Activity activity = null; try { //通過(guò)ClassLoader創(chuàng)建一個(gè)activity的實(shí)例 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) { if (!mInstrumentation.onException(activity, e)) { throw new RuntimeException( "Unable to instantiate activity " + component + ": " + e.toString(), e); } } try { //設(shè)置application Application app = r.packageInfo.makeApplication(false, mInstrumentation); if (localLOGV) Slog.v(TAG, "Performing launch of " + r); if (localLOGV) Slog.v( TAG, r + ": app=" + app + ", appName=" + app.getPackageName() + ", pkg=" + r.packageInfo.getPackageName() + ", comp=" + r.intent.getComponent().toShortString() + ", dir=" + r.packageInfo.getAppDir()); 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綁定context璃饱,application等信息 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; //調(diào)用callActivityOnCreate方法執(zhí)行Activity的oncreate方法与斤。 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) { if (!mInstrumentation.onException(activity, e)) { throw new RuntimeException( "Unable to start activity " + component + ": " + e.toString(), e); } } return activity; }
-
Instrumentation的callActivityOnCreate方法
在該方法中調(diào)用Activity的performCreate(icicle)方法
public void callActivityOnCreate(Activity activity, Bundle icicle) { prePerformCreate(activity); activity.performCreate(icicle); postPerformCreate(activity); }
-
Activity的performCreate
該方法最終調(diào)用了它的重載方法,在重載方法中調(diào)用onCreate荚恶。
final void performCreate(Bundle icicle, PersistableBundle persistentState) { mCanEnterPictureInPicture = true; restoreHasCurrentPermissionRequest(icicle); if (persistentState != null) { onCreate(icicle, persistentState); } else { onCreate(icicle); } writeEventLog(LOG_AM_ON_CREATE_CALLED, "performCreate"); mActivityTransitionState.readState(icicle); mVisibleFromClient = !mWindow.getWindowStyle().getBoolean( com.android.internal.R.styleable.Window_windowNoDisplay, false); mFragments.dispatchActivityCreated(); mActivityTransitionState.setEnterActivityOptions(this, getActivityOptions()); }
這一階段就結(jié)束了撩穿。下面看應(yīng)用未啟動(dòng)的情況。
應(yīng)用未啟動(dòng)的條件下Activity的啟動(dòng)谒撼。
在上文中說(shuō)到應(yīng)用未啟動(dòng)下會(huì)調(diào)用AMS的startProcessLocked方法
//調(diào)用該方法執(zhí)行application未啟動(dòng)的條件下的Activity啟動(dòng)流程食寡。
mService.startProcessLocked(r.processName, r.info.applicationInfo, true, 0,
"activity", r.intent.getComponent(), false, false, true);
-
AMS的startProcessLocked
在該方法中會(huì)執(zhí)行開(kāi)啟進(jìn)程的操作,并有一個(gè)變量設(shè)置為entryPoint = "android.app.ActivityThread"廓潜。接著調(diào)用 startProcessLocked方法
private final boolean startProcessLocked(ProcessRecord app, String hostingType, String hostingNameStr, boolean disableHiddenApiChecks, String abiOverride) { .... final String entryPoint = "android.app.ActivityThread"; return startProcessLocked(hostingType, hostingNameStr, entryPoint, app, uid, gids, runtimeFlags, mountExternal, seInfo, requiredAbi, instructionSet, invokeWith, startTime); .... }
startProcessLocked方法:
在方法中會(huì)調(diào)用startProcess開(kāi)啟進(jìn)程的方法抵皱。
final ProcessStartResult startResult = startProcess(app.hostingType, entryPoint, app, app.startUid, gids, runtimeFlags, mountExternal, app.seInfo, requiredAbi, instructionSet, invokeWith, app.startTime);
在startProcess方法中會(huì)調(diào)用Process.start進(jìn)程的開(kāi)始方法
startResult = Process.start(entryPoint, app.processName, uid, uid, gids, runtimeFlags, mountExternal, app.info.targetSdkVersion, seInfo, requiredAbi, instructionSet, app.info.dataDir, invokeWith, new String[] {PROC_START_SEQ_IDENT + app.startSeq});
-
Process的start
在Process的方法中會(huì)調(diào)用ZygoteProcess進(jìn)程的start方法善榛,
public static final ProcessStartResult start(final String processClass, final String niceName, int uid, int gid, int[] gids, int runtimeFlags, int mountExternal, int targetSdkVersion, String seInfo, String abi, String instructionSet, String appDataDir, String invokeWith, String[] zygoteArgs) { return zygoteProcess.start(processClass, niceName, uid, gid, gids, runtimeFlags, mountExternal, targetSdkVersion, seInfo, abi, instructionSet, appDataDir, invokeWith, zygoteArgs); }
-
ZygoteProcess的start方法
該方法的第一個(gè)參數(shù)是哪個(gè)類的main方法會(huì)運(yùn)行,也就是上面?zhèn)鞯淖址產(chǎn)ndroid.app.ActivityThread即ActivityThread類的main方法呻畸。然后通過(guò)ZygoteProcess會(huì)fork出一個(gè)新進(jìn)程移盆。
private Process.ProcessStartResult startViaZygote(final String processClass, final String niceName, final int uid, final int gid, final int[] gids, int runtimeFlags, int mountExternal, int targetSdkVersion, String seInfo, String abi, String instructionSet, String appDataDir, String invokeWith, boolean startChildZygote, String[] extraArgs) throws ZygoteStartFailedEx { synchronized(mLock) { return zygoteSendArgsAndGetResult(openZygoteSocketIfNeeded(abi), argsForZygote); } }
openZygoteSocketIfNeeded方法:
該方法內(nèi)會(huì)連接socket,并與fork出的進(jìn)程通信伤为。
/** * Tries to open socket to Zygote process if not already open. If * already open, does nothing. May block and retry. Requires that mLock be held. */ @GuardedBy("mLock") private ZygoteState openZygoteSocketIfNeeded(String abi) throws ZygoteStartFailedEx { Preconditions.checkState(Thread.holdsLock(mLock), "ZygoteProcess lock not held"); if (primaryZygoteState == null || primaryZygoteState.isClosed()) { try { primaryZygoteState = ZygoteState.connect(mSocket); } catch (IOException ioe) { throw new ZygoteStartFailedEx("Error connecting to primary zygote", ioe); } maybeSetApiBlacklistExemptions(primaryZygoteState, false); maybeSetHiddenApiAccessLogSampleRate(primaryZygoteState); } if (primaryZygoteState.matches(abi)) { return primaryZygoteState; } // The primary zygote didn't match. Try the secondary. if (secondaryZygoteState == null || secondaryZygoteState.isClosed()) { try { secondaryZygoteState = ZygoteState.connect(mSecondarySocket); } catch (IOException ioe) { throw new ZygoteStartFailedEx("Error connecting to secondary zygote", ioe); } maybeSetApiBlacklistExemptions(secondaryZygoteState, false); maybeSetHiddenApiAccessLogSampleRate(secondaryZygoteState); } if (secondaryZygoteState.matches(abi)) { return secondaryZygoteState; } throw new ZygoteStartFailedEx("Unsupported zygote ABI: " + abi); }
-
ActivityThread的main方法
main方法中創(chuàng)建Looper,Handler消息對(duì)列MessageQueue并調(diào)用Looper.loop()開(kāi)啟消息循環(huán)咒循。并且調(diào)用ActivityThread的attach方法。
public static void main(String[] args) { ... Looper.prepareMainLooper(); ActivityThread thread = new ActivityThread(); thread.attach(false, startSeq); if (sMainThreadHandler == null) { sMainThreadHandler = thread.getHandler(); } if (false) { Looper.myLooper().setMessageLogging(new LogPrinter(Log.DEBUG, "ActivityThread")); } // End of event ActivityThreadMain. Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER); Looper.loop(); throw new RuntimeException("Main thread loop unexpectedly exited"); }
-
ActivityThread的attach
在該方法中調(diào)用IActivityManager的attachApplication方法即調(diào)用AMS的attachApplication绞愚,綁定application叙甸,然后設(shè)置垃圾回收器。
private void attach(boolean system, long startSeq) { sCurrentActivityThread = this; mSystemThread = system; if (!system) { ViewRootImpl.addFirstDrawHandler(new Runnable() { @Override public void run() { ensureJitEnabled(); } }); android.ddm.DdmHandleAppName.setAppName("<pre-initialized>", UserHandle.myUserId()); RuntimeInit.setApplicationObject(mAppThread.asBinder()); final IActivityManager mgr = ActivityManager.getService(); try { mgr.attachApplication(mAppThread, startSeq); } catch (RemoteException ex) { throw ex.rethrowFromSystemServer(); } // Watch for getting close to heap limit. BinderInternal.addGcWatcher(new Runnable() { @Override public void run() { if (!mSomeActivitiesChanged) { return; } Runtime runtime = Runtime.getRuntime(); long dalvikMax = runtime.maxMemory(); long dalvikUsed = runtime.totalMemory() - runtime.freeMemory(); if (dalvikUsed > ((3*dalvikMax)/4)) { if (DEBUG_MEMORY_TRIM) Slog.d(TAG, "Dalvik max=" + (dalvikMax/1024) + " total=" + (runtime.totalMemory()/1024) + " used=" + (dalvikUsed/1024)); mSomeActivitiesChanged = false; try { mgr.releaseSomeActivities(mAppThread); } catch (RemoteException e) { throw e.rethrowFromSystemServer(); } } } }); } else { // Don't set application object here -- if the system crashes, // we can't display an alert, we just want to die die die. android.ddm.DdmHandleAppName.setAppName("system_process", UserHandle.myUserId()); try { mInstrumentation = new Instrumentation(); mInstrumentation.basicInit(this); ContextImpl context = ContextImpl.createAppContext( this, getSystemContext().mPackageInfo); mInitialApplication = context.mPackageInfo.makeApplication(true, null); mInitialApplication.onCreate(); } catch (Exception e) { throw new RuntimeException( "Unable to instantiate Application():" + e.toString(), e); } } // add dropbox logging to libcore DropBox.setReporter(new DropBoxReporter()); ViewRootImpl.ConfigChangedCallback configChangedCallback = (Configuration globalConfig) -> { synchronized (mResourcesManager) { // We need to apply this change to the resources immediately, because upon returning // the view hierarchy will be informed about it. if (mResourcesManager.applyConfigurationToResourcesLocked(globalConfig, null /* compat */)) { updateLocaleListFromAppContext(mInitialApplication.getApplicationContext(), mResourcesManager.getConfiguration().getLocales()); // This actually changed the resources! Tell everyone about it. if (mPendingConfiguration == null || mPendingConfiguration.isOtherSeqNewer(globalConfig)) { mPendingConfiguration = globalConfig; sendMessage(H.CONFIGURATION_CHANGED, globalConfig); } } } }; ViewRootImpl.addConfigCallback(configChangedCallback); }
-
AMS的attachApplication
attachApplication方法調(diào)用attachApplicationLocked方法爽醋,
@Override public final void attachApplication(IApplicationThread thread, long startSeq) { synchronized (this) { int callingPid = Binder.getCallingPid(); final int callingUid = Binder.getCallingUid(); final long origId = Binder.clearCallingIdentity(); attachApplicationLocked(thread, callingPid, callingUid, startSeq); Binder.restoreCallingIdentity(origId); } }
attachApplicationLocked方法,該方法會(huì)調(diào)用ActivityStackSupervisor的attachApplicationLocked方法
@GuardedBy("this") private final boolean attachApplicationLocked(IApplicationThread thread, int pid, int callingUid, long startSeq) { ... // See if the top visible activity is waiting to run in this process... if (normalMode) { try { if (mStackSupervisor.attachApplicationLocked(app)) { didSomething = true; } } catch (Exception e) { Slog.wtf(TAG, "Exception thrown launching activities in " + app, e); badApp = true; } } ... }
-
ActivityStackSupervisor的attachApplicationLocked
該方法內(nèi)會(huì)調(diào)用realStartActivityLocked方法蚁署,通過(guò)方法名字知道Activity的啟動(dòng)應(yīng)該在這個(gè)方法內(nèi)便脊。
boolean attachApplicationLocked(ProcessRecord app) throws RemoteException { .... if (realStartActivityLocked(activity, app, top == activity /* andResume */, true /* checkConfig */)) { didSomething = true; } ... return didSomething; }
realStartActivityLocked方法內(nèi)又找到跟應(yīng)用啟動(dòng)條件下相同的Activity的代碼蚂四。創(chuàng)建LaunchActivityItem的Activity的啟動(dòng)對(duì)象,并通過(guò)AMS獲取ClientLifecycleManager對(duì)象哪痰,并執(zhí)行ClientLifecycleManager的scheduleTransaction方法遂赠。后續(xù)的流程已經(jīng)在上面的在應(yīng)用啟動(dòng)的條件下Activity的啟動(dòng)流程中分析過(guò)了。
final boolean realStartActivityLocked(ActivityRecord r, ProcessRecord app, boolean andResume, boolean checkConfig) throws RemoteException { ... // Create activity launch transaction. final ClientTransaction clientTransaction = ClientTransaction.obtain(app.thread, r.appToken); 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, app.repProcState, r.icicle, r.persistentState, results, newIntents, mService.isNextTransitionForward(), profilerInfo)); // Set desired final state. final ActivityLifecycleItem lifecycleItem; if (andResume) { lifecycleItem = ResumeActivityItem.obtain(mService.isNextTransitionForward()); } else { lifecycleItem = PauseActivityItem.obtain(); } clientTransaction.setLifecycleStateRequest(lifecycleItem); // Schedule transaction. mService.getLifecycleManager().scheduleTransaction(clientTransaction); ..... }