基於Android 6.0的源碼剖析, 分析android Activity啓動流程,相關源碼:java
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.javaandroid
一. 概述app
startActivity的總體流程與startService啓動過程分析很是相近,但比Service啓動更爲複雜,多了stack/task以及UI的相關內容以及Activity的生命週期更爲豐富。ide
Activity啓動發起後,經過Binder最終交由system進程中的AMS來完成,則啓動流程以下圖:函數
接下來,從源碼來講說每一個過程。
二. 啓動流程
2.1 Activity.startActivity測試
[-> Activity.java]ui
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);
}
}this
2.2 startActivityForResult.net
[-> 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切換是否容許
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
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.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 {
...
}
...
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;
}
...
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);
}
......
//處於睡眠或者關機狀態,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;
}
......
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);
}
}
//見流程2.14
mStackSupervisor.startSpecificActivityLocked(next, true, true);
}
return true;
}
主要分支功能:
當找不到須要resume的Activity,則直接回到桌面;
不然,當mResumedActivity不爲空,則執行startPausingLocked()暫停該activity;
而後再進入startSpecificActivityLocked環節,接下來從這裏繼續往下說。
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()) {
//調用Activity.onCreat方法
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()生命週期。
從另外一個角度下圖來歸納:
啓動流程:
點擊桌面App圖標,Launcher進程採用Binder IPC向system_server進程發起startActivity請求;
system_server進程接收到請求後,向zygote進程發送建立進程的請求;
Zygote進程fork出新的子進程,即App進程;
App進程,經過Binder IPC向sytem_server進程發起attachApplication請求;
system_server進程在收到請求後,進行一系列準備工做後,再經過binder IPC向App進程發送scheduleLaunchActivity請求;
App進程的binder線程(ApplicationThread)在收到請求後,經過handler向主線程發送LAUNCH_ACTIVITY消息;
主線程在收到Message後,經過發射機制建立目標Activity,並回調Activity.onCreate()等方法。
到此,App便正式啓動,開始進入Activity生命週期,執行完onCreate/onStart/onResume方法,UI渲染結束後即可以看到App的主界面。 啓動Activity較爲複雜,後續計劃再進一步講解生命週期過程與系統是如何交互,以及UI渲染過程,敬請期待。 ---------------------