了解Activity啟動過程,從startActivity到ATMS的高效協(xié)作
在Android系統(tǒng)中,啟動一個Activity無論是從應(yīng)用內(nèi)部啟動Activity,還是通過桌面程序(Launcher)啟動,都需要通過調(diào)用startActivity方法來發(fā)起啟動請求。
啟動請求的發(fā)起
- 「應(yīng)用內(nèi)部啟動Activity」:
當(dāng)應(yīng)用內(nèi)部需要啟動一個新的Activity時,開發(fā)者會調(diào)用startActivity方法,并傳遞一個包含目標(biāo)Activity信息的Intent對象。
這個Intent對象可以指定要啟動的Activity的類名、傳遞的數(shù)據(jù)、附加的extras等。
調(diào)用startActivity后,系統(tǒng)會開始處理啟動請求,并按照Activity啟動流程進行后續(xù)操作。
- 「Launcher啟動Activity」:
Launcher是Android系統(tǒng)的桌面程序,它負(fù)責(zé)顯示已安裝的應(yīng)用程序圖標(biāo),并提供用戶與應(yīng)用程序交互的入口。
當(dāng)用戶從Launcher點擊一個應(yīng)用程序圖標(biāo)時,Launcher會創(chuàng)建一個新的Intent,用于啟動該應(yīng)用程序的主Activity(通常是根Activity)。
然后,Launcher調(diào)用startActivity方法,并將該Intent傳遞給系統(tǒng),以啟動目標(biāo)Activity。
在兩種情況下,啟動請求的發(fā)起都是通過調(diào)用startActivity方法實現(xiàn)的。這個方法會觸發(fā)一系列的操作,包括將啟動請求傳遞給ActivityTaskManagerService(ATMS),進行線程切換和消息處理,以及最終完成Activity的初始化和顯示。無論是startActivity還是startActivityForResult最終都是調(diào)用startActivityForResult。
圖片
public class Activity extends ContextThemeWrapper
implements LayoutInflater.Factory2,
Window.Callback, KeyEvent.Callback,
OnCreateContextMenuListener, ComponentCallbacks2,
Window.OnWindowDismissedCallback,
AutofillManager.AutofillClient, ContentCaptureManager.ContentCaptureClient {
@Override
public void startActivity(Intent intent, @Nullable Bundle options) {
//...
if (options != null) {
startActivityForResult(intent, -1, options);
} else {
startActivityForResult(intent, -1);
}
}
public void startActivityForResult(@RequiresPermission Intent intent, int requestCode,
@Nullable Bundle options) {
// mParent 是Activity類型,是當(dāng)前Activity的父類
if (mParent == null) {
options = transferSpringboardActivityOptions(options);
// 調(diào)用Instrumentation.execStartActivity啟動activity
Instrumentation.ActivityResult ar =
mInstrumentation.execStartActivity(
this, mMainThread.getApplicationThread(), mToken, this,
intent, requestCode, options);
//...
} else {
//...
}
}
}
startActivityForResult中調(diào)用Instrumentation.execStartActivity方法。Activity中的mInstrumentation是在attach()方法中初始化,由ActivityThread傳入,其作用是通過遠(yuǎn)程服務(wù)調(diào)用啟動activity,連接ActivityThread與activity,處理activity生命周期回調(diào)。
// Instrumentation主要用來監(jiān)控應(yīng)用程序和系統(tǒng)的交互,比如調(diào)用ATMS啟動activity,回調(diào)生命周期
public class Instrumentation {
public ActivityResult execStartActivity(
Context who, IBinder contextThread, IBinder token, Activity target,
Intent intent, int requestCode, Bundle options) {
//...
try {
//...
// 通過ATMS遠(yuǎn)程調(diào)用startActivity
int result = ActivityTaskManager.getService().startActivity(whoThread,
who.getOpPackageName(), who.getAttributionTag(), 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;
}
/**
* 根據(jù)result判斷當(dāng)前能否啟動activity,不能則拋出異常
*/
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)
// 沒有在manifest中聲明
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);
}
}
}
@SystemService(Context.ACTIVITY_TASK_SERVICE)
public class ActivityTaskManager {
/**
* IActivityTaskManager是一個Binder,用于和system_server進程中的ActivityTaskManagerService通信
*/
public static IActivityTaskManager getService() {
return IActivityTaskManagerSingleton.get();
}
private static final Singleton<IActivityTaskManager> IActivityTaskManagerSingleton =
new Singleton<IActivityTaskManager>() {
@Override
protected IActivityTaskManager create() {
final IBinder b = ServiceManager.getService(Context.ACTIVITY_TASK_SERVICE);
return IActivityTaskManager.Stub.asInterface(b);
}
};
}
當(dāng)請求到達(dá)ATMS時,ATMS會首先檢查該請求是否合法,包括檢查Intent的有效性、權(quán)限等。一旦請求被驗證為有效,ATMS會進一步處理這個請求。
處理過程中,ATMS會根據(jù)當(dāng)前系統(tǒng)的狀態(tài)和任務(wù)棧的情況來決定如何響應(yīng)這個啟動請求。例如,它可能會決定創(chuàng)建一個新的Activity實例,或者將已存在的Activity實例帶到前臺。ATMS還會與ActivityManagerService(AMS)進行交互,以協(xié)調(diào)應(yīng)用程序組件的生命周期管理。AMS負(fù)責(zé)跟蹤和管理這些組件的生命周期,確保它們按照預(yù)期的方式運行。
Activity的初始化與生命周期管理
當(dāng)Activity啟動請求到達(dá)ActivityTaskManagerService(ATMS)并被驗證為有效后,ATMS會通知相應(yīng)的應(yīng)用進程進行Activity的初始化。
// /frameworks/base/services/core/java/com/android/server/wm/ActivityTaskManagerService.java
public class ActivityTaskManagerService extends IActivityTaskManager.Stub {
public final int startActivity(IApplicationThread caller, String callingPackage,
String callingFeatureId, Intent intent, String resolvedType, IBinder resultTo,
String resultWho, int requestCode, int startFlags, ProfilerInfo profilerInfo,
Bundle bOptions) {
return startActivityAsUser(caller, callingPackage, callingFeatureId, intent, resolvedType,
resultTo, resultWho, requestCode, startFlags, profilerInfo, bOptions,
UserHandle.getCallingUserId());
}
private int startActivityAsUser(IApplicationThread caller, String callingPackage,
@Nullable String callingFeatureId, Intent intent, String resolvedType,
IBinder resultTo, String resultWho, int requestCode, int startFlags,
ProfilerInfo profilerInfo, Bundle bOptions, int userId, boolean validateIncomingUser) {
assertPackageMatchesCallingUid(callingPackage);
// 判斷調(diào)用者進程是否被隔離
enforceNotIsolatedCaller("startActivityAsUser");
// 檢查調(diào)用者權(quán)限
userId = getActivityStartController().checkTargetUser(userId, validateIncomingUser,
Binder.getCallingPid(), Binder.getCallingUid(), "startActivityAsUser");
return getActivityStartController().obtainStarter(intent, "startActivityAsUser")
.setCaller(caller)
.setCallingPackage(callingPackage)
.setCallingFeatureId(callingFeatureId)
.setResolvedType(resolvedType)
.setResultTo(resultTo)
.setResultWho(resultWho)
.setRequestCode(requestCode)
.setStartFlags(startFlags)
.setProfilerInfo(profilerInfo)
.setActivityOptions(bOptions)
.setUserId(userId)
.execute();
}
}
ATMS通過一系列方法最終調(diào)到startActivityAsUser方法,先檢查調(diào)用者權(quán)限,再通過getActivityStartController().obtainStarter創(chuàng)建ActivityStarter類,把參數(shù)設(shè)置到ActivityStarter.Request類中,最后執(zhí)行ActivityStarter.execute()方法。
// /frameworks/base/services/core/java/com/android/server/wm/ActivityStarter.java
class ActivityStarter {
int execute() {
try {
//...
int res;
synchronized (mService.mGlobalLock) {
//...
res = executeRequest(mRequest);
//...
}
} finally {
onExecutionComplete();
}
}
private int executeRequest(Request request) {
// 判斷啟動的理由不為空
if (TextUtils.isEmpty(request.reason)) {
throw new IllegalArgumentException("Need to specify a reason.");
}
// 獲取調(diào)用的進程
WindowProcessController callerApp = null;
if (caller != null) {
callerApp = mService.getProcessController(caller);
if (callerApp != null) {
// 獲取調(diào)用進程的pid和uid并賦值
callingPid = callerApp.getPid();
callingUid = callerApp.mInfo.uid;
} else {
err = ActivityManager.START_PERMISSION_DENIED;
}
}
final int userId = aInfo != null && aInfo.applicationInfo != null
? UserHandle.getUserId(aInfo.applicationInfo.uid) : 0;
ActivityRecord sourceRecord = null;
ActivityRecord resultRecord = null;
if (resultTo != null) {
// 獲取調(diào)用者所在的ActivityRecord
sourceRecord = mRootWindowContainer.isInAnyStack(resultTo);
if (sourceRecord != null) {
if (requestCode >= 0 && !sourceRecord.finishing) {
//requestCode = -1 則不進入
resultRecord = sourceRecord;
}
}
}
final int launchFlags = intent.getFlags();
if ((launchFlags & Intent.FLAG_ACTIVITY_FORWARD_RESULT) != 0 && sourceRecord != null) {
// activity執(zhí)行結(jié)果的返回由源Activity轉(zhuǎn)換到新Activity, 不需要返回結(jié)果則不會進入該分支
}
if (err == ActivityManager.START_SUCCESS && intent.getComponent() == null) {
// 從Intent中無法找到相應(yīng)的Component
err = ActivityManager.START_INTENT_NOT_RESOLVED;
}
if (err == ActivityManager.START_SUCCESS && aInfo == null) {
// 從Intent中無法找到相應(yīng)的ActivityInfo
err = ActivityManager.START_CLASS_NOT_FOUND;
}
//執(zhí)行后resultStack = null
final ActivityStack resultStack = resultRecord == null
? null : resultRecord.getRootTask();
//權(quán)限檢查
if (mService.mController != null) {
try {
Intent watchIntent = intent.cloneFilter();
abort |= !mService.mController.activityStarting(watchIntent,
aInfo.applicationInfo.packageName);
} catch (RemoteException e) {
mService.mController = null;
}
}
if (abort) {
//權(quán)限檢查不滿足,才進入該分支則直接返回;
return START_ABORTED;
if (aInfo != null) {
if (mService.getPackageManagerInternalLocked().isPermissionsReviewRequired(
aInfo.packageName, userId)) {
// 向PKMS獲取啟動Activity的ResolveInfo
rInfo = mSupervisor.resolveIntent(intent, resolvedType, userId, 0,
computeResolveFilterUid(
callingUid, realCallingUid, request.filterCallingUid));
// 向PKMS獲取啟動Activity的ActivityInfo
aInfo = mSupervisor.resolveActivity(intent, rInfo, startFlags,
null /*profilerInfo*/);
}
}
// 創(chuàng)建即將要啟動的Activity的描述類ActivityRecord
final ActivityRecord r = new ActivityRecord(mService, callerApp, callingPid, callingUid,
callingPackage, callingFeatureId, intent, resolvedType, aInfo,
mService.getGlobalConfiguration(), resultRecord, resultWho, requestCode,
request.componentSpecified, voiceSession != null, mSupervisor, checkedOptions,
sourceRecord);
mLastStartActivityRecord = r;
// 調(diào)用 startActivityUnchecked
mLastStartActivityResult = startActivityUnchecked(r, sourceRecord, voiceSession,
request.voiceInteractor, startFlags, true /* doResume */, checkedOptions, inTask,
restrictedBgActivity, intentGrants);
if (request.outActivity != null) {
request.outActivity[0] = mLastStartActivityRecord;
}
return mLastStartActivityResult;
}
}
在ActivityStarter中調(diào)用executeRequest方法,先做一系列檢查,包括進程檢查、intent檢查、權(quán)限檢查、向PKMS獲取啟動Activity的ActivityInfo等信息,調(diào)用startActivityUnchecked方法開始對要啟動的activity進行任務(wù)棧管理。
private int startActivityUnchecked(final ActivityRecord r, ActivityRecord sourceRecord,
IVoiceInteractionSession voiceSession, IVoiceInteractor voiceInteractor,
int startFlags, boolean doResume, ActivityOptions options, Task inTask,
boolean restrictedBgActivity, NeededUriGrants intentGrants) {
try {
result = startActivityInner(r, sourceRecord, voiceSession, voiceInteractor,
startFlags, doResume, options, inTask, restrictedBgActivity, intentGrants);
} finally {
//...
}
//...
return result;
}
ActivityRecord mStartActivity;
private ActivityStack mSourceStack;
private ActivityStack mTargetStack;
private Task mTargetTask;
// 主要處理棧管理相關(guān)的邏輯
int startActivityInner(final ActivityRecord r, ActivityRecord sourceRecord,
IVoiceInteractionSession voiceSession, IVoiceInteractor voiceInteractor,
int startFlags, boolean doResume, ActivityOptions options, Task inTask,
boolean restrictedBgActivity, NeededUriGrants intentGrants) {
// 初始化啟動Activity的各種配置,在初始化前會重置各種配置再進行配置,
// 這些配置包括:ActivityRecord、Intent、Task和LaunchFlags(啟動的FLAG)等等
setInitialState(r, options, inTask, doResume, startFlags, sourceRecord, voiceSession,
voiceInteractor, restrictedBgActivity);
// 給不同的啟動模式計算出mLaunchFlags
computeLaunchingTaskFlags();
// 主要作用是設(shè)置ActivityStack
computeSourceStack();
// 將mLaunchFlags設(shè)置給Intent
mIntent.setFlags(mLaunchFlags);
// 確定是否應(yīng)將新活動插入現(xiàn)有任務(wù)。如果不是,則返回null,
// 或者返回帶有應(yīng)將新活動添加到其中的任務(wù)的ActivityRecord。
final Task reusedTask = getReusableTask();
// 如果reusedTask為null,則計算是否存在可以使用的任務(wù)棧
final Task targetTask = reusedTask != null ? reusedTask : computeTargetTask();
final boolean newTask = targetTask == null; // 啟動Activity是否需要新創(chuàng)建棧
mTargetTask = targetTask;
computeLaunchParams(r, sourceRecord, targetTask);
// 檢查是否允許在給定任務(wù)或新任務(wù)上啟動活動。
int startResult = isAllowedToStart(r, newTask, targetTask);
if (startResult != START_SUCCESS) {
return startResult;
}
final ActivityStack topStack = mRootWindowContainer.getTopDisplayFocusedStack();
if (topStack != null) {
// 檢查正在啟動的活動是否與當(dāng)前位于頂部的活動相同,并且應(yīng)該只啟動一次
startResult = deliverToCurrentTopIfNeeded(topStack, intentGrants);
if (startResult != START_SUCCESS) {
return startResult;
}
}
if (mTargetStack == null) {
// 復(fù)用或者創(chuàng)建堆棧
mTargetStack = getLaunchStack(mStartActivity, mLaunchFlags, targetTask, mOptions);
}
if (newTask) {
// 新建一個task
final Task taskToAffiliate = (mLaunchTaskBehind && mSourceRecord != null)
? mSourceRecord.getTask() : null;
setNewTask(taskToAffiliate);
if (mService.getLockTaskController().isLockTaskModeViolation(
mStartActivity.getTask())) {
Slog.e(TAG, "Attempted Lock Task Mode violation mStartActivity=" + mStartActivity);
return START_RETURN_LOCK_TASK_MODE_VIOLATION;
}
} else if (mAddingToTask) {
// 復(fù)用之前的task
addOrReparentStartingActivity(targetTask, "adding to task");
}
// 檢查是否需要觸發(fā)過渡動畫和開始窗口
mTargetStack.startActivityLocked(mStartActivity,
topStack != null ? topStack.getTopNonFinishingActivity() : null, newTask,
mKeepCurTransition, mOptions);
if (mDoResume) {
// 調(diào)用RootWindowContainer的resumeFocusedStacksTopActivities方法
mRootWindowContainer.resumeFocusedStacksTopActivities(
mTargetStack, mStartActivity, mOptions);
}
return START_SUCCESS;
}
private void setInitialState(ActivityRecord r, ActivityOptions options, Task inTask,
boolean doResume, int startFlags, ActivityRecord sourceRecord,
IVoiceInteractionSession voiceSession, IVoiceInteractor voiceInteractor,
boolean restrictedBgActivity) {
reset(false /* clearRequest */);
mStartActivity = r;
mIntent = r.intent;
mSourceRecord = sourceRecord;
mLaunchMode = r.launchMode;
// 啟動Flags
mLaunchFlags = adjustLaunchFlagsToDocumentMode(
r, LAUNCH_SINGLE_INSTANCE == mLaunchMode,
LAUNCH_SINGLE_TASK == mLaunchMode, mIntent.getFlags());
mInTask = inTask;
// ...
}
private void computeLaunchingTaskFlags() {
if (mInTask == null) {
if (mSourceRecord == null) {
if ((mLaunchFlags & FLAG_ACTIVITY_NEW_TASK) == 0 && mInTask == null) {
mLaunchFlags |= FLAG_ACTIVITY_NEW_TASK;
}
} else if (mSourceRecord.launchMode == LAUNCH_SINGLE_INSTANCE) {
mLaunchFlags |= FLAG_ACTIVITY_NEW_TASK;
} else if (isLaunchModeOneOf(LAUNCH_SINGLE_INSTANCE, LAUNCH_SINGLE_TASK)) {
mLaunchFlags |= FLAG_ACTIVITY_NEW_TASK;
}
}
}
// 設(shè)置ActivityStack
private void computeSourceStack() {
if (mSourceRecord == null) {
mSourceStack = null;
return;
}
if (!mSourceRecord.finishing) {
mSourceStack = mSourceRecord.getRootTask();
return;
}
if ((mLaunchFlags & FLAG_ACTIVITY_NEW_TASK) == 0) {
mLaunchFlags |= FLAG_ACTIVITY_NEW_TASK;
mNewTaskInfo = mSourceRecord.info;
final Task sourceTask = mSourceRecord.getTask();
mNewTaskIntent = sourceTask != null ? sourceTask.intent : null;
}
mSourceRecord = null;
mSourceStack = null;
}
private Task getReusableTask() {
// If a target task is specified, try to reuse that one
if (mOptions != null && mOptions.getLaunchTaskId() != INVALID_TASK_ID) {
Task launchTask = mRootWindowContainer.anyTaskForId(mOptions.getLaunchTaskId());
if (launchTask != null) {
return launchTask;
}
return null;
}
//標(biāo)志位,如果為true,說明要放入已經(jīng)存在的棧,
// 可以看出,如果是設(shè)置了FLAG_ACTIVITY_NEW_TASK 而沒有設(shè)置 FLAG_ACTIVITY_MULTIPLE_TASK,
// 或者設(shè)置了singleTask以及singleInstance
boolean putIntoExistingTask = ((mLaunchFlags & FLAG_ACTIVITY_NEW_TASK) != 0 &&
(mLaunchFlags & FLAG_ACTIVITY_MULTIPLE_TASK) == 0)
|| isLaunchModeOneOf(LAUNCH_SINGLE_INSTANCE, LAUNCH_SINGLE_TASK);
// 重新檢驗
putIntoExistingTask &= mInTask == null && mStartActivity.resultTo == null;
ActivityRecord intentActivity = null;
if (putIntoExistingTask) {
if (LAUNCH_SINGLE_INSTANCE == mLaunchMode) {
//如果是 singleInstance,那么就找看看之前存在的該實例,找不到就為null
intentActivity = mRootWindowContainer.findActivity(mIntent, mStartActivity.info,
mStartActivity.isActivityTypeHome());
} else if ((mLaunchFlags & FLAG_ACTIVITY_LAUNCH_ADJACENT) != 0) {
// For the launch adjacent case we only want to put the activity in an existing
// task if the activity already exists in the history.
intentActivity = mRootWindowContainer.findActivity(mIntent, mStartActivity.info,
!(LAUNCH_SINGLE_TASK == mLaunchMode));
} else {
// Otherwise find the best task to put the activity in.
intentActivity =
mRootWindowContainer.findTask(mStartActivity, mPreferredTaskDisplayArea);
}
}
if (intentActivity != null
&& (mStartActivity.isActivityTypeHome() || intentActivity.isActivityTypeHome())
&& intentActivity.getDisplayArea() != mPreferredTaskDisplayArea) {
// Do not reuse home activity on other display areas.
intentActivity = null;
}
return intentActivity != null ? intentActivity.getTask() : null;
}
// 計算啟動的Activity的棧
private Task computeTargetTask() {
if (mStartActivity.resultTo == null && mInTask == null && !mAddingToTask
&& (mLaunchFlags & FLAG_ACTIVITY_NEW_TASK) != 0) {
// 返回null,應(yīng)該新創(chuàng)建一個Task,而不是使用現(xiàn)有的Task
return null;
} else if (mSourceRecord != null) {
// 使用源Activity的task
return mSourceRecord.getTask();
} else if (mInTask != null) {
// 使用啟動時傳遞的task
return mInTask;
} else {
// 理論上的可能,不可能走到這里
final ActivityStack stack = getLaunchStack(mStartActivity, mLaunchFlags,
null /* task */, mOptions);
final ActivityRecord top = stack.getTopNonFinishingActivity();
if (top != null) {
return top.getTask();
} else {
// Remove the stack if no activity in the stack.
stack.removeIfPossible();
}
}
return null;
}
在startActivityInner方法中,根據(jù)啟動模式和flag等條件判斷要啟動的activity的ActivityRecord是加入現(xiàn)有的Task棧中或創(chuàng)建新的Task棧。在為Activity準(zhǔn)備好Task棧后,調(diào)用RootWindowContainer.resumeFocusedStacksTopActivities方法。
class RootWindowContainer extends WindowContainer<DisplayContent>
implements DisplayManager.DisplayListener {
boolean resumeFocusedStacksTopActivities(
ActivityStack targetStack, ActivityRecord target, ActivityOptions targetOptions) {
//...
boolean result = false;
if (targetStack != null && (targetStack.isTopStackInDisplayArea()
|| getTopDisplayFocusedStack() == targetStack)) {
// 調(diào)用ActivityStack.resumeTopActivityUncheckedLocked
result = targetStack.resumeTopActivityUncheckedLocked(target, targetOptions);
}
//...
return result;
}
}
class ActivityStack extends Task {
boolean resumeTopActivityUncheckedLocked(ActivityRecord prev, ActivityOptions options) {
if (mInResumeTopActivity) {
// Don't even start recurscheduleTransactionsing.
return false;
}
boolean result = false;
try {
mInResumeTopActivity = true;
// 繼續(xù)調(diào)用resumeTopActivityInnerLocked
result = resumeTopActivityInnerLocked(prev, options);
final ActivityRecord next = topRunningActivity(true /* focusableOnly */);
if (next == null || !next.canTurnScreenOn()) {
checkReadyForSleep();
}
} finally {
mInResumeTopActivity = false;
}
return result;
}
private boolean resumeTopActivityInnerLocked(ActivityRecord prev, ActivityOptions options) {
// Find the next top-most activity to resume in this stack that is not finishing and is
// focusable. If it is not focusable, we will fall into the case below to resume the
// top activity in the next focusable task.
// 在當(dāng)前Task棧中找到最上層正在運行的activity,如果這個activity沒有獲取焦點,那這個activity將會被重新啟動
ActivityRecord next = topRunningActivity(true /* focusableOnly */);
final boolean hasRunningActivity = next != null;
if (next.attachedToProcess()) {
...
} else {
...
// 調(diào)用StackSupervisor.startSpecificActivity
mStackSupervisor.startSpecificActivity(next, true, true);
}
return true;
}
}
ActivityStack用于單個活動棧的管理,最終調(diào)到ActivityStackSupervisor.startSpecificActivity()。
public class ActivityStackSupervisor implements RecentTasks.Callbacks {
// 檢查啟動Activity所在進程是否有啟動,沒有則先啟動進程
void startSpecificActivity(ActivityRecord r, boolean andResume, boolean checkConfig) {
// 根據(jù)processName和Uid查找啟動Activity的所在進程
final WindowProcessController wpc =
mService.getProcessController(r.processName, r.info.applicationInfo.uid);
boolean knownToBeDead = false;
if (wpc != null && wpc.hasThread()) {
// 進程已經(jīng)存在,則直接啟動Activity
try {
// 啟動Activity ,并返回
realStartActivityLocked(r, wpc, andResume, checkConfig);
return;
} catch (RemoteException e) {
...
}
knownToBeDead = true;
}
// 所在進程沒創(chuàng)建則調(diào)用ATMS.startProcessAsync創(chuàng)建進程并啟動Activity
mService.startProcessAsync(r, knownToBeDead, isTop, isTop ? "top-activity" : "activity");
}
// 啟動Activity的進程存在,則執(zhí)行此方法
boolean realStartActivityLocked(ActivityRecord r, WindowProcessController proc,
boolean andResume, boolean checkConfig) throws RemoteException {
...
// 創(chuàng)建活動啟動事務(wù)
// proc.getThread()是一個IApplicationThread對象,可以通過ClientTransaction.getClient()獲取
final ClientTransaction clientTransaction = ClientTransaction.obtain(
proc.getThread(), r.appToken);
// 為事務(wù)設(shè)置Callback,為LaunchActivityItem,在客戶端時會被調(diào)用
clientTransaction.addCallback(LaunchActivityItem.obtain(new Intent(r.intent),
System.identityHashCode(r), r.info,
// TODO: Have this take the merged configuration instead of separate global
// and override configs.
mergedConfiguration.getGlobalConfiguration(),
mergedConfiguration.getOverrideConfiguration(), r.compat,
r.launchedFromPackage, task.voiceInteractor, proc.getReportedProcState(),
r.getSavedState(), r.getPersistentSavedState(), results, newIntents,
dc.isNextTransitionForward(), proc.createProfilerInfoIfNeeded(),
r.assistToken, r.createFixedRotationAdjustmentsIfNeeded()));
// 設(shè)置所需的最終狀態(tài)
final ActivityLifecycleItem lifecycleItem;
if (andResume) {
lifecycleItem = ResumeActivityItem.obtain(dc.isNextTransitionForward());
} else {
lifecycleItem = PauseActivityItem.obtain();
}
clientTransaction.setLifecycleStateRequest(lifecycleItem);
// 執(zhí)行事件,調(diào)用ClientLifecycleManager.scheduleTransaction
mService.getLifecycleManager().scheduleTransaction(clientTransaction);
...
return true;
}
}
在ActivityStackSupervisor中,先檢查要啟動activity的進程是否存在,存在則調(diào)用realStartActivityLocked方法,通過ClientTransaction事務(wù)回調(diào)ApplicationThread.scheduleTransaction方法;進程不存在則創(chuàng)建進程。
Activity的顯示
// 主要是處理AMS端的請求
private class ApplicationThread extends IApplicationThread.Stub {
@Override
public void scheduleTransaction(ClientTransaction transaction) throws RemoteException {
ActivityThread.this.scheduleTransaction(transaction);
}
}
// ActivityThread的父類
public abstract class ClientTransactionHandler {
void scheduleTransaction(ClientTransaction transaction) {
transaction.preExecute(this);
// 發(fā)送EXECUTE_TRANSACTION消息
sendMessage(ActivityThread.H.EXECUTE_TRANSACTION, transaction);
}
}
// 它管理應(yīng)用程序進程中主線程的執(zhí)行,根據(jù)活動管理器的請求,在其上調(diào)度和執(zhí)行活動、廣播和其他操作。
public final class ActivityThread extends ClientTransactionHandler {
class H extends Handler {
public void handleMessage(Message msg) {
switch (msg.what) {
case EXECUTE_TRANSACTION:
final ClientTransaction transaction = (ClientTransaction) msg.obj;
// 調(diào)用TransactionExecutor.execute去處理ATMS階段傳過來的ClientTransaction
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();
}
break;
}
}
}
}
public class TransactionExecutor {
public void execute(ClientTransaction transaction) {
//...
// 調(diào)用傳過來的ClientTransaction事務(wù)的Callback
executeCallbacks(transaction);
executeLifecycleState(transaction);
}
public void executeCallbacks(ClientTransaction transaction) {
final List<ClientTransactionItem> callbacks = transaction.getCallbacks();
...
final int size = callbacks.size();
for (int i = 0; i < size; ++i) {
final ClientTransactionItem item = callbacks.get(i);
...
// 調(diào)用LaunchActivityItem.execute
item.execute(mTransactionHandler, token, mPendingActions);
item.postExecute(mTransactionHandler, token, mPendingActions);
...
}
}
}
public class LaunchActivityItem extends ClientTransactionItem {
public void execute(ClientTransactionHandler client, IBinder token,
PendingTransactionActions pendingActions) {
ActivityClientRecord r = new ActivityClientRecord(token, mIntent, mIdent, mInfo,
mOverrideConfig, mCompatInfo, mReferrer, mVoiceInteractor, mState, mPersistentState,
mPendingResults, mPendingNewIntents, mIsForward,
mProfilerInfo, client, mAssistToken, mFixedRotationAdjustments);
// 調(diào)用ActivityThread.handleLaunchActivity
client.handleLaunchActivity(r, pendingActions, null /* customIntent */);
}
}
ApplicationThread最后調(diào)用在ATMS階段設(shè)置的ClientTransaction的CallBack的execute方法,即LaunchActivityItem.execute方法,此時創(chuàng)建一個ActivityClientRecord對象,然后通過ActivityThread.handleLaunchActivity開啟真正的Actvity啟動。
public final class ActivityThread extends ClientTransactionHandler {
// ActivityThread啟動Activity的過程
@Override
public Activity handleLaunchActivity(ActivityClientRecord r,
PendingTransactionActions pendingActions, Intent customIntent) {
// ...
WindowManagerGlobal.initialize();
// 啟動Activity
final Activity a = performLaunchActivity(r, customIntent);
if (a != null) {
...
} else {
// 啟動失敗,調(diào)用ATMS停止Activity啟動
try {
ActivityTaskManager.getService()
.finishActivity(r.token, Activity.RESULT_CANCELED, null,
Activity.DONT_FINISH_TASK_WITH_ACTIVITY);
} catch (RemoteException ex) {
throw ex.rethrowFromSystemServer();
}
}
return a;
}
private Activity performLaunchActivity(ActivityClientRecord r, Intent customIntent) {
// 獲取ActivityInfo類
ActivityInfo aInfo = r.activityInfo;
if (r.packageInfo == null) {
// 獲取APK文件的描述類LoadedApk
r.packageInfo = getPackageInfo(aInfo.applicationInfo, r.compatInfo,
Context.CONTEXT_INCLUDE_CODE);
}
// 啟動的Activity的ComponentName類
ComponentName component = r.intent.getComponent();
// 創(chuàng)建要啟動Activity的上下文環(huán)境
ContextImpl appContext = createBaseContextForActivity(r);
Activity activity = null;
try {
java.lang.ClassLoader cl = appContext.getClassLoader();
// 用類加載器來創(chuàng)建該Activity的實例
activity = mInstrumentation.newActivity(
cl, component.getClassName(), r.intent);
// ...
} catch (Exception e) {
// ...
}
try {
// 創(chuàng)建Application
Application app = r.packageInfo.makeApplication(false, mInstrumentation);
if (activity != null) {
// 初始化Activity
activity.attach(appContext, this, getInstrumentation(), r.token,
r.ident, app, r.intent, r.activityInfo, title, r.parent,
r.embeddedID, r.lastNonConfigurationInstances, config,
r.referrer, r.voiceInteractor, window, r.configCallback,
r.assistToken);
...
// 調(diào)用Instrumentation的callActivityOnCreate方法來啟動Activity
if (r.isPersistable()) {
mInstrumentation.callActivityOnCreate(activity, r.state, r.persistentState);
} else {
mInstrumentation.callActivityOnCreate(activity, r.state);
}
...
}
...
} catch (SuperNotCalledException e) {
throw e;
} catch (Exception e) {
...
}
return activity;
}
public class Instrumentation {
public void callActivityOnCreate(Activity activity, Bundle icicle) {
prePerformCreate(activity);
// 調(diào)用Activity的performCreate
activity.performCreate(icicle);
postPerformCreate(activity);
}
}
public class Activity extends ContextThemeWrapper
implements LayoutInflater.Factory2,
Window.Callback, KeyEvent.Callback,
OnCreateContextMenuListener, ComponentCallbacks2,
Window.OnWindowDismissedCallback,
AutofillManager.AutofillClient, ContentCaptureManager.ContentCaptureClient {
final void performCreate(Bundle icicle) {
performCreate(icicle, null);
}
@UnsupportedAppUsage
final void performCreate(Bundle icicle, PersistableBundle persistentState) {
...
// 調(diào)用onCreate方法
if (persistentState != null) {
onCreate(icicle, persistentState);
} else {
onCreate(icicle);
}
...
}
}
當(dāng)初始化完成后,Activity的界面會被繪制并顯示到屏幕上。此時,用戶可以與Activity進行交互。
總結(jié)
- 「啟動請求的發(fā)起」:
無論是從應(yīng)用內(nèi)部啟動Activity,還是通過桌面程序(Launcher)啟動,都需要通過調(diào)用startActivity方法來發(fā)起啟動請求。
這個請求包含了要啟動的Activity的信息,通常通過Intent對象來傳遞。
- 「請求到達(dá)ActivityTaskManagerService(ATMS)」:
當(dāng)啟動請求被發(fā)起后,它會首先到達(dá)ActivityTaskManagerService(ATMS)。
ATMS是負(fù)責(zé)管理Activity生命周期和任務(wù)棧的系統(tǒng)服務(wù)。
「線程切換與消息處理」:
在ATMS處理啟動請求的過程中,可能涉及到線程切換和消息處理。
例如,將請求從應(yīng)用線程切換到系統(tǒng)服務(wù)線程,或者通過消息隊列來處理請求。
「Activity的初始化與生命周期管理」:
一旦ATMS決定了要啟動哪個Activity,它會通知相應(yīng)的應(yīng)用進程進行Activity的初始化。
這包括創(chuàng)建Activity的實例、加載布局、初始化組件等。
同時,Activity的生命周期方法(如onCreate、onStart、onResume等)也會被調(diào)用,以確保Activity的正確初始化和狀態(tài)管理。
「Activity的顯示」:
當(dāng)初始化完成后,Activity的界面會被繪制并顯示到屏幕上。
此時,用戶可以與Activity進行交互。
在Android的不同版本中,啟動流程可能會有所不同,并且可能涉及到更多的細(xì)節(jié)和組件。此外,如果啟動的是一個根Activity(例如從Launcher啟動),那么流程中可能還包括應(yīng)用進程的創(chuàng)建等步驟。Activity的啟動流程是一個涉及多個組件和服務(wù)的復(fù)雜過程,它確保了Android應(yīng)用程序能夠正確地創(chuàng)建、初始化和顯示Activity,從而為用戶提供流暢和一致的體驗。