一.ActivityManagerService
1.概述
???????AMS是Android系統(tǒng)中一個(gè)特別重要的系統(tǒng)服務(wù),也是上層APP打交道最多的系統(tǒng)服務(wù)之一娃圆,主要負(fù)責(zé)系統(tǒng)中四大組件的啟動(dòng)拾碌、切換曹铃、調(diào)度及應(yīng)用進(jìn)程的管理和調(diào)度等工作绞佩,其職責(zé)與操作系統(tǒng)中的進(jìn)程管理和調(diào)度模塊相類似冬阳,因此它在Android系統(tǒng)中非常重要颤霎。
2.組成
2.1.Client
???????由ActivityManager封裝一部分服務(wù)接口供Client調(diào)用媳谁,ActivityManager內(nèi)部通過(guò)調(diào)用getService()可以獲取到IActivityManager對(duì)象的引用,進(jìn)而通過(guò)該引用遠(yuǎn)程服務(wù)的方法友酱;
2.2.Server
???????由ActivityManagerService實(shí)現(xiàn)晴音,提供Server端的系統(tǒng)服務(wù);
3.啟動(dòng)過(guò)程
???????AMS是在SystemServer中被添加的缔杉,本文基于Android 8.1進(jìn)行分析锤躁,先到SystemServer中查看初始化過(guò)程:
3.1.SystemServer
public static void main(String[] args) {
new SystemServer().run();
}
???????在run()方法中,創(chuàng)建SystemServiceManager對(duì)象或详,然后啟動(dòng)一些service系羞。
private void run() {
......
......
// Prepare the main looper thread (this thread).
android.os.Process.setThreadPriority(
android.os.Process.THREAD_PRIORITY_FOREGROUND);
android.os.Process.setCanSelfBackground(false);
Looper.prepareMainLooper();
// Initialize native services.
System.loadLibrary("android_servers");
// Initialize the system context.
createSystemContext();
// Create the system service manager.
mSystemServiceManager = new SystemServiceManager(mSystemContext);
mSystemServiceManager.setRuntimeRestarted(mRuntimeRestart);
LocalServices.addService(SystemServiceManager.class, mSystemServiceManager);
.......
// Start services.
try {
traceBeginAndSlog("StartServices");
startBootstrapServices();
startCoreServices();
startOtherServices();
SystemServerInitThreadPool.shutdown();
}
// Loop forever.
Looper.loop();
}
???????ActivityManagerService是在startBootstrapServices()中創(chuàng)建啟動(dòng)的。
private void startBootstrapServices() {
......
......
// Activity manager runs the show.
traceBeginAndSlog("StartActivityManager");
mActivityManagerService = mSystemServiceManager.startService(
ActivityManagerService.Lifecycle.class).getService();
mActivityManagerService.setSystemServiceManager(mSystemServiceManager);
mActivityManagerService.setInstaller(installer);
traceEnd();
......
......
// Set up the Application instance for the system process and get started.
traceBeginAndSlog("SetSystemProcess");
//將自己注冊(cè)到ServiceManager中霸琴,供IPC調(diào)用
mActivityManagerService.setSystemProcess();
traceEnd();
.......
}
???????AMS是通過(guò)SystemServiceManager.startService去啟動(dòng)的,參數(shù)是ActivityManagerService.Lifecycle.class, 首先看看SystemServiceManager.java的startService方法調(diào)用邏輯:
public SystemService startService(String className) {
final Class<SystemService> serviceClass;
try {
serviceClass = (Class<SystemService>)Class.forName(className);
} catch (ClassNotFoundException ex) {
......
}
return startService(serviceClass);
}
???????通過(guò)傳入的類名字獲取到對(duì)應(yīng)的class椒振,接著將該class作為參數(shù)傳入執(zhí)行下一個(gè)startService()方法:
public <T extends SystemService> T startService(Class<T> serviceClass) {
try {
final String name = serviceClass.getName();
......
final T service;
try {
Constructor<T> constructor = serviceClass.getConstructor(Context.class);
service = constructor.newInstance(mContext);
}
......
startService(service);
return service;
}
......
}
???????通過(guò)反射獲取到類的構(gòu)造方法,然后通過(guò)newInstance()來(lái)創(chuàng)建實(shí)例梧乘,接著將該實(shí)例作為參數(shù)傳入執(zhí)行下一個(gè)startService()方法:
public void startService(@NonNull final SystemService service) {
// Register it.
mServices.add(service);
// Start it.
long time = SystemClock.elapsedRealtime();
try {
service.onStart();
}
......
}
???????startService方法很簡(jiǎn)單杠人,是通過(guò)傳進(jìn)來(lái)的class然后反射創(chuàng)建對(duì)應(yīng)的service服務(wù)。所以此處創(chuàng)建的是Lifecycle的實(shí)例,然后在startService中執(zhí)行了service.onStart()嗡善。
???????上面創(chuàng)建ActivityManagerService時(shí)傳入的是ActivityManagerService.Lifecycle.class辑莫,看一下這個(gè)類:
public static final class Lifecycle extends SystemService {
private final ActivityManagerService mService;
public Lifecycle(Context context) {
super(context);
mService = new ActivityManagerService(context);
}
@Override
public void onStart() {
mService.start();
}
@Override
public void onCleanupUser(int userId) {
mService.mBatteryStatsService.onCleanupUser(userId);
}
public ActivityManagerService getService() {
return mService;
}
}
???????通過(guò)以上類可以看到,LifeCycle繼承SystemService[SystemService是一個(gè)抽象類]罩引,在構(gòu)造方法中創(chuàng)建了ActivityManagerService對(duì)象mService各吨,然后通過(guò)getService()可以獲取到mService。
3.2.構(gòu)造方法
???????看一下ActivityManagerService初始化主要做了什么:
public ActivityManagerService(Context systemContext) {
......
mServices = new ActiveServices(this);
......
mStackSupervisor = createStackSupervisor();
mTaskChangeNotificationController =
new TaskChangeNotificationController(this, mStackSupervisor, mHandler);
mActivityStarter = new ActivityStarter(this, mStackSupervisor);
mRecentTasks = new RecentTasks(this, mStackSupervisor);
mProcessCpuThread = new Thread("CpuTracker") {
@Override
public void run() {
................
................
};
Watchdog.getInstance().addMonitor(this);
Watchdog.getInstance().addThread(mHandler);
}
???????在構(gòu)造方法中執(zhí)行了許多初始化工作袁铐,主要如下:
???????1.創(chuàng)建ActiveServices實(shí)例揭蜒,來(lái)處理Service啟動(dòng)等相關(guān)邏輯;
???????2.創(chuàng)建ActivityStackSupervisor實(shí)例剔桨,核心類屉更,管理ActivityStack,創(chuàng)建ActivityDisplay等洒缀;
???????3.創(chuàng)建mTaskChangeNotificationController來(lái)監(jiān)聽(tīng)Task棧變化并進(jìn)行通知瑰谜;
???????4.創(chuàng)建ActivityStarter實(shí)例,來(lái)處理Activity啟動(dòng)等相關(guān)邏輯树绩;
???????5.創(chuàng)建RecentTasks實(shí)例萨脑,來(lái)管理最近打開(kāi)的任務(wù);
???????6.啟動(dòng)一個(gè)線程專門(mén)跟進(jìn)cpu當(dāng)前狀態(tài)信息,AMS對(duì)當(dāng)前cpu狀態(tài)了如指掌,可以更加高效的安排其他工作
???????7.注冊(cè)看門(mén)狗監(jiān)聽(tīng)進(jìn)程饺饭,每分鐘調(diào)用一次監(jiān)視器渤早,如果進(jìn)程沒(méi)有任何返回就殺掉;
3.3.setSystemProcess()
???????前面分析到瘫俊,在SystemServer中會(huì)先啟動(dòng)ActivityManagerService鹊杖,啟動(dòng)完成后會(huì)執(zhí)行setSystemProcess(),看一下setSystemProcess()做了什么工作:
public class ActivityManagerService extends IActivityManager.Stub implements xxx {
.......
.......
public void setSystemProcess() {
try {
ServiceManager.addService(Context.ACTIVITY_SERVICE, this, true);
}
......
.......
}
.......
.......
}
???????在setSystemProcess()內(nèi)部進(jìn)行服務(wù)注冊(cè)扛芽,首先將ActivityManagerService注冊(cè)到ServiceManager中仅淑,其次將幾個(gè)與系統(tǒng)性能調(diào)試相關(guān)的服務(wù)注冊(cè)到ServiceManager。此時(shí)其他進(jìn)程可以通過(guò)ServiceManager.getService(Context.ACTIVITY_SERVICE)獲取到IBinder胸哥,IActivityManager.Stub.asInterface(IBinder)可以獲取到ActivityManagerService涯竟,然后可以與ActivityManagerService進(jìn)行IPC了。
???????前面講到在SystemServer的main()中會(huì)執(zhí)行一系列啟動(dòng)services空厌,如下:
// Start services.
try {
traceBeginAndSlog("StartServices");
startBootstrapServices();
startCoreServices();
startOtherServices();
SystemServerInitThreadPool.shutdown();
}
???????在startBootstrapServices()中會(huì)啟動(dòng)ActivityManagerService庐船,然后在startOtherServices()中會(huì)執(zhí)行到以下邏輯:
mActivityManagerService.systemReady(() -> {
Slog.i(TAG, "Making services ready");
......
......
if (mPackageManager.hasSystemFeature(PackageManager.FEATURE_AUTOMOTIVE)) {
traceBeginAndSlog("StartCarServiceHelperService");
mSystemServiceManager.startService(CarServiceHelperService.class);
traceEnd();
}
traceBeginAndSlog("StartSystemUI");
try {
startSystemUi(context, windowManagerF);
}
.......
.......
}, BOOT_TIMINGS_TRACE_LOG);
static final void startSystemUi(Context context, WindowManagerService windowManager) {
Intent intent = new Intent();
intent.setComponent(new ComponentName("com.android.systemui",
"com.android.systemui.SystemUIService"));
intent.addFlags(Intent.FLAG_DEBUG_TRIAGED_MISSING);
context.startServiceAsUser(intent, UserHandle.SYSTEM);
windowManager.onSystemUiStarted();
}
???????通過(guò)以上可以看到,會(huì)執(zhí)行到ActivityManagerService的systemReady()方法嘲更,然后啟動(dòng)CarServiceHelperService筐钟,接下來(lái)會(huì)啟動(dòng)SystemUISerivce,找到了啟動(dòng)SystemUISerivce的地方赋朦,接下來(lái)分析一下ActivityManagerService的systemReady()內(nèi)部主要做了什么工作:
3.4.systemReady()
public void systemReady(final Runnable goingCallback, TimingsTraceLog traceLog) {
traceLog.traceBegin("PhaseActivityManagerReady");
synchronized(this) {
if (mSystemReady) {
if (goingCallback != null) {
goingCallback.run();
}
return;
}
.......
mSystemReady = true;
}
.......
.......
if (goingCallback != null) goingCallback.run();
.......
synchronized (this) {
startPersistentApps(PackageManager.MATCH_DIRECT_BOOT_AWARE);
.......
startHomeActivityLocked(currentUserId, "systemReady");
.......
}
}
}
???????通過(guò)以上可以看到篓冲,在systemReady()中李破,有兩處比較重要的地方是:
???????1.執(zhí)行startPersistentApps(),啟動(dòng)那些在AndroidManifest.xml中設(shè)置了android:persist="true"的app壹将。
???????2.執(zhí)行startHomeActivityLocked()嗤攻,啟動(dòng)home activity,比如手機(jī)端應(yīng)該是啟動(dòng)了Launcher诽俯。
二.Activity管理
1.結(jié)構(gòu)圖
2.ActivityDisplay
???????ActivityDisplay與系統(tǒng)屏幕對(duì)應(yīng)妇菱,屬于AMS管理Activity的頂層數(shù)據(jù)結(jié)構(gòu);
2.1.構(gòu)建
???????在ActivityStackSupervisor內(nèi)通過(guò)DMS遍歷系統(tǒng)Display創(chuàng)建ActivityDisplay暴区,具體實(shí)現(xiàn)邏輯是在setWindowManager()方法內(nèi)部:
void setWindowManager(WindowManagerService wm) {
synchronized (mService) {
mWindowManager = wm;
mKeyguardController.setWindowManager(wm);
mDisplayManager =
(DisplayManager)mService.mContext.getSystemService(Context.DISPLAY_SERVICE);
mDisplayManager.registerDisplayListener(this, null);
mDisplayManagerInternal = LocalServices.getService(DisplayManagerInternal.class);
Display[] displays = mDisplayManager.getDisplays();
for (int displayNdx = displays.length - 1; displayNdx >= 0; --displayNdx) {
final int displayId = displays[displayNdx].getDisplayId();
ActivityDisplay activityDisplay = new ActivityDisplay(displayId);
if (activityDisplay.mDisplay == null) {
throw new IllegalStateException("Default Display does not exist");
}
mActivityDisplays.put(displayId, activityDisplay);
calculateDefaultMinimalSizeOfResizeableTasks(activityDisplay);
}
mHomeStack = mFocusedStack = mLastFocusedStack =
getStack(HOME_STACK_ID, CREATE_IF_NEEDED, ON_TOP);
mInputManagerInternal = LocalServices.getService(InputManagerInternal.class);
}
}
???????根據(jù)前面的分析闯团,在AMS構(gòu)造方法內(nèi)部創(chuàng)建ActivityStackSupervisor實(shí)例,根據(jù)調(diào)用關(guān)系仙粱,setWindowManager()是在SystemServer內(nèi)部的startOtherServices()內(nèi)部通過(guò)AMS來(lái)間接調(diào)用的房交,從而實(shí)現(xiàn)了ActivityDisplay的構(gòu)建;
2.2.管理
???????通過(guò)ActivityStackSupervisor內(nèi)部的mActivityDisplays進(jìn)行管理伐割;
3.ActivityStack
???????ActivityStack負(fù)責(zé)Activity在AMS的棧管理候味,用來(lái)記錄已經(jīng)啟動(dòng)的Activity的先后關(guān)系,狀態(tài)信息等口猜;
3.1.構(gòu)建
???????根據(jù)前面的分析负溪,在setWindowManager()內(nèi)部會(huì)進(jìn)行創(chuàng)建初始的ActivityStack透揣;
mHomeStack = mFocusedStack = mLastFocusedStack = getStack(HOME_STACK_ID, CREATE_IF_NEEDED, ON_TOP);
???????mHomeStack管理的是Launcher相關(guān)的Activity棧济炎;mFocusedStack管理的是當(dāng)前顯示在前臺(tái)Activity的Activity棧;mLastFocusedStack管理的是上一次顯示在前臺(tái)Activity的Activity棧辐真;
???????在執(zhí)行g(shù)etStack()時(shí)會(huì)創(chuàng)建ActivityStack實(shí)例须尚,看一下構(gòu)造方法實(shí)現(xiàn):
ActivityStack(ActivityStackSupervisor.ActivityDisplay display, int stackId,
ActivityStackSupervisor supervisor, RecentTasks recentTasks, boolean onTop) {
mStackSupervisor = supervisor;
mService = supervisor.mService;
mHandler = new ActivityStackHandler(mService.mHandler.getLooper());
mWindowManager = mService.mWindowManager;
mStackId = stackId;
mCurrentUser = mService.mUserController.getCurrentUserIdLocked();
mRecentTasks = recentTasks;
mTaskPositioner = mStackId == FREEFORM_WORKSPACE_STACK_ID
? new LaunchingTaskPositioner() : null;
mTmpRect2.setEmpty();
mWindowContainerController = createStackWindowController(display.mDisplayId, onTop,
mTmpRect2);
mStackSupervisor.mStacks.put(mStackId, this);
postAddToDisplay(display, mTmpRect2.isEmpty() ? null : mTmpRect2, onTop);
}
3.2.管理
???????新創(chuàng)建的ActivityStack會(huì)被存入ActivityStackSupervisor內(nèi)部的mStacks進(jìn)行管理;在postAddToDisplay()內(nèi)部同時(shí)會(huì)將新創(chuàng)建的ActivityStack存入ActivityDisplay內(nèi)部的mStacks進(jìn)行管理侍咱;
3.3.類型
???????系統(tǒng)定義了不同類型的Stack耐床,每一個(gè)Stack用于容納特定的類型的Activity,主要類型有以下幾種:
???????1.HOME_STACK_ID:存放home activity楔脯;
???????2.FULLSCREEN_WORKSPACE_STACK_ID:普通的Activity撩轰;
???????3.PINNED_STACK_ID:畫(huà)中畫(huà)Activity;
???????4.RECENTS_STACK_ID:Recents Activity昧廷;
4.TaskRecord
???????內(nèi)部維護(hù)一個(gè) ArrayList<ActivityRecord> 用來(lái)保存ActivityRecord堪嫂,TaskRecord中的mStack表示其所在的ActivityStack,TaskRecord與ActivityStack建立了聯(lián)系木柬;
5.簡(jiǎn)單總結(jié)
三.Activity啟動(dòng)構(gòu)建
1.啟動(dòng)模式
???????Activity啟動(dòng)有四種模式:
1.1.standard
???????標(biāo)準(zhǔn)啟動(dòng)模式皆串,也是activity的默認(rèn)啟動(dòng)模式,在這種模式下啟動(dòng)的activity可以被多次實(shí)例化眉枕,即在同一個(gè)任務(wù)中可以存在多個(gè)activity的實(shí)例恶复,每個(gè)實(shí)例都會(huì)處理一個(gè)Intent對(duì)怜森;
1.2.singleTop
???????啟動(dòng)的Activity已經(jīng)在頂部會(huì)復(fù)用,如果不在頂部則和standard類似谤牡,會(huì)重復(fù)創(chuàng)建實(shí)例副硅;
???????如果一個(gè)以singleTop模式啟動(dòng)的activity的實(shí)例已經(jīng)存在于任務(wù)桟的桟頂,那么再啟動(dòng)這個(gè)Activity時(shí)拓哟,不會(huì)創(chuàng)建新的實(shí)例想许,而是重用位于棧頂?shù)哪莻€(gè)實(shí)例,并且會(huì)調(diào)用該實(shí)例的onNewIntent()方法將Intent對(duì)象傳遞到這個(gè)實(shí)例中断序;
???????如果以singleTop模式啟動(dòng)的activity的一個(gè)實(shí)例已經(jīng)存在與任務(wù)桟中流纹,但是不在桟頂,那么它的行為和standard模式相同违诗,也會(huì)創(chuàng)建多個(gè)實(shí)例漱凝;
1.3.singleTask
???????如果一個(gè)activity的啟動(dòng)模式為singleTask,那么系統(tǒng)總會(huì)在一個(gè)新任務(wù)的最底部(root)啟動(dòng)這個(gè)activity诸迟,并且被這個(gè)activity啟動(dòng)的其他activity會(huì)和該activity同時(shí)存在于這個(gè)新任務(wù)中茸炒。
???????如果系統(tǒng)中已經(jīng)存在這樣的一個(gè)activity則會(huì)重用這個(gè)實(shí)例,清除位于SecondActivity上面的所有Activity阵苇,顯示SecondActivity壁公,并且調(diào)用他的onNewIntent()方法,即這樣的一個(gè)activity在系統(tǒng)中只會(huì)存在一個(gè)實(shí)例绅项。
1.4.singleInstance
???????總是在新的任務(wù)中開(kāi)啟紊册,并且這個(gè)新的任務(wù)中有且只有這一個(gè)實(shí)例,也就是說(shuō)被該實(shí)例啟動(dòng)的其他activity會(huì)自動(dòng)運(yùn)行于另一個(gè)任務(wù)中快耿。當(dāng)再次啟動(dòng)該activity的實(shí)例時(shí)囊陡,會(huì)重用已存在的任務(wù)和實(shí)例。并且會(huì)調(diào)用這個(gè)實(shí)例的onNewIntent()方法掀亥,將Intent實(shí)例傳遞到該實(shí)例中撞反。和singleTask相同,同一時(shí)刻在系統(tǒng)中只會(huì)存在一個(gè)這樣的Activity實(shí)例搪花。
1.5.taskAffinity
???????可以翻譯為任務(wù)相關(guān)性遏片。這個(gè)參數(shù)標(biāo)識(shí)了一個(gè) Activity 所需要的任務(wù)棧的名字,默認(rèn)情況下所有Activity所需的任務(wù)棧的名字為應(yīng)用的包名撮竿,當(dāng)Activity設(shè)置了 taskAffinity屬性吮便,那么這個(gè)Activity在被創(chuàng)建時(shí)就會(huì)運(yùn)行在和taskAffinity名字相同的任務(wù)棧中,如果沒(méi)有倚聚,則新建taskAffinity指定的任務(wù)棧线衫,并將Activity放入該棧中;另外惑折,taskAffinity屬性主要和singleTask或者
allowTaskReparenting屬性配對(duì)使用授账,在其他情況下沒(méi)有意義枯跑。
2.創(chuàng)建ActivityRecord
???????在通過(guò)startActivity()啟動(dòng)Activity時(shí),會(huì)先創(chuàng)建ActivityRecord白热,具體實(shí)現(xiàn)是在AcvityStarter內(nèi)部的startActivity()方法:
ActivityRecord r = new ActivityRecord(mService, callerApp, callingPid, callingUid,
callingPackage, intent, resolvedType, aInfo, mService.getGlobalConfiguration(),
resultRecord, resultWho, requestCode, componentSpecified, voiceSession != null,
mSupervisor, options, sourceRecord);
return startActivity(r, sourceRecord, voiceSession, voiceInteractor, startFlags, true,
options, inTask, outActivity);
???????根據(jù)Intent及ActivityInfo信息來(lái)構(gòu)建ActivityRecord敛助,然后調(diào)用startActivity來(lái)執(zhí)行后續(xù)邏輯;
3.初始化
???????跟隨調(diào)用關(guān)系屋确,會(huì)調(diào)用到ActivityStarter內(nèi)部的startActivityUnchecked()方法會(huì)調(diào)用到setInitialState()方法:
private void setInitialState(ActivityRecord r, ActivityOptions options, TaskRecord inTask,
boolean doResume, int startFlags, ActivityRecord sourceRecord,
IVoiceInteractionSession voiceSession, IVoiceInteractor voiceInteractor) {
reset();
mStartActivity = r;
mIntent = r.intent;
mOptions = options;
mSourceRecord = sourceRecord;
.....................
mSourceDisplayId = getSourceDisplayId(mSourceRecord, mStartActivity);
.................................
mLaunchSingleTop = r.launchMode == LAUNCH_SINGLE_TOP;
mLaunchSingleInstance = r.launchMode == LAUNCH_SINGLE_INSTANCE;
mLaunchSingleTask = r.launchMode == LAUNCH_SINGLE_TASK;
.....................
.....................
}
???????進(jìn)行一些初始化賦值操作纳击,將要啟動(dòng)的ActivityRecord賦值給mStartActivity等,根據(jù)r.launchMode來(lái)確定對(duì)應(yīng)的LaunchMode攻臀;
4.確定Launch Mode和Flags
???????主要通過(guò)adjustLaunchFlagsToDocumentMode()及computeLaunchingTaskFlags()進(jìn)行調(diào)整計(jì)算:
private void computeLaunchingTaskFlags() {
........................
..........................
if (mInTask == null) {
if (mSourceRecord == null) {
// This activity is not being started from another... in this case we -always- start a new task.
if ((mLaunchFlags & FLAG_ACTIVITY_NEW_TASK) == 0 && mInTask == null) {
Slog.w(TAG, "startActivity called from non-Activity context; forcing " +
"Intent.FLAG_ACTIVITY_NEW_TASK for: " + mIntent);
mLaunchFlags |= FLAG_ACTIVITY_NEW_TASK;
}
} else if (mSourceRecord.launchMode == LAUNCH_SINGLE_INSTANCE) {
// The original activity who is starting us is running as a single
// instance... this new activity it is starting must go on its own task.
mLaunchFlags |= FLAG_ACTIVITY_NEW_TASK;
} else if (mLaunchSingleInstance || mLaunchSingleTask) {
// The activity being started is a single instance... it always
// gets launched into its own task.
mLaunchFlags |= FLAG_ACTIVITY_NEW_TASK;
}
}
}
???????mInTask為null時(shí)焕数,會(huì)默認(rèn)添加FLAG_ACTIVITY_NEW_TASK;如果mSourceRecord.launchMode 是 SingleInstance刨啸,那么被他啟動(dòng)的Activity 需要添加 FLAG_ACTIVITY_NEW_TASK堡赔;如果launchMode是 SingleInstance或者 SingleTask 也需要添加 FLAG_ACTIVITY_NEW_TASK。
5.確定目標(biāo)ActivityStack
???????確定目標(biāo)ActivityStack的過(guò)程就是來(lái)初始化ActivityStarter的成員變量mTargetStack设联,分為在新的Task內(nèi)進(jìn)行啟動(dòng)setTaskFromReuseOrCreateNewTask()或在已有的Task內(nèi)進(jìn)行啟動(dòng)setTaskFromSourceRecord()等善已,主要來(lái)看一下setTaskFromReuseOrCreateNewTask():
private int setTaskFromReuseOrCreateNewTask(
TaskRecord taskToAffiliate, int preferredLaunchStackId, ActivityStack topStack) {
mTargetStack = computeStackFocus(
mStartActivity, true, mLaunchBounds, mLaunchFlags, mOptions);
..................
...................
return START_SUCCESS;
}
???????在該方法內(nèi)部會(huì)調(diào)用computeStackFocus()來(lái)確定mTargetStack,看一下邏輯實(shí)現(xiàn):
private ActivityStack computeStackFocus(ActivityRecord r, boolean newTask, Rect bounds,
int launchFlags, ActivityOptions aOptions) {
final TaskRecord task = r.getTask();
ActivityStack stack = getLaunchStack(r, launchFlags, task, aOptions);
if (stack != null) {
return stack;
}
........................
if (stack == null) {
// We first try to put the task in the first dynamic stack on home display.
final ArrayList<ActivityStack> homeDisplayStacks = mSupervisor.mHomeStack.mStacks;
for (int stackNdx = homeDisplayStacks.size() - 1; stackNdx >= 0; --stackNdx) {
stack = homeDisplayStacks.get(stackNdx);
if (isDynamicStack(stack.mStackId)) {
if (DEBUG_FOCUS || DEBUG_STACK) Slog.d(TAG_FOCUS,
"computeStackFocus: Setting focused stack=" + stack);
return stack;
}
}
// If there is no suitable dynamic stack then we figure out which static stack to use.
final int stackId = task != null ? task.getLaunchStackId() :
bounds != null ? FREEFORM_WORKSPACE_STACK_ID :
FULLSCREEN_WORKSPACE_STACK_ID;
stack = mSupervisor.getStack(stackId, CREATE_IF_NEEDED, ON_TOP);
}
if (DEBUG_FOCUS || DEBUG_STACK) Slog.d(TAG_FOCUS, "computeStackFocus: New stack r="
+ r + " stackId=" + stack.mStackId);
return stack;
}
???????主要分為三種場(chǎng)景:
???????1.在getLaunchStack()內(nèi)部根據(jù)Activity的屬性定位指定的ActivityStack离例;
if (r.isHomeActivity()) {
return mSupervisor.mHomeStack;
}
if (r.isRecentsActivity()) {
return mSupervisor.getStack(RECENTS_STACK_ID, CREATE_IF_NEEDED, ON_TOP);
}
if (r.isAssistantActivity()) {
return mSupervisor.getStack(ASSISTANT_STACK_ID, CREATE_IF_NEEDED, ON_TOP);
}
???????2.在Activity啟動(dòng)的時(shí)候Bundle是否指定了DisplayId或StackId(兩者不能同時(shí)指定)换团;
final int launchDisplayId = (aOptions != null) ? aOptions.getLaunchDisplayId() : INVALID_DISPLAY;
final int launchStackId = (aOptions != null) ? aOptions.getLaunchStackId() : INVALID_STACK_ID;
if (launchStackId != INVALID_STACK_ID && launchDisplayId != INVALID_DISPLAY) {
throw new IllegalArgumentException("Stack and display id can't be set at the same time.");
}
if (isValidLaunchStackId(launchStackId, launchDisplayId, r)) {
return mSupervisor.getStack(launchStackId, CREATE_IF_NEEDED, ON_TOP);
}
???????3.不符合以上條件時(shí),會(huì)返回stackId為FULLSCREEN_WORKSPACE_STACK_ID的ActivityStack宫蛆;
final int stackId = task != null ? task.getLaunchStackId() :
bounds != null ? FREEFORM_WORKSPACE_STACK_ID :
FULLSCREEN_WORKSPACE_STACK_ID;
stack = mSupervisor.getStack(stackId, CREATE_IF_NEEDED, ON_TOP);
6.確定TaskRecord
???????在前面setTaskFromReuseOrCreateNewTask()內(nèi)部在獲取到mTargetStack后艘包,會(huì)通過(guò)其來(lái)創(chuàng)建TaskRecord,再來(lái)看一下:
private int setTaskFromReuseOrCreateNewTask(
TaskRecord taskToAffiliate, int preferredLaunchStackId, ActivityStack topStack) {
mTargetStack = computeStackFocus(
mStartActivity, true, mLaunchBounds, mLaunchFlags, mOptions);
if (mReuseTask == null) {
final TaskRecord task = mTargetStack.createTaskRecord(
mSupervisor.getNextTaskIdForUserLocked(mStartActivity.userId),
mNewTaskInfo != null ? mNewTaskInfo : mStartActivity.info,
mNewTaskIntent != null ? mNewTaskIntent : mIntent, mVoiceSession,
mVoiceInteractor, !mLaunchTaskBehind /* toTop */, mStartActivity.mActivityType);
addOrReparentStartingActivity(task, "setTaskFromReuseOrCreateNewTask - mReuseTask");
.................................
}
.......................
}
???????1.在createTaskRecord()內(nèi)部會(huì)創(chuàng)建TaskRecord實(shí)例洒扎,然后通過(guò)addTask()將其加入到ActivityStack內(nèi)部的mTaskHistory進(jìn)行管理辑甜;
TaskRecord createTaskRecord(int taskId, ActivityInfo info, Intent intent,
IVoiceInteractionSession voiceSession, IVoiceInteractor voiceInteractor,
boolean toTop, int type) {
TaskRecord task = new TaskRecord(mService, taskId, info, intent, voiceSession,
voiceInteractor, type);
// add the task to stack first, mTaskPositioner might need the stack association
addTask(task, toTop, "createTaskRecord");
..............
task.createWindowContainer(toTop, (info.flags & FLAG_SHOW_FOR_ALL_USERS) != 0);
return task;
}
???????2.通過(guò)addOrReparentStartingActivity()內(nèi)部將ActivityRecord添加到新創(chuàng)建的TaskRecord中衰絮;
private void addOrReparentStartingActivity(TaskRecord parent, String reason) {
if (mStartActivity.getTask() == null || mStartActivity.getTask() == parent) {
parent.addActivityToTop(mStartActivity);
}
........................
}
void addActivityToTop(ActivityRecord r) {
addActivityAtIndex(mActivities.size(), r);
}
void addActivityAtIndex(int index, ActivityRecord r) {
TaskRecord task = r.getTask();
r.setTask(this);
.........................
mActivities.add(index, r);
.........................
}
???????ActivityRecord通過(guò)setTask(this)與TaskRecord建立聯(lián)系袍冷,TaskRecord將ActivityRecord加入到mActivities進(jìn)行管理;
7.與WMS關(guān)聯(lián)
???????Activity在啟動(dòng)時(shí)猫牡,會(huì)根據(jù)ActivityRecord確定ActivityStack胡诗、TaskRecord,在創(chuàng)建以上時(shí)淌友,都會(huì)在WMS創(chuàng)建對(duì)應(yīng)的管理者煌恢,在ActivityStack的startActivityLocked()內(nèi)部會(huì)創(chuàng)建ActivityRecord在WMS對(duì)應(yīng)的管理著,本文就不展開(kāi)分析了震庭,列出對(duì)應(yīng)關(guān)系圖如下:
四.其他
???????關(guān)于Activity啟動(dòng)及顯示可以參考以下文章:
???????Android activity啟動(dòng)流程分析
???????Android View 顯示原理分析
???????關(guān)于AMS關(guān)聯(lián)可以參以下文章:
???????Android WMS窗口管理
???????Android WMS窗口管理(二)