startActivity啟動過程分析(轉)


基於Android 6.0的源碼剖析, 分析android Activity啟動流程,相關源碼:

frameworks/base/services/core/java/com/android/server/am/ - ActivityManagerService.java - ActivityStackSupervisor.java - ActivityStack.java - ActivityRecord.java - ProcessRecord.java frameworks/base/core/java/android/app/ - IActivityManager.java - ActivityManagerNative.java (內含AMP) - ActivityManager.java - IApplicationThread.java - ApplicationThreadNative.java (內含ATP) - ActivityThread.java (內含ApplicationThread) - ContextImpl.java 

一. 概述

startActivity的整體流程與startService啟動過程分析非常相近,但比Service啟動更為復雜,多了stack/task以及UI的相關內容以及Activity的生命周期更為豐富。

Activity啟動發起后,通過Binder最終交由system進程中的AMS來完成,則啟動流程如下圖:

start_activity

接下來,從源碼來說說每個過程。

二. 啟動流程

2.1 Activity.startActivity

[-> Activity.java]

public void startActivity(Intent intent) { this.startActivity(intent, null); } public void startActivity(Intent intent, @Nullable Bundle options) { if (options != null) { startActivityForResult(intent, -1, options); } else { //[見小節2.2] startActivityForResult(intent, -1); } } 

2.2 startActivityForResult

[-> Activity.java]

public void startActivityForResult(Intent intent, int requestCode) { startActivityForResult(intent, requestCode, null); } public void startActivityForResult(Intent intent, int requestCode, @Nullable Bundle options) { if (mParent == null) { //[見小節2.3] Instrumentation.ActivityResult ar = mInstrumentation.execStartActivity( this, mMainThread.getApplicationThread(), mToken, this, intent, requestCode, options); if (ar != null) { mMainThread.sendActivityResult( mToken, mEmbeddedID, requestCode, ar.getResultCode(), ar.getResultData()); } //此時requestCode =-1 if (requestCode >= 0) { mStartedActivity = true; } cancelInputsAndStartExitTransition(options); } else { ... } } 

execStartActivity()方法的參數:

  • mAppThread: 數據類型為ApplicationThread,通過mMainThread.getApplicationThread()方法獲取。
  • mToken: 數據類型為IBinder.

2.3 execStartActivity

[-> Instrumentation.java]

public ActivityResult execStartActivity( Context who, IBinder contextThread, IBinder token, Activity target, Intent intent, int requestCode, Bundle options) { IApplicationThread whoThread = (IApplicationThread) contextThread; ... if (mActivityMonitors != null) { synchronized (mSync) { final int N = mActivityMonitors.size(); for (int i=0; i<N; i++) { final ActivityMonitor am = mActivityMonitors.get(i); if (am.match(who, null, intent)) { am.mHits++; //當該monitor阻塞activity啟動,則直接返回 if (am.isBlocking()) { return requestCode >= 0 ? am.getResult() : null; } break; } } } } try { intent.migrateExtraStreamToClipData(); intent.prepareToLeaveProcess(); //[見小節2.4] int result = ActivityManagerNative.getDefault() .startActivity(whoThread, who.getBasePackageName(), intent, intent.resolveTypeIfNeeded(who.getContentResolver()), token, target != null ? target.mEmbeddedID : null, requestCode, 0, null, options); //檢查activity是否啟動成功 checkStartActivityResult(result, intent); } catch (RemoteException e) { throw new RuntimeException("Failure from system", e); } return null; } 

關於 ActivityManagerNative.getDefault()返回的是ActivityManagerProxy對象. 此處startActivity()的共有10個參數, 下面說說每個參數傳遞AMP.startActivity()每一項的對應值:

  • caller: 當前應用的ApplicationThread對象mAppThread;
  • callingPackage: 調用當前ContextImpl.getBasePackageName(),獲取當前Activity所在包名;
  • intent: 這便是啟動Activity時,傳遞過來的參數;
  • resolvedType: 調用intent.resolveTypeIfNeeded而獲取;
  • resultTo: 來自於當前Activity.mToken
  • resultWho: 來自於當前Activity.mEmbeddedID
  • requestCode = -1;
  • startFlags = 0;
  • profilerInfo = null;
  • options = null;

2.4 AMP.startActivity

[-> ActivityManagerNative.java :: ActivityManagerProxy]

class ActivityManagerProxy implements IActivityManager { ... public int startActivity(IApplicationThread caller, String callingPackage, Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode, int startFlags, ProfilerInfo profilerInfo, Bundle options) throws RemoteException { Parcel data = Parcel.obtain(); Parcel reply = Parcel.obtain(); data.writeInterfaceToken(IActivityManager.descriptor); data.writeStrongBinder(caller != null ? caller.asBinder() : null); data.writeString(callingPackage); intent.writeToParcel(data, 0); data.writeString(resolvedType); data.writeStrongBinder(resultTo); data.writeString(resultWho); data.writeInt(requestCode); data.writeInt(startFlags); if (profilerInfo != null) { data.writeInt(1); profilerInfo.writeToParcel(data, Parcelable.PARCELABLE_WRITE_RETURN_VALUE); } else { data.writeInt(0); } if (options != null) { data.writeInt(1); options.writeToParcel(data, 0); } else { data.writeInt(0); } //[見流程2.5] mRemote.transact(START_ACTIVITY_TRANSACTION, data, reply, 0); reply.readException(); int result = reply.readInt(); reply.recycle(); data.recycle(); return result; } ... } 

AMP經過binder IPC,進入ActivityManagerNative(簡稱AMN)。接下來程序進入了system_servr進程,開始繼續執行。

2.5 AMN.onTransact

[-> ActivityManagerNative.java]

public boolean onTransact(int code, Parcel data, Parcel reply, int flags) throws RemoteException { switch (code) { case START_ACTIVITY_TRANSACTION: { data.enforceInterface(IActivityManager.descriptor); IBinder b = data.readStrongBinder(); IApplicationThread app = ApplicationThreadNative.asInterface(b); String callingPackage = data.readString(); Intent intent = Intent.CREATOR.createFromParcel(data); String resolvedType = data.readString(); IBinder resultTo = data.readStrongBinder(); String resultWho = data.readString(); int requestCode = data.readInt(); int startFlags = data.readInt(); ProfilerInfo profilerInfo = data.readInt() != 0 ? ProfilerInfo.CREATOR.createFromParcel(data) : null; Bundle options = data.readInt() != 0 ? Bundle.CREATOR.createFromParcel(data) : null; //[見流程2.6] int result = startActivity(app, callingPackage, intent, resolvedType, resultTo, resultWho, requestCode, startFlags, profilerInfo, options); reply.writeNoException(); reply.writeInt(result); return true; } ... } } 

2.6 AMS.startActivity

[-> ActivityManagerService.java]

public final int startActivity(IApplicationThread caller, String callingPackage, Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode, int startFlags, ProfilerInfo profilerInfo, Bundle options) { return startActivityAsUser(caller, callingPackage, intent, resolvedType, resultTo, resultWho, requestCode, startFlags, profilerInfo, options, UserHandle.getCallingUserId()); } public final int startActivityAsUser(IApplicationThread caller, String callingPackage, Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode, int startFlags, ProfilerInfo profilerInfo, Bundle options, int userId) { enforceNotIsolatedCaller("startActivity"); userId = handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(), userId, false, ALLOW_FULL_ONLY, "startActivity", null); //[見小節2.7] return mStackSupervisor.startActivityMayWait(caller, -1, callingPackage, intent, resolvedType, null, null, resultTo, resultWho, requestCode, startFlags, profilerInfo, null, null, options, false, userId, null, null); } 

此處mStackSupervisor的數據類型為ActivityStackSupervisor

2.7 ASS.startActivityMayWait

當程序運行到這里時, ASS.startActivityMayWait的各個參數取值如下:

  • caller = ApplicationThreadProxy, 用於跟調用者進程ApplicationThread進行通信的binder代理類.
  • callingUid = -1;
  • callingPackage = ContextImpl.getBasePackageName(),獲取調用者Activity所在包名
  • intent: 這是啟動Activity時傳遞過來的參數;
  • resolvedType = intent.resolveTypeIfNeeded
  • voiceSession = null;
  • voiceInteractor = null;
  • resultTo = Activity.mToken, 其中Activity是指調用者所在Activity, mToken對象保存自己所處的ActivityRecord信息
  • resultWho = Activity.mEmbeddedID, 其中Activity是指調用者所在Activity
  • requestCode = -1;
  • startFlags = 0;
  • profilerInfo = null;
  • outResult = null;
  • config = null;
  • options = null;
  • ignoreTargetSecurity = false;
  • userId = AMS.handleIncomingUser, 當調用者userId跟當前處於同一個userId,則直接返回該userId;當不相等時則根據調用者userId來決定是否需要將callingUserId轉換為mCurrentUserId.
  • iContainer = null;
  • inTask = null;

再來看看這個方法的源碼:

[-> ActivityStackSupervisor.java]

final int startActivityMayWait(IApplicationThread caller, int callingUid, String callingPackage, Intent intent, String resolvedType, IVoiceInteractionSession voiceSession, IVoiceInteractor voiceInteractor, IBinder resultTo, String resultWho, int requestCode, int startFlags, ProfilerInfo profilerInfo, WaitResult outResult, Configuration config, Bundle options, boolean ignoreTargetSecurity, int userId, IActivityContainer iContainer, TaskRecord inTask) { ... boolean componentSpecified = intent.getComponent() != null; //創建新的Intent對象,即便intent被修改也不受影響 intent = new Intent(intent); //收集Intent所指向的Activity信息, 當存在多個可供選擇的Activity,則直接向用戶彈出resolveActivity [見2.7.1] ActivityInfo aInfo = resolveActivity(intent, resolvedType, startFlags, profilerInfo, userId); ActivityContainer container = (ActivityContainer)iContainer; synchronized (mService) { if (container != null && container.mParentActivity != null && container.mParentActivity.state != RESUMED) { ... //不進入該分支, container == nul } final int realCallingPid = Binder.getCallingPid(); final int realCallingUid = Binder.getCallingUid(); int callingPid; if (callingUid >= 0) { callingPid = -1; } else if (caller == null) { callingPid = realCallingPid; callingUid = realCallingUid; } else { callingPid = callingUid = -1; } final ActivityStack stack; if (container == null || container.mStack.isOnHomeDisplay()) { stack = mFocusedStack; // 進入該分支 } else { stack = container.mStack; } //此時mConfigWillChange = false stack.mConfigWillChange = config != null && mService.mConfiguration.diff(config) != 0; final long origId = Binder.clearCallingIdentity(); if (aInfo != null && (aInfo.applicationInfo.privateFlags &ApplicationInfo.PRIVATE_FLAG_CANT_SAVE_STATE) != 0) { // heavy-weight進程處理流程, 一般情況下不進入該分支 if (aInfo.processName.equals(aInfo.applicationInfo.packageName)) { ... } } //[見流程2.8] int res = startActivityLocked(caller, intent, resolvedType, aInfo, voiceSession, voiceInteractor, resultTo, resultWho, requestCode, callingPid, callingUid, callingPackage, realCallingPid, realCallingUid, startFlags, options, ignoreTargetSecurity, componentSpecified, null, container, inTask); Binder.restoreCallingIdentity(origId); if (stack.mConfigWillChange) { ... //不進入該分支 } if (outResult != null) { ... //不進入該分支 } return res; } } 

該過程主要功能:通過resolveActivity來獲取ActivityInfo信息, 然后再進入ASS.startActivityLocked().先來看看

2.7.1 ASS.resolveActivity

// startFlags = 0; profilerInfo = null; userId代表caller UserId ActivityInfo resolveActivity(Intent intent, String resolvedType, int startFlags, ProfilerInfo profilerInfo, int userId) { ActivityInfo aInfo; ResolveInfo rInfo = AppGlobals.getPackageManager().resolveIntent( intent, resolvedType, PackageManager.MATCH_DEFAULT_ONLY | ActivityManagerService.STOCK_PM_FLAGS, userId); aInfo = rInfo != null ? rInfo.activityInfo : null; if (aInfo != null) { intent.setComponent(new ComponentName( aInfo.applicationInfo.packageName, aInfo.name)); if (!aInfo.processName.equals("system")) { ... //對於非system進程,根據flags來設置相應的debug信息 } } return aInfo; } 

ActivityManager類有如下4個flags用於調試:

  • START_FLAG_DEBUG:用於調試debug app
  • START_FLAG_OPENGL_TRACES:用於調試OpenGL tracing
  • START_FLAG_NATIVE_DEBUGGING:用於調試native
  • START_FLAG_TRACK_ALLOCATION: 用於調試allocation tracking

2.7.2 PKMS.resolveIntent

AppGlobals.getPackageManager()經過函數層層調用,獲取的是ApplicationPackageManager對象。經過binder IPC調用,最終會調用PackageManagerService對象。故此時調用方法為PMS.resolveIntent().

[-> PackageManagerService.java]

public ResolveInfo resolveIntent(Intent intent, String resolvedType, int flags, int userId) { if (!sUserManager.exists(userId)) return null; enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "resolve intent"); //[見流程2.7.3] List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId); //根據priority,preferred選擇最佳的Activity return chooseBestActivity(intent, resolvedType, flags, query, userId); } 

2.7.3 PMS.queryIntentActivities

public List<ResolveInfo> queryIntentActivities(Intent intent, String resolvedType, int flags, int userId) { ... ComponentName comp = intent.getComponent(); if (comp == null) { if (intent.getSelector() != null) { intent = intent.getSelector(); comp = intent.getComponent(); } } if (comp != null) { final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); //獲取Activity信息 final ActivityInfo ai = getActivityInfo(comp, flags, userId); if (ai != null) { final ResolveInfo ri = new ResolveInfo(); ri.activityInfo = ai; list.add(ri); } return list; } ... } 

ASS.resolveActivity()方法的核心功能是找到相應的Activity組件,並保存到intent對象。

2.8 ASS.startActivityLocked

[-> ActivityStackSupervisor.java]

final int startActivityLocked(IApplicationThread caller, Intent intent, String resolvedType, ActivityInfo aInfo, IVoiceInteractionSession voiceSession, IVoiceInteractor voiceInteractor, IBinder resultTo, String resultWho, int requestCode, int callingPid, int callingUid, String callingPackage, int realCallingPid, int realCallingUid, int startFlags, Bundle options, boolean ignoreTargetSecurity, boolean componentSpecified, ActivityRecord[] outActivity, ActivityContainer container, TaskRecord inTask) { int err = ActivityManager.START_SUCCESS; //獲取調用者的進程記錄對象 ProcessRecord callerApp = null; if (caller != null) { callerApp = mService.getRecordForAppLocked(caller); if (callerApp != null) { callingPid = callerApp.pid; callingUid = callerApp.info.uid; } else { err = ActivityManager.START_PERMISSION_DENIED; } } final int userId = aInfo != null ? UserHandle.getUserId(aInfo.applicationInfo.uid) : 0; ActivityRecord sourceRecord = null; ActivityRecord resultRecord = null; if (resultTo != null) { //獲取調用者所在的Activity sourceRecord = isInAnyStackLocked(resultTo); if (sourceRecord != null) { if (requestCode >= 0 && !sourceRecord.finishing) { ... //requestCode = -1 則不進入 } } } final int launchFlags = intent.getFlags(); if ((launchFlags & Intent.FLAG_ACTIVITY_FORWARD_RESULT) != 0 && sourceRecord != null) { ... // activity執行結果的返回由源Activity轉換到新Activity, 不需要返回結果則不會進入該分支 } if (err == ActivityManager.START_SUCCESS && intent.getComponent() == null) { //從Intent中無法找到相應的Component err = ActivityManager.START_INTENT_NOT_RESOLVED; } if (err == ActivityManager.START_SUCCESS && aInfo == null) { //從Intent中無法找到相應的ActivityInfo err = ActivityManager.START_INTENT_NOT_RESOLVED; } if (err == ActivityManager.START_SUCCESS && !isCurrentProfileLocked(userId) && (aInfo.flags & FLAG_SHOW_FOR_ALL_USERS) == 0) { //嘗試啟動一個后台Activity, 但該Activity對當前用戶不可見 err = ActivityManager.START_NOT_CURRENT_USER_ACTIVITY; } ... //執行后resultStack = null final ActivityStack resultStack = resultRecord == null ? null : resultRecord.task.stack; ... //權限檢查 // ActivityController不為空的情況,比如monkey測試過程 if (mService.mController != null) { Intent watchIntent = intent.cloneFilter(); abort |= !mService.mController.activityStarting(watchIntent, aInfo.applicationInfo.packageName); } if (abort) { ... //權限檢查不滿足,才進入該分支則直接返回; return ActivityManager.START_SUCCESS; } // 創建Activity記錄對象 ActivityRecord r = new ActivityRecord(mService, callerApp, callingUid, callingPackage, intent, resolvedType, aInfo, mService.mConfiguration, resultRecord, resultWho, requestCode, componentSpecified, voiceSession != null, this, container, options); if (outActivity != null) { outActivity[0] = r; } if (r.appTimeTracker == null && sourceRecord != null) { r.appTimeTracker = sourceRecord.appTimeTracker; } // 將mFocusedStack賦予當前stack final ActivityStack stack = mFocusedStack; if (voiceSession == null && (stack.mResumedActivity == null || stack.mResumedActivity.info.applicationInfo.uid != callingUid)) { // 前台stack還沒有resume狀態的Activity時, 則檢查app切換是否允許 [見流程2.8.1] if (!mService.checkAppSwitchAllowedLocked(callingPid, callingUid, realCallingPid, realCallingUid, "Activity start")) { PendingActivityLaunch pal = new PendingActivityLaunch(r, sourceRecord, startFlags, stack); // 當不允許切換,則把要啟動的Activity添加到mPendingActivityLaunches對象, 並且直接返回. mPendingActivityLaunches.add(pal); ActivityOptions.abort(options); return ActivityManager.START_SWITCHES_CANCELED; } } if (mService.mDidAppSwitch) { //從上次禁止app切換以來,這是第二次允許app切換,因此將允許切換時間設置為0,則表示可以任意切換app mService.mAppSwitchesAllowedTime = 0; } else { mService.mDidAppSwitch = true; } //處理 pendind Activity的啟動, 這些Activity是由於app switch禁用從而被hold的等待啟動activity [見流程2.8.2] doPendingActivityLaunchesLocked(false); //[見流程2.9] err = startActivityUncheckedLocked(r, sourceRecord, voiceSession, voiceInteractor, startFlags, true, options, inTask); if (err < 0) { notifyActivityDrawnForKeyguard(); } return err; } 

其中有兩個返回值代表啟動Activity失敗:

  • START_INTENT_NOT_RESOLVED: 從Intent中無法找到相應的Component或者ActivityInfo
  • START_NOT_CURRENT_USER_ACTIVITY:該Activity對當前用戶不可見

2.8.1 AMS.checkAppSwitchAllowedLocked

boolean checkAppSwitchAllowedLocked(int sourcePid, int sourceUid, int callingPid, int callingUid, String name) { if (mAppSwitchesAllowedTime < SystemClock.uptimeMillis()) { return true; } int perm = checkComponentPermission( android.Manifest.permission.STOP_APP_SWITCHES, sourcePid, sourceUid, -1, true); if (perm == PackageManager.PERMISSION_GRANTED) { return true; } if (callingUid != -1 && callingUid != sourceUid) { perm = checkComponentPermission( android.Manifest.permission.STOP_APP_SWITCHES, callingPid, callingUid, -1, true); if (perm == PackageManager.PERMISSION_GRANTED) { return true; } } return false; } 

當mAppSwitchesAllowedTime時間小於當前時長,或者具有STOP_APP_SWITCHES的權限,則允許app發生切換操作.

其中mAppSwitchesAllowedTime, 在AMS.stopAppSwitches()的過程中會設置為:mAppSwitchesAllowedTime = SystemClock.uptimeMillis() + APP_SWITCH_DELAY_TIME. 禁止app切換的timeout時長為5s(APP_SWITCH_DELAY_TIME = 5s).

當發送5秒超時或者執行AMS.resumeAppSwitches()過程會將mAppSwitchesAllowedTime設置0, 都會開啟允許app執行切換的操作.另外,禁止App切換的操作,對於同一個app是不受影響的,有興趣可以進一步查看checkComponentPermission過程.

2.8.2 ASS.doPendingActivityLaunchesLocked

[-> ActivityStackSupervisor.java]

final void doPendingActivityLaunchesLocked(boolean doResume) { while (!mPendingActivityLaunches.isEmpty()) { PendingActivityLaunch pal = mPendingActivityLaunches.remove(0); try { //[見流程2.9] startActivityUncheckedLocked(pal.r, pal.sourceRecord, null, null, pal.startFlags, doResume && mPendingActivityLaunches.isEmpty(), null, null); } catch (Exception e) { ... } } } 

mPendingActivityLaunches記錄着所有將要啟動的Activity, 是由於在startActivityLocked的過程時App切換功能被禁止, 也就是不運行切換Activity, 那么此時便會把相應的Activity加入到mPendingActivityLaunches隊列. 該隊列的成員在執行完doPendingActivityLaunchesLocked便會清空.

啟動mPendingActivityLaunches中所有的Activity, 由於doResume = false, 那么這些activtity並不會進入resume狀態,而是設置delayedResume = true, 會延遲resume.

2.9 ASS.startActivityUncheckedLocked

[-> ActivityStackSupervisor.java]

// sourceRecord是指調用者, r是指本次將要啟動的Activity final int startActivityUncheckedLocked(final ActivityRecord r, ActivityRecord sourceRecord, IVoiceInteractionSession voiceSession, IVoiceInteractor voiceInteractor, int startFlags, boolean doResume, Bundle options, TaskRecord inTask) { final Intent intent = r.intent; final int callingUid = r.launchedFromUid; if (inTask != null && !inTask.inRecents) { inTask = null; } final boolean launchSingleTop = r.launchMode == ActivityInfo.LAUNCH_SINGLE_TOP; final boolean launchSingleInstance = r.launchMode == ActivityInfo.LAUNCH_SINGLE_INSTANCE; final boolean launchSingleTask = r.launchMode == ActivityInfo.LAUNCH_SINGLE_TASK; int launchFlags = intent.getFlags(); // 當intent和activity manifest存在沖突,則manifest優先 if ((launchFlags & Intent.FLAG_ACTIVITY_NEW_DOCUMENT) != 0 && (launchSingleInstance || launchSingleTask)) { launchFlags &= ~(Intent.FLAG_ACTIVITY_NEW_DOCUMENT | Intent.FLAG_ACTIVITY_MULTIPLE_TASK); } else { ... } final boolean launchTaskBehind = r.mLaunchTaskBehind && !launchSingleTask && !launchSingleInstance && (launchFlags & Intent.FLAG_ACTIVITY_NEW_DOCUMENT) != 0; if (r.resultTo != null && (launchFlags & Intent.FLAG_ACTIVITY_NEW_TASK) != 0 && r.resultTo.task.stack != null) { r.resultTo.task.stack.sendActivityResultLocked(-1, r.resultTo, r.resultWho, r.requestCode, Activity.RESULT_CANCELED, null); r.resultTo = null; } if ((launchFlags & Intent.FLAG_ACTIVITY_NEW_DOCUMENT) != 0 && r.resultTo == null) { launchFlags |= Intent.FLAG_ACTIVITY_NEW_TASK; } if ((launchFlags & Intent.FLAG_ACTIVITY_NEW_TASK) != 0) { if (launchTaskBehind || r.info.documentLaunchMode == ActivityInfo.DOCUMENT_LAUNCH_ALWAYS) { launchFlags |= Intent.FLAG_ACTIVITY_MULTIPLE_TASK; } } mUserLeaving = (launchFlags & Intent.FLAG_ACTIVITY_NO_USER_ACTION) == 0; //當本次不需要resume,則設置為延遲resume的狀態 if (!doResume) { r.delayedResume = true; } ActivityRecord notTop = (launchFlags & Intent.FLAG_ACTIVITY_PREVIOUS_IS_TOP) != 0 ? r : null; if ((startFlags&ActivityManager.START_FLAG_ONLY_IF_NEEDED) != 0) { ActivityRecord checkedCaller = sourceRecord; if (checkedCaller == null) { checkedCaller = mFocusedStack.topRunningNonDelayedActivityLocked(notTop); } if (!checkedCaller.realActivity.equals(r.realActivity)) { //調用者 與將要啟動的Activity不相同時,進入該分支。 startFlags &= ~ActivityManager.START_FLAG_ONLY_IF_NEEDED; } } boolean addingToTask = false; TaskRecord reuseTask = null; //當調用者不是來自activity,而是明確指定task的情況。 if (sourceRecord == null && inTask != null && inTask.stack != null) { ... //目前sourceRecord不為空,則不進入該分支 } else { inTask = null; } if (inTask == null) { if (sourceRecord == null) { //調用者並不是Activity context,則強制創建新task if ((launchFlags & Intent.FLAG_ACTIVITY_NEW_TASK) == 0 && inTask == null) { launchFlags |= Intent.FLAG_ACTIVITY_NEW_TASK; } } else if (sourceRecord.launchMode == ActivityInfo.LAUNCH_SINGLE_INSTANCE) { //調用者activity帶有single instance,則創建新task launchFlags |= Intent.FLAG_ACTIVITY_NEW_TASK; } else if (launchSingleInstance || launchSingleTask) { //目標activity帶有single instance或者single task,則創建新task launchFlags |= Intent.FLAG_ACTIVITY_NEW_TASK; } } ActivityInfo newTaskInfo = null; Intent newTaskIntent = null; ActivityStack sourceStack; if (sourceRecord != null) { if (sourceRecord.finishing) { //調用者處於即將finish狀態,則創建新task if ((launchFlags & Intent.FLAG_ACTIVITY_NEW_TASK) == 0) { launchFlags |= Intent.FLAG_ACTIVITY_NEW_TASK; newTaskInfo = sourceRecord.info; newTaskIntent = sourceRecord.task.intent; } sourceRecord = null; sourceStack = null; } else { //當調用者Activity不為空,且不處於finishing狀態,則其所在棧賦於sourceStack sourceStack = sourceRecord.task.stack; } } else { sourceStack = null; } boolean movedHome = false; ActivityStack targetStack; intent.setFlags(launchFlags); final boolean noAnimation = (launchFlags & Intent.FLAG_ACTIVITY_NO_ANIMATION) != 0; if (((launchFlags & Intent.FLAG_ACTIVITY_NEW_TASK) != 0 && (launchFlags & Intent.FLAG_ACTIVITY_MULTIPLE_TASK) == 0) || launchSingleInstance || launchSingleTask) { if (inTask == null && r.resultTo == null) { //從mActivityDisplays開始查詢是否有相應ActivityRecord ActivityRecord intentActivity = !launchSingleInstance ? findTaskLocked(r) : findActivityLocked(intent, r.info); if (intentActivity != null) { if (isLockTaskModeViolation(intentActivity.task, (launchFlags & (FLAG_ACTIVITY_NEW_TASK | FLAG_ACTIVITY_CLEAR_TASK)) == (FLAG_ACTIVITY_NEW_TASK | FLAG_ACTIVITY_CLEAR_TASK))) { return ActivityManager.START_RETURN_LOCK_TASK_MODE_VIOLATION; } if (r.task == null) { r.task = intentActivity.task; } if (intentActivity.task.intent == null) { intentActivity.task.setIntent(r); } targetStack = intentActivity.task.stack; targetStack.mLastPausedActivity = null; final ActivityStack focusStack = getFocusedStack(); ActivityRecord curTop = (focusStack == null) ? null : focusStack.topRunningNonDelayedActivityLocked(notTop); boolean movedToFront = false; if (curTop != null && (curTop.task != intentActivity.task || curTop.task != focusStack.topTask())) { r.intent.addFlags(Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT); if (sourceRecord == null || (sourceStack.topActivity() != null && sourceStack.topActivity().task == sourceRecord.task)) { if (launchTaskBehind && sourceRecord != null) { intentActivity.setTaskToAffiliateWith(sourceRecord.task); } movedHome = true; //將該task移至前台 targetStack.moveTaskToFrontLocked(intentActivity.task, noAnimation, options, r.appTimeTracker, "bringingFoundTaskToFront"); movedToFront = true; if ((launchFlags & (FLAG_ACTIVITY_NEW_TASK | FLAG_ACTIVITY_TASK_ON_HOME)) == (FLAG_ACTIVITY_NEW_TASK | FLAG_ACTIVITY_TASK_ON_HOME)) { //將toReturnTo設置為home intentActivity.task.setTaskToReturnTo(HOME_ACTIVITY_TYPE); } options = null; } } if (!movedToFront) { targetStack.moveToFront("intentActivityFound"); } if ((launchFlags&Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED) != 0) { //重置目標task intentActivity = targetStack.resetTaskIfNeededLocked(intentActivity, r); } if ((startFlags & ActivityManager.START_FLAG_ONLY_IF_NEEDED) != 0) { if (doResume) { resumeTopActivitiesLocked(targetStack, null, options); //當沒有啟動至前台,則通知Keyguard if (!movedToFront) { notifyActivityDrawnForKeyguard(); } } else { ActivityOptions.abort(options); } return ActivityManager.START_RETURN_INTENT_TO_CALLER; } if ((launchFlags & (FLAG_ACTIVITY_NEW_TASK | FLAG_ACTIVITY_CLEAR_TASK)) == (FLAG_ACTIVITY_NEW_TASK | FLAG_ACTIVITY_CLEAR_TASK)) { reuseTask = intentActivity.task; //移除所有跟已存在的task有關聯的activity reuseTask.performClearTaskLocked(); reuseTask.setIntent(r); } else if ((launchFlags & FLAG_ACTIVITY_CLEAR_TOP) != 0 || launchSingleInstance || launchSingleTask) { ActivityRecord top = intentActivity.task.performClearTaskLocked(r, launchFlags); if (top != null) { if (top.frontOfTask) { top.task.setIntent(r); } //觸發onNewIntent() top.deliverNewIntentLocked(callingUid, r.intent, r.launchedFromPackage); } else { sourceRecord = intentActivity; TaskRecord task = sourceRecord.task; if (task != null && task.stack == null) { targetStack = computeStackFocus(sourceRecord, false /* newTask */); targetStack.addTask( task, !launchTaskBehind /* toTop */, false /* moving */); } } } else if (r.realActivity.equals(intentActivity.task.realActivity)) { if (((launchFlags&Intent.FLAG_ACTIVITY_SINGLE_TOP) != 0 || launchSingleTop) && intentActivity.realActivity.equals(r.realActivity)) { if (intentActivity.frontOfTask) { intentActivity.task.setIntent(r); } //觸發onNewIntent() intentActivity.deliverNewIntentLocked(callingUid, r.intent, r.launchedFromPackage); } else if (!r.intent.filterEquals(intentActivity.task.intent)) { addingToTask = true; sourceRecord = intentActivity; } } else if ((launchFlags&Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED) == 0) { addingToTask = true; sourceRecord = intentActivity; } else if (!intentActivity.task.rootWasReset) { intentActivity.task.setIntent(r); } if (!addingToTask && reuseTask == null) { if (doResume) { targetStack.resumeTopActivityLocked(null, options); if (!movedToFront) { notifyActivityDrawnForKeyguard(); } } else { ActivityOptions.abort(options); } return ActivityManager.START_TASK_TO_FRONT; } } } } if (r.packageName != null) { //當啟動的activity跟前台顯示是同一個的情況 ActivityStack topStack = mFocusedStack; ActivityRecord top = topStack.topRunningNonDelayedActivityLocked(notTop); if (top != null && r.resultTo == null) { if (top.realActivity.equals(r.realActivity) && top.userId == r.userId) { if (top.app != null && top.app.thread != null) { if ((launchFlags & Intent.FLAG_ACTIVITY_SINGLE_TOP) != 0 || launchSingleTop || launchSingleTask) { topStack.mLastPausedActivity = null; if (doResume) { resumeTopActivitiesLocked(); } ActivityOptions.abort(options); if ((startFlags&ActivityManager.START_FLAG_ONLY_IF_NEEDED) != 0) { } //觸發onNewIntent() top.deliverNewIntentLocked(callingUid, r.intent, r.launchedFromPackage); return ActivityManager.START_DELIVERED_TO_TOP; } } } } } else { if (r.resultTo != null && r.resultTo.task.stack != null) { r.resultTo.task.stack.sendActivityResultLocked(-1, r.resultTo, r.resultWho, r.requestCode, Activity.RESULT_CANCELED, null); } ActivityOptions.abort(options); return ActivityManager.START_CLASS_NOT_FOUND; } boolean newTask = false; boolean keepCurTransition = false; TaskRecord taskToAffiliate = launchTaskBehind && sourceRecord != null ? sourceRecord.task : null; if (r.resultTo == null && inTask == null && !addingToTask && (launchFlags & Intent.FLAG_ACTIVITY_NEW_TASK) != 0) { newTask = true; targetStack = computeStackFocus(r, newTask); targetStack.moveToFront("startingNewTask"); if (reuseTask == null) { r.setTask(targetStack.createTaskRecord(getNextTaskId(), newTaskInfo != null ? newTaskInfo : r.info, newTaskIntent != null ? newTaskIntent : intent, voiceSession, voiceInteractor, !launchTaskBehind /* toTop */), taskToAffiliate); } else { r.setTask(reuseTask, taskToAffiliate); } if (isLockTaskModeViolation(r.task)) { return ActivityManager.START_RETURN_LOCK_TASK_MODE_VIOLATION; } if (!movedHome) { if ((launchFlags & (FLAG_ACTIVITY_NEW_TASK | FLAG_ACTIVITY_TASK_ON_HOME)) == (FLAG_ACTIVITY_NEW_TASK | FLAG_ACTIVITY_TASK_ON_HOME)) { r.task.setTaskToReturnTo(HOME_ACTIVITY_TYPE); } } } else if (sourceRecord != null) { final TaskRecord sourceTask = sourceRecord.task; if (isLockTaskModeViolation(sourceTask)) { return ActivityManager.START_RETURN_LOCK_TASK_MODE_VIOLATION; } targetStack = sourceTask.stack; targetStack.moveToFront("sourceStackToFront"); final TaskRecord topTask = targetStack.topTask(); if (topTask != sourceTask) { targetStack.moveTaskToFrontLocked(sourceTask, noAnimation, options, r.appTimeTracker, "sourceTaskToFront"); } if (!addingToTask && (launchFlags&Intent.FLAG_ACTIVITY_CLEAR_TOP) != 0) { ActivityRecord top = sourceTask.performClearTaskLocked(r, launchFlags); keepCurTransition = true; if (top != null) { //觸發onNewIntent() top.deliverNewIntentLocked(callingUid, r.intent, r.launchedFromPackage); targetStack.mLastPausedActivity = null; if (doResume) { targetStack.resumeTopActivityLocked(null); } ActivityOptions.abort(options); return ActivityManager.START_DELIVERED_TO_TOP; } } else if (!addingToTask && (launchFlags&Intent.FLAG_ACTIVITY_REORDER_TO_FRONT) != 0) { final ActivityRecord top = sourceTask.findActivityInHistoryLocked(r); if (top != null) { final TaskRecord task = top.task; task.moveActivityToFrontLocked(top); top.updateOptionsLocked(options); //觸發onNewIntent() top.deliverNewIntentLocked(callingUid, r.intent, r.launchedFromPackage); targetStack.mLastPausedActivity = null; if (doResume) { targetStack.resumeTopActivityLocked(null); } return ActivityManager.START_DELIVERED_TO_TOP; } } r.setTask(sourceTask, null); } else if (inTask != null) { if (isLockTaskModeViolation(inTask)) { return ActivityManager.START_RETURN_LOCK_TASK_MODE_VIOLATION; } targetStack = inTask.stack; targetStack.moveTaskToFrontLocked(inTask, noAnimation, options, r.appTimeTracker, "inTaskToFront"); ActivityRecord top = inTask.getTopActivity(); if (top != null && top.realActivity.equals(r.realActivity) && top.userId == r.userId) { if ((launchFlags & Intent.FLAG_ACTIVITY_SINGLE_TOP) != 0 || launchSingleTop || launchSingleTask) { if ((startFlags&ActivityManager.START_FLAG_ONLY_IF_NEEDED) != 0) { return ActivityManager.START_RETURN_INTENT_TO_CALLER; } //觸發onNewIntent() top.deliverNewIntentLocked(callingUid, r.intent, r.launchedFromPackage); return ActivityManager.START_DELIVERED_TO_TOP; } } if (!addingToTask) { ActivityOptions.abort(options); return ActivityManager.START_TASK_TO_FRONT; } r.setTask(inTask, null); } else { targetStack = computeStackFocus(r, newTask); targetStack.moveToFront("addingToTopTask"); ActivityRecord prev = targetStack.topActivity(); r.setTask(prev != null ? prev.task : targetStack.createTaskRecord(getNextTaskId(), r.info, intent, null, null, true), null); mWindowManager.moveTaskToTop(r.task.taskId); } mService.grantUriPermissionFromIntentLocked(callingUid, r.packageName, intent, r.getUriPermissionsLocked(), r.userId); if (sourceRecord != null && sourceRecord.isRecentsActivity()) { r.task.setTaskToReturnTo(RECENTS_ACTIVITY_TYPE); } targetStack.mLastPausedActivity = null; //創建activity [見流程2.10] targetStack.startActivityLocked(r, newTask, doResume, keepCurTransition, options); if (!launchTaskBehind) { mService.setFocusedActivityLocked(r, "startedActivity"); } return ActivityManager.START_SUCCESS; } 

找到或創建新的Activit所屬於的Task對象,之后調用AS.startActivityLocked

2.9.1 Launch Mode

先來說說在ActivityInfo.java中定義了4類Launch Mode:

  • LAUNCH_MULTIPLE(standard):最常見的情形,每次啟動Activity都是創建新的Activity;
  • LAUNCH_SINGLE_TOP: 當Task頂部存在同一個Activity則不再重新創建;其余情況同上;
  • LAUNCH_SINGLE_TASK:當Task棧存在同一個Activity(不在task頂部),則不重新創建,而移除該Activity上面其他的Activity;其余情況同上;
  • LAUNCH_SINGLE_INSTANCE:每個Task只有一個Activity.

再來說說幾個常見的flag含義:

  • FLAG_ACTIVITY_NEW_TASK:將Activity放入一個新啟動的Task;
  • FLAG_ACTIVITY_CLEAR_TASK:啟動Activity時,將目標Activity關聯的Task清除,再啟動新Task,將該Activity放入該Task。該flags跟FLAG_ACTIVITY_NEW_TASK配合使用。
  • FLAG_ACTIVITY_CLEAR_TOP:啟動非棧頂Activity時,先清除該Activity之上的Activity。例如Task已有A、B、C3個Activity,啟動A,則清除B,C。類似於SingleTop。

最后再說說:設置FLAG_ACTIVITY_NEW_TASK的幾個情況:

  • 調用者並不是Activity context;
  • 調用者activity帶有single instance;
  • 目標activity帶有single instance或者single task;
  • 調用者處於finishing狀態;

2.10 AS.startActivityLocked

[-> ActivityStack.java]

final void startActivityLocked(ActivityRecord r, boolean newTask, boolean doResume, boolean keepCurTransition, Bundle options) { TaskRecord rTask = r.task; final int taskId = rTask.taskId; if (!r.mLaunchTaskBehind && (taskForIdLocked(taskId) == null || newTask)) { //task中的上一個activity已被移除,或者ams重用該task,則將該task移到頂部 insertTaskAtTop(rTask, r); mWindowManager.moveTaskToTop(taskId); } TaskRecord task = null; if (!newTask) { boolean startIt = true; for (int taskNdx = mTaskHistory.size() - 1; taskNdx >= 0; --taskNdx) { task = mTaskHistory.get(taskNdx); if (task.getTopActivity() == null) { //該task所有activity都finishing continue; } if (task == r.task) { if (!startIt) { task.addActivityToTop(r); r.putInHistory(); mWindowManager.addAppToken(task.mActivities.indexOf(r), r.appToken, r.task.taskId, mStackId, r.info.screenOrientation, r.fullscreen, (r.info.flags & ActivityInfo.FLAG_SHOW_FOR_ALL_USERS) != 0, r.userId, r.info.configChanges, task.voiceSession != null, r.mLaunchTaskBehind); ActivityOptions.abort(options); return; } break; } else if (task.numFullscreen > 0) { startIt = false; } } } if (task == r.task && mTaskHistory.indexOf(task) != (mTaskHistory.size() - 1)) { mStackSupervisor.mUserLeaving = false; } task = r.task; task.addActivityToTop(r); task.setFrontOfTask(); r.putInHistory(); mActivityTrigger.activityStartTrigger(r.intent, r.info, r.appInfo); if (!isHomeStack() || numActivities() > 0) { //當切換到新的task,或者下一個activity進程目前並沒有運行,則 boolean showStartingIcon = newTask; ProcessRecord proc = r.app; if (proc == null) { proc = mService.mProcessNames.get(r.processName, r.info.applicationInfo.uid); } if (proc == null || proc.thread == null) { showStartingIcon = true; } if ((r.intent.getFlags() & Intent.FLAG_ACTIVITY_NO_ANIMATION) != 0) { mWindowManager.prepareAppTransition(AppTransition.TRANSIT_NONE, keepCurTransition); mNoAnimActivities.add(r); } else { mWindowManager.prepareAppTransition(newTask ? r.mLaunchTaskBehind ? AppTransition.TRANSIT_TASK_OPEN_BEHIND : AppTransition.TRANSIT_TASK_OPEN : AppTransition.TRANSIT_ACTIVITY_OPEN, keepCurTransition); mNoAnimActivities.remove(r); } mWindowManager.addAppToken(task.mActivities.indexOf(r), r.appToken, r.task.taskId, mStackId, r.info.screenOrientation, r.fullscreen, (r.info.flags & ActivityInfo.FLAG_SHOW_FOR_ALL_USERS) != 0, r.userId, r.info.configChanges, task.voiceSession != null, r.mLaunchTaskBehind); boolean doShow = true; if (newTask) { if ((r.intent.getFlags() & Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED) != 0) { resetTaskIfNeededLocked(r, r); doShow = topRunningNonDelayedActivityLocked(null) == r; } } else if (options != null && new ActivityOptions(options).getAnimationType() == ActivityOptions.ANIM_SCENE_TRANSITION) { doShow = false; } if (r.mLaunchTaskBehind) { mWindowManager.setAppVisibility(r.appToken, true); ensureActivitiesVisibleLocked(null, 0); } else if (SHOW_APP_STARTING_PREVIEW && doShow) { ActivityRecord prev = mResumedActivity; if (prev != null) { //當前activity所屬不同的task if (prev.task != r.task) { prev = null; } //當前activity已經displayed else if (prev.nowVisible) { prev = null; } } mWindowManager.setAppStartingWindow( r.appToken, r.packageName, r.theme, mService.compatibilityInfoForPackageLocked( r.info.applicationInfo), r.nonLocalizedLabel, r.labelRes, r.icon, r.logo, r.windowFlags, prev != null ? prev.appToken : null, showStartingIcon); r.mStartingWindowShown = true; } } else { mWindowManager.addAppToken(task.mActivities.indexOf(r), r.appToken, r.task.taskId, mStackId, r.info.screenOrientation, r.fullscreen, (r.info.flags & ActivityInfo.FLAG_SHOW_FOR_ALL_USERS) != 0, r.userId, r.info.configChanges, task.voiceSession != null, r.mLaunchTaskBehind); ActivityOptions.abort(options); options = null; } if (doResume) { // [見流程2.11] mStackSupervisor.resumeTopActivitiesLocked(this, r, options); } } 

2.11 ASS.resumeTopActivitiesLocked

boolean resumeTopActivitiesLocked(ActivityStack targetStack, ActivityRecord target, Bundle targetOptions) { if (targetStack == null) { targetStack = mFocusedStack; } boolean result = false; if (isFrontStack(targetStack)) { //[見流程2.12] result = targetStack.resumeTopActivityLocked(target, targetOptions); } for (int displayNdx = mActivityDisplays.size() - 1; displayNdx >= 0; --displayNdx) { final ArrayList<ActivityStack> stacks = mActivityDisplays.valueAt(displayNdx).mStacks; for (int stackNdx = stacks.size() - 1; stackNdx >= 0; --stackNdx) { final ActivityStack stack = stacks.get(stackNdx); if (stack == targetStack) { //上面剛已啟動 continue; } if (isFrontStack(stack)) { stack.resumeTopActivityLocked(null); } } } return result; } 

2.12 AS.resumeTopActivityLocked

final boolean resumeTopActivityLocked(ActivityRecord prev, Bundle options) { if (mStackSupervisor.inResumeTopActivity) { return false; //防止遞歸啟動 } boolean result = false; try { mStackSupervisor.inResumeTopActivity = true; if (mService.mLockScreenShown == ActivityManagerService.LOCK_SCREEN_LEAVING) { mService.mLockScreenShown = ActivityManagerService.LOCK_SCREEN_HIDDEN; mService.updateSleepIfNeededLocked(); } //[見流程2.13] result = resumeTopActivityInnerLocked(prev, options); } finally { mStackSupervisor.inResumeTopActivity = false; } return result; } 

inResumeTopActivity用於保證每次只有一個Activity執行resumeTopActivityLocked()操作.

2.13 AS.resumeTopActivityInnerLocked

private boolean resumeTopActivityInnerLocked(ActivityRecord prev, Bundle options) { ... //系統沒有進入booting或booted狀態,則不允許啟動Activity ActivityRecord parent = mActivityContainer.mParentActivity; if ((parent != null && parent.state != ActivityState.RESUMED) || !mActivityContainer.isAttachedLocked()) { return false; } //top running之后的任意處於初始化狀態且有顯示StartingWindow, 則移除StartingWindow cancelInitializingActivities(); //找到第一個沒有finishing的棧頂activity final ActivityRecord next = topRunningActivityLocked(null); final boolean userLeaving = mStackSupervisor.mUserLeaving; mStackSupervisor.mUserLeaving = false; final TaskRecord prevTask = prev != null ? prev.task : null; if (next == null) { final String reason = "noMoreActivities"; if (!mFullscreen) { //當該棧沒有全屏,則嘗試聚焦到下一個可見的stack final ActivityStack stack = getNextVisibleStackLocked(); if (adjustFocusToNextVisibleStackLocked(stack, reason)) { return mStackSupervisor.resumeTopActivitiesLocked(stack, prev, null); } } ActivityOptions.abort(options); final int returnTaskType = prevTask == null || !prevTask.isOverHomeStack() ? HOME_ACTIVITY_TYPE : prevTask.getTaskToReturnTo(); //啟動home桌面activity return isOnHomeDisplay() && mStackSupervisor.resumeHomeStackTask(returnTaskType, prev, reason); } next.delayedResume = false; if (mResumedActivity == next && next.state == ActivityState.RESUMED && mStackSupervisor.allResumedActivitiesComplete()) { mWindowManager.executeAppTransition(); mNoAnimActivities.clear(); ActivityOptions.abort(options); return false; } final TaskRecord nextTask = next.task; if (prevTask != null && prevTask.stack == this && prevTask.isOverHomeStack() && prev.finishing && prev.frontOfTask) { if (prevTask == nextTask) { prevTask.setFrontOfTask(); } else if (prevTask != topTask()) { final int taskNdx = mTaskHistory.indexOf(prevTask) + 1; mTaskHistory.get(taskNdx).setTaskToReturnTo(HOME_ACTIVITY_TYPE); } else if (!isOnHomeDisplay()) { return false; } else if (!isHomeStack()){ final int returnTaskType = prevTask == null || !prevTask.isOverHomeStack() ? HOME_ACTIVITY_TYPE : prevTask.getTaskToReturnTo(); return isOnHomeDisplay() && mStackSupervisor.resumeHomeStackTask(returnTaskType, prev, "prevFinished"); } } //處於睡眠或者關機狀態,top activity已暫停的情況下 if (mService.isSleepingOrShuttingDown() && mLastPausedActivity == next && mStackSupervisor.allPausedActivitiesComplete()) { mWindowManager.executeAppTransition(); mNoAnimActivities.clear(); ActivityOptions.abort(options); return false; } if (mService.mStartedUsers.get(next.userId) == null) { return false; //擁有該activity的用戶沒有啟動則直接返回 } mStackSupervisor.mStoppingActivities.remove(next); mStackSupervisor.mGoingToSleepActivities.remove(next); next.sleeping = false; mStackSupervisor.mWaitingVisibleActivities.remove(next); mActivityTrigger.activityResumeTrigger(next.intent, next.info, next.appInfo); if (!mStackSupervisor.allPausedActivitiesComplete()) { return false; //當正處於暫停activity,則直接返回 } mStackSupervisor.setLaunchSource(next.info.applicationInfo.uid); //需要等待暫停當前activity完成,再resume top activity boolean dontWaitForPause = (next.info.flags&ActivityInfo.FLAG_RESUME_WHILE_PAUSING) != 0; //暫停其他Activity[見小節2.13.1] boolean pausing = mStackSupervisor.pauseBackStacks(userLeaving, true, dontWaitForPause); if (mResumedActivity != null) { //當前resumd狀態activity不為空,則需要先暫停該Activity pausing |= startPausingLocked(userLeaving, false, true, dontWaitForPause); } if (pausing) { if (next.app != null && next.app.thread != null) { mService.updateLruProcessLocked(next.app, true, null); } return true; } if (mService.isSleeping() && mLastNoHistoryActivity != null && !mLastNoHistoryActivity.finishing) { requestFinishActivityLocked(mLastNoHistoryActivity.appToken, Activity.RESULT_CANCELED, null, "resume-no-history", false); mLastNoHistoryActivity = null; } if (prev != null && prev != next) { if (!mStackSupervisor.mWaitingVisibleActivities.contains(prev) && next != null && !next.nowVisible) { mStackSupervisor.mWaitingVisibleActivities.add(prev); } else { if (prev.finishing) { mWindowManager.setAppVisibility(prev.appToken, false); } } } AppGlobals.getPackageManager().setPackageStoppedState( next.packageName, false, next.userId); boolean anim = true; if (mIsAnimationBoostEnabled == true && mPerf == null) { mPerf = new BoostFramework(); } if (prev != null) { if (prev.finishing) { if (mNoAnimActivities.contains(prev)) { anim = false; mWindowManager.prepareAppTransition(AppTransition.TRANSIT_NONE, false); } else { mWindowManager.prepareAppTransition(prev.task == next.task ? AppTransition.TRANSIT_ACTIVITY_CLOSE : AppTransition.TRANSIT_TASK_CLOSE, false); if(prev.task != next.task && mPerf != null) { mPerf.perfLockAcquire(aBoostTimeOut, aBoostParamVal); } } mWindowManager.setAppWillBeHidden(prev.appToken); mWindowManager.setAppVisibility(prev.appToken, false); } else { if (mNoAnimActivities.contains(next)) { anim = false; mWindowManager.prepareAppTransition(AppTransition.TRANSIT_NONE, false); } else { mWindowManager.prepareAppTransition(prev.task == next.task ? AppTransition.TRANSIT_ACTIVITY_OPEN : next.mLaunchTaskBehind ? AppTransition.TRANSIT_TASK_OPEN_BEHIND : AppTransition.TRANSIT_TASK_OPEN, false); if(prev.task != next.task && mPerf != null) { mPerf.perfLockAcquire(aBoostTimeOut, aBoostParamVal); } } } } else { if (mNoAnimActivities.contains(next)) { anim = false; mWindowManager.prepareAppTransition(AppTransition.TRANSIT_NONE, false); } else { mWindowManager.prepareAppTransition(AppTransition.TRANSIT_ACTIVITY_OPEN, false); } } Bundle resumeAnimOptions = null; if (anim) { ActivityOptions opts = next.getOptionsForTargetActivityLocked(); if (opts != null) { resumeAnimOptions = opts.toBundle(); } next.applyOptionsLocked(); } else { next.clearOptionsLocked(); } ActivityStack lastStack = mStackSupervisor.getLastStack(); //進程已存在的情況 if (next.app != null && next.app.thread != null) { //activity正在成為可見 mWindowManager.setAppVisibility(next.appToken, true); next.startLaunchTickingLocked(); ActivityRecord lastResumedActivity = lastStack == null ? null :lastStack.mResumedActivity; ActivityState lastState = next.state; mService.updateCpuStats(); //設置Activity狀態為resumed next.state = ActivityState.RESUMED; mResumedActivity = next; next.task.touchActiveTime(); mRecentTasks.addLocked(next.task); mService.updateLruProcessLocked(next.app, true, null); updateLRUListLocked(next); mService.updateOomAdjLocked(); boolean notUpdated = true; if (mStackSupervisor.isFrontStack(this)) { Configuration config = mWindowManager.updateOrientationFromAppTokens( mService.mConfiguration, next.mayFreezeScreenLocked(next.app) ? next.appToken : null); if (config != null) { next.frozenBeforeDestroy = true; } notUpdated = !mService.updateConfigurationLocked(config, next, false, false); } if (notUpdated) { ActivityRecord nextNext = topRunningActivityLocked(null); if (nextNext != next) { mStackSupervisor.scheduleResumeTopActivities(); } if (mStackSupervisor.reportResumedActivityLocked(next)) { mNoAnimActivities.clear(); return true; } return false; } try { //分發所有pending結果. ArrayList<ResultInfo> a = next.results; if (a != null) { final int N = a.size(); if (!next.finishing && N > 0) { next.app.thread.scheduleSendResult(next.appToken, a); } } if (next.newIntents != null) { next.app.thread.scheduleNewIntent(next.newIntents, next.appToken); } next.sleeping = false; mService.showAskCompatModeDialogLocked(next); next.app.pendingUiClean = true; next.app.forceProcessStateUpTo(mService.mTopProcessState); next.clearOptionsLocked(); //觸發onResume() next.app.thread.scheduleResumeActivity(next.appToken, next.app.repProcState, mService.isNextTransitionForward(), resumeAnimOptions); mStackSupervisor.checkReadyForSleepLocked(); } catch (Exception e) { ... return true; } next.visible = true; completeResumeLocked(next); next.stopped = false; } else { if (!next.hasBeenLaunched) { next.hasBeenLaunched = true; } else { if (SHOW_APP_STARTING_PREVIEW) { mWindowManager.setAppStartingWindow( next.appToken, next.packageName, next.theme, mService.compatibilityInfoForPackageLocked( next.info.applicationInfo), next.nonLocalizedLabel, next.labelRes, next.icon, next.logo, next.windowFlags, null, true); } } mStackSupervisor.startSpecificActivityLocked(next, true, true); } return true; } 

主要分支功能:

  • 當找不到需要resume的Activity,則直接回到桌面;
  • 否則,當mResumedActivity不為空,則執行startPausingLocked()暫停該activity;
  • 然后再進入startSpecificActivityLocked環節,接下來從這里繼續往下說。

2.13.1 ASS.pauseBackStacks

boolean pauseBackStacks(boolean userLeaving, boolean resuming, boolean dontWait) { boolean someActivityPaused = false; for (int displayNdx = mActivityDisplays.size() - 1; displayNdx >= 0; --displayNdx) { ArrayList<ActivityStack> stacks = mActivityDisplays.valueAt(displayNdx).mStacks; for (int stackNdx = stacks.size() - 1; stackNdx >= 0; --stackNdx) { final ActivityStack stack = stacks.get(stackNdx); if (!isFrontStack(stack) && stack.mResumedActivity != null) { //[見小節2.13.2] someActivityPaused |= stack.startPausingLocked(userLeaving, false, resuming, dontWait); } } } return someActivityPaused; } 

暫停所有處於后台棧的所有Activity。

2.13.2 AS.startPausingLocked

final boolean startPausingLocked(boolean userLeaving, boolean uiSleeping, boolean resuming, boolean dontWait) { if (mPausingActivity != null) { if (!mService.isSleeping()) { completePauseLocked(false); } } ActivityRecord prev = mResumedActivity; ... if (mActivityContainer.mParentActivity == null) { //暫停所有子棧的Activity mStackSupervisor.pauseChildStacks(prev, userLeaving, uiSleeping, resuming, dontWait); } ... final ActivityRecord next = mStackSupervisor.topRunningActivityLocked(); if (prev.app != null && prev.app.thread != null) { EventLog.writeEvent(EventLogTags.AM_PAUSE_ACTIVITY, prev.userId, System.identityHashCode(prev), prev.shortComponentName); mService.updateUsageStats(prev, false); //暫停目標Activity prev.app.thread.schedulePauseActivity(prev.appToken, prev.finishing, userLeaving, prev.configChangeFlags, dontWait); }else { ... } if (!uiSleeping && !mService.isSleepingOrShuttingDown()) { mStackSupervisor.acquireLaunchWakelock(); //申請wakelock } if (mPausingActivity != null) { if (!uiSleeping) { prev.pauseKeyDispatchingLocked(); } if (dontWait) { completePauseLocked(false); return false; } else { Message msg = mHandler.obtainMessage(PAUSE_TIMEOUT_MSG); msg.obj = prev; prev.pauseTime = SystemClock.uptimeMillis(); //500ms后,執行暫停超時的消息 mHandler.sendMessageDelayed(msg, PAUSE_TIMEOUT); return true; } } else { if (!resuming) { //調度暫停失敗,則認為已暫停完成,開始執行resume操作 mStackSupervisor.getFocusedStack().resumeTopActivityLocked(null); } return false; } 

該方法中,下一步通過Binder調用,進入acitivity所在進程來執行schedulePauseActivity()操作。 接下來,對於dontWait=true則執行執行completePauseLocked,否則等待app通知或許500ms超時再執行該方法。

3.13.3 completePauseLocked

2.14 ASS.startSpecificActivityLocked

void startSpecificActivityLocked(ActivityRecord r, boolean andResume, boolean checkConfig) { ProcessRecord app = mService.getProcessRecordLocked(r.processName, r.info.applicationInfo.uid, true); r.task.stack.setLaunchTime(r); if (app != null && app.thread != null) { try { if ((r.info.flags&ActivityInfo.FLAG_MULTIPROCESS) == 0 || !"android".equals(r.info.packageName)) { app.addPackage(r.info.packageName, r.info.applicationInfo.versionCode, mService.mProcessStats); } //真正的啟動Activity【見流程2.17】 realStartActivityLocked(r, app, andResume, checkConfig); return; } catch (RemoteException e) { Slog.w(TAG, "Exception when starting activity " + r.intent.getComponent().flattenToShortString(), e); } } //當進程不存在則創建進程 [見流程2.14.1] mService.startProcessLocked(r.processName, r.info.applicationInfo, true, 0, "activity", r.intent.getComponent(), false, false, true); } 

2.15 AMS.startProcessLocked

在文章理解Android進程啟動之全過程中,詳細介紹了AMS.startProcessLocked()整個過程,創建完新進程后會在新進程中調用AMP.attachApplication ,該方法經過binder ipc后調用到AMS.attachApplicationLocked

private final boolean attachApplicationLocked(IApplicationThread thread, int pid) { ... ////只有當系統啟動完,或者app允許啟動過程允許,則會true boolean normalMode = mProcessesReady || isAllowedWhileBooting(app.info); thread.bindApplication(...); if (normalMode) { //【見流程2.16】 if (mStackSupervisor.attachApplicationLocked(app)) { didSomething = true; } } ... } 

在執行完bindApplication()之后進入ASS.attachApplicationLocked()

2.16 ASS.attachApplicationLocked

boolean attachApplicationLocked(ProcessRecord app) throws RemoteException { final String processName = app.processName; boolean didSomething = false; for (int displayNdx = mActivityDisplays.size() - 1; displayNdx >= 0; --displayNdx) { ArrayList<ActivityStack> stacks = mActivityDisplays.valueAt(displayNdx).mStacks; for (int stackNdx = stacks.size() - 1; stackNdx >= 0; --stackNdx) { final ActivityStack stack = stacks.get(stackNdx); if (!isFrontStack(stack)) { continue; } //獲取前台stack中棧頂第一個非finishing的Activity ActivityRecord hr = stack.topRunningActivityLocked(null); if (hr != null) { if (hr.app == null && app.uid == hr.info.applicationInfo.uid && processName.equals(hr.processName)) { try { //真正的啟動Activity【見流程2.17】 if (realStartActivityLocked(hr, app, true, true)) { didSomething = true; } } catch (RemoteException e) { throw e; } } } } } if (!didSomething) { //啟動Activity不成功,則確保有可見的Activity ensureActivitiesVisibleLocked(null, 0); } return didSomething; } 

2.17 ASS.realStartActivityLocked

final boolean realStartActivityLocked(ActivityRecord r, ProcessRecord app, boolean andResume, boolean checkConfig) throws RemoteException { if (andResume) { r.startFreezingScreenLocked(app, 0); mWindowManager.setAppVisibility(r.appToken, true); //調度啟動ticks用以收集應用啟動慢的信息 r.startLaunchTickingLocked(); } if (checkConfig) { Configuration config = mWindowManager.updateOrientationFromAppTokens( mService.mConfiguration, r.mayFreezeScreenLocked(app) ? r.appToken : null); //更新Configuration mService.updateConfigurationLocked(config, r, false, false); } r.app = app; app.waitingToKill = null; r.launchCount++; r.lastLaunchTime = SystemClock.uptimeMillis(); int idx = app.activities.indexOf(r); if (idx < 0) { app.activities.add(r); } mService.updateLruProcessLocked(app, true, null); mService.updateOomAdjLocked(); final TaskRecord task = r.task; if (task.mLockTaskAuth == LOCK_TASK_AUTH_LAUNCHABLE || task.mLockTaskAuth == LOCK_TASK_AUTH_LAUNCHABLE_PRIV) { setLockTaskModeLocked(task, LOCK_TASK_MODE_LOCKED, "mLockTaskAuth==LAUNCHABLE", false); } final ActivityStack stack = task.stack; try { if (app.thread == null) { throw new RemoteException(); } List<ResultInfo> results = null; List<ReferrerIntent> newIntents = null; if (andResume) { results = r.results; newIntents = r.newIntents; } if (r.isHomeActivity() && r.isNotResolverActivity()) { //home進程是該棧的根進程 mService.mHomeProcess = task.mActivities.get(0).app; } mService.ensurePackageDexOpt(r.intent.getComponent().getPackageName()); ... if (andResume) { app.hasShownUi = true; app.pendingUiClean = true; } //將該進程設置為前台進程PROCESS_STATE_TOP app.forceProcessStateUpTo(mService.mTopProcessState); //【見流程2.18】 app.thread.scheduleLaunchActivity(new Intent(r.intent), r.appToken, System.identityHashCode(r), r.info, new Configuration(mService.mConfiguration), new Configuration(stack.mOverrideConfig), r.compat, r.launchedFromPackage, task.voiceInteractor, app.repProcState, r.icicle, r.persistentState, results, newIntents, !andResume, mService.isNextTransitionForward(), profilerInfo); if ((app.info.privateFlags&ApplicationInfo.PRIVATE_FLAG_CANT_SAVE_STATE) != 0) { ... //處理heavy-weight進程 } } catch (RemoteException e) { if (r.launchFailed) { //第二次啟動失敗,則結束該activity mService.appDiedLocked(app); stack.requestFinishActivityLocked(r.appToken, Activity.RESULT_CANCELED, null, "2nd-crash", false); return false; } //這是第一個啟動失敗,則重啟進程 app.activities.remove(r); throw e; } //將該進程加入到mLRUActivities隊列頂部 stack.updateLRUListLocked(r); if (andResume) { //啟動過程的一部分 stack.minimalResumeActivityLocked(r); } else { r.state = STOPPED; r.stopped = true; } if (isFrontStack(stack)) { //當系統發生更新時,只會執行一次的用戶向導 mService.startSetupActivityLocked(); } //更新所有與該Activity具有綁定關系的Service連接 mService.mServices.updateServiceConnectionActivitiesLocked(r.app); return true; } 

2.18 ATP.scheduleLaunchActivity

[-> ApplicationThreadProxy.java]

public final void scheduleLaunchActivity(Intent intent, IBinder token, int ident, ActivityInfo info, Configuration curConfig, Configuration overrideConfig, CompatibilityInfo compatInfo, String referrer, IVoiceInteractor voiceInteractor, int procState, Bundle state, PersistableBundle persistentState, List<ResultInfo> pendingResults, List<ReferrerIntent> pendingNewIntents, boolean notResumed, boolean isForward, ProfilerInfo profilerInfo) throws RemoteException { Parcel data = Parcel.obtain(); data.writeInterfaceToken(IApplicationThread.descriptor); intent.writeToParcel(data, 0); data.writeStrongBinder(token); data.writeInt(ident); info.writeToParcel(data, 0); curConfig.writeToParcel(data, 0); if (overrideConfig != null) { data.writeInt(1); overrideConfig.writeToParcel(data, 0); } else { data.writeInt(0); } compatInfo.writeToParcel(data, 0); data.writeString(referrer); data.writeStrongBinder(voiceInteractor != null ? voiceInteractor.asBinder() : null); data.writeInt(procState); data.writeBundle(state); data.writePersistableBundle(persistentState); data.writeTypedList(pendingResults); data.writeTypedList(pendingNewIntents); data.writeInt(notResumed ? 1 : 0); data.writeInt(isForward ? 1 : 0); if (profilerInfo != null) { data.writeInt(1); profilerInfo.writeToParcel(data, Parcelable.PARCELABLE_WRITE_RETURN_VALUE); } else { data.writeInt(0); } //【見流程2.19】 mRemote.transact(SCHEDULE_LAUNCH_ACTIVITY_TRANSACTION, data, null, IBinder.FLAG_ONEWAY); data.recycle(); } 

2.19 ATN.onTransact

[-> ApplicationThreadNative.java]

public boolean onTransact(int code, Parcel data, Parcel reply, int flags) throws RemoteException { switch (code) { case SCHEDULE_LAUNCH_ACTIVITY_TRANSACTION: { data.enforceInterface(IApplicationThread.descriptor); Intent intent = Intent.CREATOR.createFromParcel(data); IBinder b = data.readStrongBinder(); int ident = data.readInt(); ActivityInfo info = ActivityInfo.CREATOR.createFromParcel(data); Configuration curConfig = Configuration.CREATOR.createFromParcel(data); Configuration overrideConfig = null; if (data.readInt() != 0) { overrideConfig = Configuration.CREATOR.createFromParcel(data); } CompatibilityInfo compatInfo = CompatibilityInfo.CREATOR.createFromParcel(data); String referrer = data.readString(); IVoiceInteractor voiceInteractor = IVoiceInteractor.Stub.asInterface( data.readStrongBinder()); int procState = data.readInt(); Bundle state = data.readBundle(); PersistableBundle persistentState = data.readPersistableBundle(); List<ResultInfo> ri = data.createTypedArrayList(ResultInfo.CREATOR); List<ReferrerIntent> pi = data.createTypedArrayList(ReferrerIntent.CREATOR); boolean notResumed = data.readInt() != 0; boolean isForward = data.readInt() != 0; ProfilerInfo profilerInfo = data.readInt() != 0 ? ProfilerInfo.CREATOR.createFromParcel(data) : null; //【見流程2.20】 scheduleLaunchActivity(intent, b, ident, info, curConfig, overrideConfig, compatInfo, referrer, voiceInteractor, procState, state, persistentState, ri, pi, notResumed, isForward, profilerInfo); return true; } ... } } 

2.20 AT.scheduleLaunchActivity

[-> ApplicationThread.java]

public final void scheduleLaunchActivity(Intent intent, IBinder token, int ident, ActivityInfo info, Configuration curConfig, Configuration overrideConfig, CompatibilityInfo compatInfo, String referrer, IVoiceInteractor voiceInteractor, int procState, Bundle state, PersistableBundle persistentState, List<ResultInfo> pendingResults, List<ReferrerIntent> pendingNewIntents, boolean notResumed, boolean isForward, ProfilerInfo profilerInfo) { updateProcessState(procState, false); ActivityClientRecord r = new ActivityClientRecord(); r.token = token; r.ident = ident; r.intent = intent; r.referrer = referrer; r.voiceInteractor = voiceInteractor; r.activityInfo = info; r.compatInfo = compatInfo; r.state = state; r.persistentState = persistentState; r.pendingResults = pendingResults; r.pendingIntents = pendingNewIntents; r.startsNotResumed = notResumed; r.isForward = isForward; r.profilerInfo = profilerInfo; r.overrideConfig = overrideConfig; updatePendingConfiguration(curConfig); //【見流程2.21】 sendMessage(H.LAUNCH_ACTIVITY, r); } 

2.21 H.handleMessage

[-> ActivityThread.java ::H]

public void handleMessage(Message msg) { switch (msg.what) { case LAUNCH_ACTIVITY: { final ActivityClientRecord r = (ActivityClientRecord) msg.obj; r.packageInfo = getPackageInfoNoCheck( r.activityInfo.applicationInfo, r.compatInfo); //【見流程2.22】 handleLaunchActivity(r, null); } break; ... } } 

2.22 ActivityThread.handleLaunchActivity

[-> ActivityThread.java]

private void handleLaunchActivity(ActivityClientRecord r, Intent customIntent) { unscheduleGcIdler(); mSomeActivitiesChanged = true; //最終回調目標Activity的onConfigurationChanged() handleConfigurationChanged(null, null); //初始化wms WindowManagerGlobal.initialize(); //最終回調目標Activity的onCreate[見流程2.23] Activity a = performLaunchActivity(r, customIntent); if (a != null) { r.createdConfig = new Configuration(mConfiguration); Bundle oldState = r.state; //最終回調目標Activity的onStart,onResume. handleResumeActivity(r.token, false, r.isForward, !r.activity.mFinished && !r.startsNotResumed); if (!r.activity.mFinished && r.startsNotResumed) { r.activity.mCalled = false; mInstrumentation.callActivityOnPause(r.activity); r.paused = true; } } else { //存在error則停止該Activity ActivityManagerNative.getDefault() .finishActivity(r.token, Activity.RESULT_CANCELED, null, false); } } 

2.23 ActivityThread.performLaunchActivity

[-> 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); } Activity activity = null; try { java.lang.ClassLoader cl = r.packageInfo.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對象 Application app = r.packageInfo.makeApplication(false, mInstrumentation); if (activity != null) { Context appContext = createBaseContextForActivity(r, activity); CharSequence title = r.activityInfo.loadLabel(appContext.getPackageManager()); Configuration config = new Configuration(mCompatConfiguration); 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); if (customIntent != null) { activity.mIntent = customIntent; } r.lastNonConfigurationInstances = null; 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); } ... r.activity = activity; r.stopped = true; if (!r.activity.mFinished) { activity.performStart(); r.stopped = false; } if (!r.activity.mFinished) { if (r.isPersistable()) { if (r.state != null || r.persistentState != null) { mInstrumentation.callActivityOnRestoreInstanceState(activity, r.state, r.persistentState); } } else if (r.state != null) { mInstrumentation.callActivityOnRestoreInstanceState(activity, r.state); } } if (!r.activity.mFinished) { activity.mCalled = false; if (r.isPersistable()) { mInstrumentation.callActivityOnPostCreate(activity, r.state, r.persistentState); } else { mInstrumentation.callActivityOnPostCreate(activity, r.state); } ... } } r.paused = true; mActivities.put(r.token, r); } catch (Exception e) { ... } return activity; } 

到此,正式進入了Activity的onCreate, onStart, onResume這些生命周期的過程。

三. 總結

本文詳細startActivity的整個啟動流程,

  • 流程[2.1 ~2.4]:運行在調用者所在進程,比如從桌面啟動Activity,則調用者所在進程為launcher進程,launcher進程利用ActivityManagerProxy作為Binder Client,進入system_server進程(AMS相應的Server端)。
  • 流程[2.5 ~2.18]:運行在system_server系統進程,整個過程最為復雜、核心的過程,下面其中部分步驟:
    • 流程[2.7]:會調用到resolveActivity(),借助PackageManager來查詢系統中所有符合要求的Activity,當存在多個滿足條件的Activity則會彈框讓用戶來選擇;
    • 流程[2.8]:創建ActivityRecord對象,並檢查是否運行App切換,然后再處理mPendingActivityLaunches中的activity;
    • 流程[2.9]:為Activity找到或創建新的Task對象,設置flags信息;
    • 流程[2.13]:當沒有處於非finishing狀態的Activity,則直接回到桌面; 否則,當mResumedActivity不為空則執行startPausingLocked()暫停該activity;然后再進入startSpecificActivityLocked()環節;
    • 流程[2.14]:當目標進程已存在則直接進入流程[2.17],當進程不存在則創建進程,經過層層調用還是會進入流程[2.17];
    • 流程[2.17]:system_server進程利用的ATP(Binder Client),經過Binder,程序接下來進入目標進程。
  • 流程[2.19 ~2.18]:運行在目標進程,通過Handler消息機制,該進程中的Binder線程向主線程發送H.LAUNCH_ACTIVITY,最終會通過反射創建目標Activity,然后進入onCreate()生命周期。

從另一個角度下圖來概括:

start_activity_process

啟動流程:

  1. 點擊桌面App圖標,Launcher進程采用Binder IPC向system_server進程發起startActivity請求;
  2. system_server進程接收到請求后,向zygote進程發送創建進程的請求;
  3. Zygote進程fork出新的子進程,即App進程;
  4. App進程,通過Binder IPC向sytem_server進程發起attachApplication請求;
  5. system_server進程在收到請求后,進行一系列准備工作后,再通過binder IPC向App進程發送scheduleLaunchActivity請求;
  6. App進程的binder線程(ApplicationThread)在收到請求后,通過handler向主線程發送LAUNCH_ACTIVITY消息;
  7. 主線程在收到Message后,通過發射機制創建目標Activity,並回調Activity.onCreate()等方法。

到此,App便正式啟動,開始進入Activity生命周期,執行完onCreate/onStart/onResume方法,UI渲染結束后便可以看到App的主界面。 啟動Activity較為復雜,后續計划再進一步講解生命周期過程與系統是如何交互,以及UI渲染過程,敬請期待。

 

 

轉自:http://gityuan.com/2016/03/12/start-activity/


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM