本次源碼基于Android11分析
相關(guān)源碼:
/frameworks/base/core/java/android/app/Activity.java
/frameworks/base/core/java/android/app/Instrumentation.java
/frameworks/base/core/java/android/app/ActivityTaskManager.java
/frameworks/base/services/core/java/com/android/server/wm/ActivityTaskManagerService.java
/frameworks/base/services/core/java/com/android/server/wm/ActivityStarter.java
/frameworks/base/services/core/java/com/android/server/wm/RootWindowContainer.java
/frameworks/base/services/core/java/com/android/server/wm/ActivityStack.java
/frameworks/base/services/core/java/com/android/server/wm/ActivityStackSupervisor.java
/frameworks/base/services/core/java/com/android/server/wm/ClientLifecycleManager.java
/frameworks/base/core/java/android/app/servertransaction/ClientTransaction.java
/frameworks/base/core/java/android/app/servertransaction/LaunchActivityItem.java
/frameworks/base/core/java/android/app/ActivityThread.java
/frameworks/base/core/java/android/app/servertransaction/TransactionExecutor.java
/frameworks/base/core/java/android/app/LoadedApk.java
概述
調(diào)用startActivity
或startActivityForResult
來啟動Activity亿昏。那么啟動的Activity有兩種情況:第一種是啟動同進(jìn)程內(nèi)的Activity; 第二種是啟動不同進(jìn)程的根Activity,比如在桌面點(diǎn)擊啟動App,就是啟動不同進(jìn)程的Activity。這兩種情況的Activity的啟動流程大致相同捂寿,其流程大致是以下三個過程:
- 調(diào)用進(jìn)程的Activity收集好信息后牡拇,向system_server進(jìn)程的ActivityTaskManagerServer服務(wù)發(fā)起請求魁瞪。
- ATMS向PKMS尋找啟動的Activity信息和進(jìn)程信息,如果啟動的Activity進(jìn)程沒有被創(chuàng)建惠呼,則創(chuàng)建新進(jìn)程,之后管理Activity的堆棧导俘,并回調(diào)啟動Activity所在進(jìn)程的ApplicationThread類
- ApplicationThread通過調(diào)用ActivityThread來反射調(diào)用啟動Activity。
以下逐一講解這三大過程:
1. 向ATMS發(fā)起請求(system_server進(jìn)程)
下圖是調(diào)用進(jìn)程向system_server進(jìn)程發(fā)起請求的過程:
無論是使用
startActivity
還是startActivityForResult
最終都會調(diào)用到Activity.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) {
this.startActivity(intent, null);
}
@Override
public void startActivity(Intent intent, @Nullable Bundle options) {
if (options != null) {
startActivityForResult(intent, -1, options);
} else {
// Note we want to go through this call for compatibility with
// applications that may have overridden the method.
startActivityForResult(intent, -1);
}
}
public void startActivityForResult(@RequiresPermission Intent intent, int requestCode) {
startActivityForResult(intent, requestCode, null);
}
public void startActivityForResult(@RequiresPermission Intent intent, int requestCode,
@Nullable Bundle options) {
// mParent 是Activity類型剔蹋,是當(dāng)前Activity的父類
if (mParent == null) {
options = transferSpringboardActivityOptions(options);
//主要看這里mInstrumentation為Instrumentation對象
Instrumentation.ActivityResult ar =
mInstrumentation.execStartActivity(
this, mMainThread.getApplicationThread(), mToken, this,
intent, requestCode, options);
//...
} else {
//...
}
}
}
startActivityForResult方法繼續(xù)調(diào)用Instrumentation.execStartActivity
方法旅薄。而Instrumentation類主要用來監(jiān)控應(yīng)用程序和系統(tǒng)的交互。
// Instrumentation主要用來監(jiān)控應(yīng)用程序和系統(tǒng)的交互
public class Instrumentation {
public ActivityResult execStartActivity(
Context who, IBinder contextThread, IBinder token, Activity target,
Intent intent, int requestCode, Bundle options) {
...
try {
intent.migrateExtraStreamToClipData(who);
intent.prepareToLeaveProcess(who);
//核心在這一句 調(diào)用ActivityTaskManagerService.startActivity(通過Binder向System_server進(jìn)程通信)
int result = ActivityTaskManager.getService().startActivity(whoThread,
who.getBasePackageName(), who.getAttributionTag(), intent,
intent.resolveTypeIfNeeded(who.getContentResolver()), token,
target != null ? target.mEmbeddedID : null, requestCode, 0, null, options);
// 根據(jù)返回的狀態(tài),檢查是否能啟動Activity少梁,不能啟動則拋出不同的異常
checkStartActivityResult(result, intent);
} catch (RemoteException e) {
throw new RuntimeException("Failure from system", e);
}
return null;
}
// 根據(jù)不同的異常狀態(tài)洛口,拋出不同的異常
public static void checkStartActivityResult(int res, Object intent) {
if (!ActivityManager.isStartResultFatalError(res)) {
return;
}
switch (res) {
case ActivityManager.START_INTENT_NOT_RESOLVED:
case ActivityManager.START_CLASS_NOT_FOUND:
if (intent instanceof Intent && ((Intent) intent).getComponent() != null)
throw new ActivityNotFoundException(
"Unable to find explicit activity class "
+ ((Intent) intent).getComponent().toShortString()
+ "; have you declared this activity in your AndroidManifest.xml?");
throw new ActivityNotFoundException(
"No Activity found to handle " + intent);
case ActivityManager.START_PERMISSION_DENIED:
throw new SecurityException("Not allowed to start activity "
+ intent);
case ActivityManager.START_FORWARD_AND_REQUEST_CONFLICT:
throw new AndroidRuntimeException(
"FORWARD_RESULT_FLAG used while also requesting a result");
case ActivityManager.START_NOT_ACTIVITY:
throw new IllegalArgumentException(
"PendingIntent is not an activity");
case ActivityManager.START_NOT_VOICE_COMPATIBLE:
throw new SecurityException(
"Starting under voice control not allowed for: " + intent);
case ActivityManager.START_VOICE_NOT_ACTIVE_SESSION:
throw new IllegalStateException(
"Session calling startVoiceActivity does not match active session");
case ActivityManager.START_VOICE_HIDDEN_SESSION:
throw new IllegalStateException(
"Cannot start voice activity on a hidden session");
case ActivityManager.START_ASSISTANT_NOT_ACTIVE_SESSION:
throw new IllegalStateException(
"Session calling startAssistantActivity does not match active session");
case ActivityManager.START_ASSISTANT_HIDDEN_SESSION:
throw new IllegalStateException(
"Cannot start assistant activity on a hidden session");
case ActivityManager.START_CANCELED:
throw new AndroidRuntimeException("Activity could not be started for "
+ intent);
default:
throw new AndroidRuntimeException("Unknown error code "
+ res + " when starting " + intent);
}
}
}
public class ActivityTaskManager {
public static IActivityTaskManager getService() {
return IActivityTaskManagerSingleton.get();
}
@UnsupportedAppUsage(trackingBug = 129726065)
private static final Singleton<IActivityTaskManager> IActivityTaskManagerSingleton =
new Singleton<IActivityTaskManager>() {
@Override
protected IActivityTaskManager create() {
// Context.ACTIVITY_TASK_SERVICE這個是ATMS
final IBinder b = ServiceManager.getService(Context.ACTIVITY_TASK_SERVICE);
return IActivityTaskManager.Stub.asInterface(b);
}
};
}
- 通過
ActivityTaskManager.getService()
獲取到ATMS的代理類,通過Binder跨進(jìn)程通信凯沪,向ATMS發(fā)起startActivity請求第焰。 - 通過向ATMS發(fā)起啟動Activity請求,從而得到的返回結(jié)果result妨马,再根據(jù)result判斷能否啟動Activity,不能則拋異常挺举,比如Activity沒有在AndroidManifest中注冊等。
2. ATMS到ApplicationThread調(diào)用過程
下圖是ATMS處理startActivity過程烘跺,并回調(diào)啟動進(jìn)程的ApplicationThread
ATMS. startActivity:
// system_server進(jìn)程
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());
}
public int startActivityAsUser(IApplicationThread caller, String callingPackage,
String callingFeatureId, Intent intent, String resolvedType, IBinder resultTo,
String resultWho, int requestCode, int startFlags, ProfilerInfo profilerInfo,
Bundle bOptions, int userId) {
return startActivityAsUser(caller, callingPackage, callingFeatureId, intent, resolvedType,
resultTo, resultWho, requestCode, startFlags, profilerInfo, bOptions, userId,
true /*validateIncomingUser*/);
}
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)用者進(jìn)程是否被隔離
enforceNotIsolatedCaller("startActivityAsUser");
//檢查調(diào)用者權(quán)限
userId = getActivityStartController().checkTargetUser(userId, validateIncomingUser,
Binder.getCallingPid(), Binder.getCallingUid(), "startActivityAsUser");
// getActivityStartController().obtainStarter 返回 ActivityStarter湘纵,
// 把參數(shù)設(shè)置到ActivityStarter.Request類中
// 最后調(diào)用ActivityStarter.execute(),
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)用進(jìn)程的權(quán)限梧喷,然后通過getActivityStartController().obtainStarter
創(chuàng)建ActivityStarter
類,并把參數(shù)設(shè)置到ActivityStarter.Request
類中脖咐,最后執(zhí)行ActivityStarter.execute()
方法铺敌。
ActivityStarter準(zhǔn)備堆棧
class ActivityStarter {
int execute() {
try {
// ...
int res;
synchronized (mService.mGlobalLock) {
//...
res = executeRequest(mRequest);
//...
return getExternalResult(mRequest.waitResult == null ? res
: waitForResult(res, mLastStartActivityRecord));
}
} finally {
onExecutionComplete();
}
}
private int executeRequest(Request request) {
//判斷啟動的理由不為空
if (TextUtils.isEmpty(request.reason)) {
throw new IllegalArgumentException("Need to specify a reason.");
}
...
//獲取調(diào)用的進(jìn)程
WindowProcessController callerApp = null;
if (caller != null) {
callerApp = mService.getProcessController(caller);
if (callerApp != null) {
//獲取調(diào)用進(jìn)程的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 則不進(jìn)入
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é)果則不會進(jìn)入該分支
}
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)限檢查
// ActivityController不為空的情況,比如monkey測試過程
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)限檢查不滿足,才進(jì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. executeRequest
方法中先做一系列的檢查适刀,包括調(diào)用進(jìn)程的檢查秤朗、Intent的檢查煤蹭、權(quán)限的檢查、向PKMS獲取啟動Activity的ActivityInfo等信息取视,然后調(diào)用startActivityUnchecked
方法開始對要啟動的Activity做堆棧管理硝皂。
private int startActivityUnchecked(final ActivityRecord r, ActivityRecord sourceRecord,
IVoiceInteractionSession voiceSession, IVoiceInteractor voiceInteractor,
int startFlags, boolean doResume, ActivityOptions options, Task inTask,
boolean restrictedBgActivity, NeededUriGrants intentGrants) {
int result = START_CANCELED;
final ActivityStack startedActivityStack;
try {
mService.deferWindowLayout();
result = startActivityInner(r, sourceRecord, voiceSession, voiceInteractor,
startFlags, doResume, options, inTask, restrictedBgActivity, intentGrants);
} finally {
//...
}
postStartActivityProcessing(r, result, startedActivityStack);
return result;
}
ActivityRecord mStartActivity;
private ActivityStack mSourceStack;
private ActivityStack mTargetStack;
private Task mTargetTask;
// 主要處理?xiàng)9芾硐嚓P(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的各種配置,在初始化前會重置各種配置再進(jìn)行配置作谭,
// 這些配置包括:ActivityRecord稽物、Intent、Task和LaunchFlags(啟動的FLAG)等等
setInitialState(r, options, inTask, doResume, startFlags, sourceRecord, voiceSession,
voiceInteractor, restrictedBgActivity);
// 給不同的啟動模式計(jì)算出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,則計(jì)算是否存在可以使用的任務(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;
}
// 初始化狀態(tài)
private void setInitialState(ActivityRecord r, ActivityOptions options, Task inTask,
boolean doResume, int startFlags, ActivityRecord sourceRecord,
IVoiceInteractionSession voiceSession, IVoiceInteractor voiceInteractor,
boolean restrictedBgActivity) {
reset(false /* clearRequest */); //重置狀態(tài)
mStartActivity = r; // 被啟動的Activity
mIntent = r.intent; //啟動的intent
mSourceRecord = sourceRecord; //發(fā)起啟動的Activity
mLaunchMode = r.launchMode; // 啟動模式
// 啟動Flags
mLaunchFlags = adjustLaunchFlagsToDocumentMode(
r, LAUNCH_SINGLE_INSTANCE == mLaunchMode,
LAUNCH_SINGLE_TASK == mLaunchMode, mIntent.getFlags());
mInTask = inTask;
// ...
}
// 根據(jù)不同啟動模式計(jì)算出不同的mLaunchFlags
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);
// 重新檢驗(yàn)
putIntoExistingTask &= mInTask == null && mStartActivity.resultTo == null;
ActivityRecord intentActivity = null;
if (putIntoExistingTask) {
if (LAUNCH_SINGLE_INSTANCE == mLaunchMode) {
//如果是 singleInstance,那么就找看看之前存在的該實(shí)例靡挥,找不到就為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;
}
// 計(jì)算啟動的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) {
// 使用啟動時(shí)傳遞的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ù)啟動模式計(jì)算出flag,在根據(jù)flag等條件啟動的Activity的ActivityRecord是加入現(xiàn)有的Task棧中幔烛,還是創(chuàng)建新Task棧啃擦。為Activity準(zhǔn)備好堆棧后,調(diào)用RootWindowContainer.resumeFocusedStacksTopActivities
方法
ActivityStack對棧的管理:
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;
}
}
// 單個活動堆棧的狀態(tài)和管理饿悬。
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) {
//在此堆棧中找到下一個要恢復(fù)的最頂層活動令蛉,該活動未完成且可聚焦。如果它不是可聚焦的狡恬,我們將陷入下面的情況以在下一個可聚焦任務(wù)中恢復(fù)頂部活動珠叔。
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;
}
}
對于啟動Activity對應(yīng)的ActivityStack
來說,是管理其棧中Activity的顯示邏輯弟劲。而后繼續(xù)調(diào)用ActivityStackSupervisor.startSpecificActivity
ActivityStackSupervisor檢查啟動進(jìn)程和回調(diào)ApplicationThread
public class ActivityStackSupervisor implements RecentTasks.Callbacks {
// 檢查啟動Activity所在進(jìn)程是否有啟動祷安,沒有則先啟動進(jìn)程
void startSpecificActivity(ActivityRecord r, boolean andResume, boolean checkConfig) {
// 根據(jù)processName和Uid查找啟動Activity的所在進(jìn)程
final WindowProcessController wpc =
mService.getProcessController(r.processName, r.info.applicationInfo.uid);
boolean knownToBeDead = false;
if (wpc != null && wpc.hasThread()) {
// 進(jìn)程已經(jīng)存在,則直接啟動Activity
try {
// 啟動Activity ,并返回
realStartActivityLocked(r, wpc, andResume, checkConfig);
return;
} catch (RemoteException e) {
...
}
knownToBeDead = true;
}
// 所在進(jìn)程沒創(chuàng)建則調(diào)用ATMS.startProcessAsync創(chuàng)建進(jìn)程并啟動Activity
mService.startProcessAsync(r, knownToBeDead, isTop, isTop ? "top-activity" : "activity");
}
// 啟動Activity的進(jìn)程存在兔乞,則執(zhí)行此方法
boolean realStartActivityLocked(ActivityRecord r, WindowProcessController proc,
boolean andResume, boolean checkConfig) throws RemoteException {
...
// 創(chuàng)建活動啟動事務(wù)
final ClientTransaction clientTransaction = ClientTransaction.obtain(
proc.getThread(), r.appToken);
// 為事務(wù)設(shè)置Callback汇鞭,為LaunchActivityItem,在客戶端時(shí)會被調(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;
}
}
class ClientLifecycleManager {
void scheduleTransaction(ClientTransaction transaction) throws RemoteException {
final IApplicationThread client = transaction.getClient();
// 反調(diào)用ClientTransaction.schedule()
transaction.schedule();
...
}
}
public class ClientTransaction implements Parcelable, ObjectPoolItem {
public void schedule() throws RemoteException {
// 調(diào)用ApplicationThread.scheduleTransaction
mClient.scheduleTransaction(this);
}
}
在ActivityStackSupervisor中先檢查要啟動Activity的進(jìn)程是否存在霍骄,不存在則創(chuàng)建進(jìn)程,存在則調(diào)用realStartActivityLocked
,realStartActivityLocked方法通過事務(wù)給回調(diào)ApplicationThread. scheduleTransaction
方法淡溯。
ATMS小結(jié)
- 檢查調(diào)用進(jìn)程读整、Intent、權(quán)限等信息咱娶,并向PKMS查找要啟動Activity的信息米间,符合則往下走。
- 根據(jù)啟動模式計(jì)算出flag等信息膘侮,為啟動的Activity設(shè)置棧
- 檢查啟動Activity對應(yīng)進(jìn)程是否存在屈糊,不存在則先啟動進(jìn)程,存在則向客戶端進(jìn)程
ApplicationThread
進(jìn)行回調(diào)啟動Activity
3. ActivityThread啟動Activity過程
下圖為ActivityThread啟動Activity過程的時(shí)序圖:
// 主要是處理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)用程序進(jìn)程中主線程的執(zhí)行喻喳,根據(jù)活動管理器的請求另玖,在其上調(diào)度和執(zhí)行活動、廣播和其他操作。
public final class ActivityThread extends ClientTransactionHandler {
// 用于處理消息同步谦去,將binder線程的消息同步到主線程中
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)用ApplicationThread.handleLaunchActivity
client.handleLaunchActivity(r, pendingActions, null /* customIntent */);
}
}
ApplicationThread類繞了一大圈慷丽,最后調(diào)用在ATMS階段設(shè)置的ClientTransaction的CallBack的execute方法,也就是LaunchActivityItem. execute
方法鳄哭,此方法創(chuàng)建一個ActivityClientRecord
對象要糊,然后調(diào)用ActivityThread. handleLaunchActivity
開啟真正的Actvity啟動。
真正啟動Activity:
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的實(shí)例
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);
}
...
}
}
小結(jié)
- 調(diào)用從system_server進(jìn)程傳過來的ClientTransaction.CallBack類中的execute方法锄俄,其繼續(xù)調(diào)用
ActivityThread.handleLaunchActivity
方法來啟動Activity。 -
ActivityThread.handleLaunchActivity
調(diào)用performLaunchActivity
方法啟動Activity -
performLaunchActivity
先獲取啟動Activity的ActivityInfo勺拣,而后創(chuàng)建一個LoadedApk和上下文ContextImpl奶赠。在通過反射去創(chuàng)建此Activity對象,并執(zhí)行Activity的onCreate方法药有。