談?wù)凙MS的誕生和使用
前言
今天接著完善Android系統(tǒng)這一塊的體系架構(gòu),說(shuō)說(shuō)在App啟動(dòng)流程中舉足輕重的ActivityManagerService。
顧名思義,這個(gè)組件肯定是用來(lái)管理Activity的服務(wù),其實(shí)不僅是Activity,它還負(fù)責(zé)四大組件相關(guān)的啟動(dòng),切換,調(diào)度等等。
具體是怎么被啟動(dòng)的,又是怎么進(jìn)行管理的呢?一起看看吧。
(代碼基于Android9.0)
服務(wù)的啟動(dòng)
之前在SystemServer章節(jié)說(shuō)過(guò),系統(tǒng)的服務(wù)一般都是通過(guò)SystemServer進(jìn)程啟動(dòng)的,AMS也不例外。
- //SystemServer.java
- private void startBootstrapServices() {
- //...
- // Activity manager runs the show.
- traceBeginAndSlog("StartActivityManager");
- mActivityManagerService = mSystemServiceManager.startService(
- ActivityManagerService.Lifecycle.class).getService();
- mActivityManagerService.setSystemServiceManager(mSystemServiceManager);
- mActivityManagerService.setInstaller(installer);
- traceEnd();
- }
- //中間用到了反射,之前說(shuō)過(guò)。
- public void startService(@NonNull final SystemService service) {
- // Register it.
- mServices.add(service);
- // Start it.
- long time = SystemClock.elapsedRealtime();
- try {
- service.onStart();
- } catch (RuntimeException ex) {
- throw new RuntimeException("Failed to start service " + service.getClass().getName()
- + ": onStart threw an exception", ex);
- }
- }
- //ActivityManagerService.java
- 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 onBootPhase(int phase) {
- mService.mBootPhase = phase;
- if (phase == PHASE_SYSTEM_SERVICES_READY) {
- mService.mBatteryStatsService.systemServicesReady();
- mService.mServices.systemServicesReady();
- }
- }
- @Override
- public void onCleanupUser(int userId) {
- mService.mBatteryStatsService.onCleanupUser(userId);
- }
- public ActivityManagerService getService() {
- return mService;
- }
- }
可以看到,通過(guò)調(diào)用了ActivityManagerService.Lifecycle這個(gè)內(nèi)部類中的onStart方法,啟動(dòng)了AMS,并調(diào)用了AMS的start方法。
再簡(jiǎn)單看看AMS的實(shí)例化方法和start方法:
- public ActivityManagerService(Context systemContext) {
- mContext = systemContext;
- mFactoryTest = FactoryTest.getMode();
- mSystemThread = ActivityThread.currentActivityThread();
- mUiContext = mSystemThread.getSystemUiContext();
- mHandlerThread = new ServiceThread(TAG,
- THREAD_PRIORITY_FOREGROUND, false /*allowIo*/);
- mHandlerThread.start();
- mHandler = new MainHandler(mHandlerThread.getLooper());
- mUiHandler = mInjector.getUiHandler(this);
- //...
- mServices = new ActiveServices(this);
- mProviderMap = new ProviderMap(this);
- mAppErrors = new AppErrors(mUiContext, this);
- // TODO: Move creation of battery stats service outside of activity manager service.
- mBatteryStatsService = new BatteryStatsService(systemContext, systemDir, mHandler);
- mBatteryStatsService.getActiveStatistics().readLocked();
- mBatteryStatsService.scheduleWriteToDisk();
- mOnBattery = DEBUG_POWER ? true
- : mBatteryStatsService.getActiveStatistics().getIsOnBattery();
- mBatteryStatsService.getActiveStatistics().setCallback(this);
- mStackSupervisor = createStackSupervisor();
- mStackSupervisor.onConfigurationChanged(mTempConfig);
- mActivityStartController = new ActivityStartController(this);
- mRecentTasks = createRecentTasks();
- mStackSupervisor.setRecentTasks(mRecentTasks);
- mLockTaskController = new LockTaskController(mContext, mStackSupervisor, mHandler);
- mLifecycleManager = new ClientLifecycleManager();
- mProcessCpuThread = new Thread("CpuTracker")
- //...
- }
- private void start() {
- removeAllProcessGroups();
- mProcessCpuThread.start();
- mBatteryStatsService.publish();
- mAppOpsService.publish(mContext);
- Slog.d("AppOps", "AppOpsService published");
- LocalServices.addService(ActivityManagerInternal.class, new LocalService());
- // Wait for the synchronized block started in mProcessCpuThread,
- // so that any other acccess to mProcessCpuTracker from main thread
- // will be blocked during mProcessCpuTracker initialization.
- try {
- mProcessCpuInitLatch.await();
- } catch (InterruptedException e) {
- Slog.wtf(TAG, "Interrupted wait during start", e);
- Thread.currentThread().interrupt();
- throw new IllegalStateException("Interrupted wait during start");
- }
- }
代碼很長(zhǎng),我只截取了一部分。
在構(gòu)造函數(shù)中,主要初始化了一些對(duì)象,比如Context、ActivityThrad、Handler、CPU監(jiān)控線程,還有一些后文要用到的ActivityStackSupervisor、ActivityStarter等對(duì)象,
在start方法中,主要就是啟動(dòng)了CPU監(jiān)控線程,然后注冊(cè)了電池狀態(tài)服務(wù)和權(quán)限管理服務(wù)。
初始工作
AMS被啟動(dòng)之后,還會(huì)在SystemServer啟動(dòng)三大服務(wù)的時(shí)候偷偷干一些工作,我們搜索下mActivityManagerService變量就可以看到:
- private void startBootstrapServices() {
- //1、初始化電源管理器
- mActivityManagerService.initPowerManagement();
- //2、為系統(tǒng)進(jìn)程設(shè)置應(yīng)用程序?qū)嵗?dòng)。
- mActivityManagerService.setSystemProcess();
- }
- private void startCoreServices() {
- // 啟動(dòng)UsageStatsManager,用于查詢應(yīng)用的使用情況
- mSystemServiceManager.startService(UsageStatsService.class);
- mActivityManagerService.setUsageStatsManager(
- LocalServices.getService(UsageStatsManagerInternal.class));
- traceEnd();
- }
- private void startOtherServices() {
- //安裝系統(tǒng)的Providers
- mActivityManagerService.installSystemProviders();
- //啟動(dòng)WMS,并為AMS設(shè)置WMS關(guān)系
- wm = WindowManagerService.main(context, inputManager,
- mFactoryTestMode != FactoryTest.FACTORY_TEST_LOW_LEVEL,
- !mFirstBoot, mOnlyCore, new PhoneWindowManager());
- mActivityManagerService.setWindowManager(wm);
- //...
- }
- public void setSystemProcess() {
- try {
- ServiceManager.addService(Context.ACTIVITY_SERVICE, this, /* allowIsolated= */ true,
- DUMP_FLAG_PRIORITY_CRITICAL | DUMP_FLAG_PRIORITY_NORMAL | DUMP_FLAG_PROTO);
- }
- }
其中第二步setSystemProcess方法中,會(huì)注冊(cè)AMS到ServiceManager中,這樣后續(xù)如果需要用到AMS的時(shí)候就可以通過(guò)ServiceManager進(jìn)行獲取,下面馬上就要講到。
啟動(dòng)就說(shuō)這么多,都是比較枯燥的內(nèi)容,所以也沒有深入下去,有個(gè)印象就行,以后如果需要用到相關(guān)知識(shí)就知道去哪里找了。
從啟動(dòng)流程看AMS工作內(nèi)容
為了了解AMS的具體工作,我們就從Activity的啟動(dòng)過(guò)程看起。
上文app啟動(dòng)流程中說(shuō)過(guò),startActivityForResult方法會(huì)轉(zhuǎn)到mInstrumentation.execStartActivity方法:
- //mInstrumentation.execStartActivity
- int result = ActivityManager.getService()
- .startActivity(whoThread, who.getBasePackageName(), intent,
- intent.resolveTypeIfNeeded(who.getContentResolver()),
- token, target != null ? target.mEmbeddedID : null,
- requestCode, 0, null, options);
- checkStartActivityResult(result, intent);
- public static IActivityManager getService() {
- return IActivityManagerSingleton.get();
- }
- private static final Singleton<IActivityManager> IActivityManagerSingleton =
- new Singleton<IActivityManager>() {
- @Override
- protected IActivityManager create() {
- final IBinder b = ServiceManager.getService(Context.ACTIVITY_SERVICE);
- final IActivityManager am = IActivityManager.Stub.asInterface(b);
- return am;
- }
- };
可以看到,最終要拿到AMS的IBinder類型引用,這里的ServiceManager.getService(Context.ACTIVITY_SERVICE)是不是有點(diǎn)熟悉,沒錯(cuò),就是剛才專門調(diào)用了setSystemProcess方法對(duì)AMS進(jìn)行了注冊(cè)在ServiceManager中。然后我們要使用相關(guān)服務(wù)的方法的時(shí)候,就通過(guò)Servermanager拿到對(duì)應(yīng)服務(wù)的引用。
這里也就是拿到了IActivityManager對(duì)象,IActivityManager其實(shí)就是AMS在當(dāng)前進(jìn)程的代理,這里的邏輯就是通過(guò)AIDL做了一個(gè)進(jìn)程間的通信。因?yàn)檫@些服務(wù),包括我們今天說(shuō)的AMS都是在SystemServer進(jìn)程中的,而我們實(shí)際用到的時(shí)候是在我們自己的應(yīng)用進(jìn)程中,所以就涉及到進(jìn)程間通信了,這里是用的Binder機(jī)制進(jìn)行通信。
Binder,ServiceManager,這是Binder通信一整套流程,不光是AMS,包括其他的WMS等服務(wù)基本上都是通過(guò)Binder機(jī)制進(jìn)行進(jìn)程間通信的,具體內(nèi)容可以期待下后面說(shuō)到的Binder章節(jié)。
接著看啟動(dòng)流程,通過(guò)Binder調(diào)用到了AMS的startActivity方法,然后會(huì)調(diào)用到ActivityStarter的startActivity方法,在這個(gè)方法中,我們發(fā)現(xiàn)一個(gè)新的類:
- //ActivityStarter.java
- private int startActivity(...){
- ActivityRecord r = new ActivityRecord(mService, callerApp, callingPid, callingUid,
- callingPackage, intent, resolvedType, aInfo, mService.getGlobalConfiguration(),
- resultRecord, resultWho, requestCode, componentSpecified, voiceSession != null,
- mSupervisor, checkedOptions, sourceRecord);
- if (outActivity != null) {
- outActivity[0] = r;
- }
- //...
- return startActivity(r, sourceRecord, voiceSession, voiceInteractor, startFlags,
- true /* doResume */, checkedOptions, inTask, outActivity);
- }
ActivityRecord
這個(gè)類翻譯過(guò)來(lái)是Activity的記錄,所以猜測(cè)是和Activity有關(guān),我們點(diǎn)進(jìn)去看看它里面包含了什么:
- final ActivityManagerService service; // owner
- final IApplicationToken.Stub appToken; // window manager token
- final ActivityInfo info; // all about me
- ApplicationInfo appInfo; // information about activity's app
- final int userId; // Which user is this running for?
- final String packageName; // the package implementing intent's component
- final String processName; // process where this component wants to run
- final String taskAffinity; // as per ActivityInfo.taskAffinity
- private int icon; // resource identifier of activity's icon.
- private int logo; // resource identifier of activity's logo.
- private int theme; // resource identifier of activity's theme.
- int launchMode; // the launch mode activity attribute.
我保留了一些比較常用的屬性,大家應(yīng)該都看得出來(lái)是什么了吧,比如當(dāng)前Activity的主題——theme,當(dāng)前Activity的token——apptoken,當(dāng)前Activity的包名——packageName。
所以這個(gè)ActivityRecord其實(shí)就是保存記錄了Activity的所有信息。
接著看流程,后續(xù)會(huì)執(zhí)行到startActivityUnchecked方法,這個(gè)方法中,我們又可以看到一個(gè)新的類——TaskRecord.
TaskRecord
- private int startActivityUnchecked(final ActivityRecord r, ActivityRecord sourceRecord,
- IVoiceInteractionSession voiceSession, IVoiceInteractor voiceInteractor,
- int startFlags, boolean doResume, ActivityOptions options, TaskRecord inTask,
- ActivityRecord[] outActivity) {
- if (mStartActivity.resultTo == null && mInTask == null && !mAddingToTask
- && (mLaunchFlags & FLAG_ACTIVITY_NEW_TASK) != 0) {
- newTask = true;
- result = setTaskFromReuseOrCreateNewTask(taskToAffiliate, topStack);
- } else if (mSourceRecord != null) {
- result = setTaskFromSourceRecord();
- } else if (mInTask != null) {
- result = setTaskFromInTask();
- } else {
- // This not being started from an existing activity, and not part of a new task...
- // just put it in the top task, though these days this case should never happen.
- setTaskToCurrentTopOrCreateNewTask();
- }
- }
- // 新建一個(gè)任務(wù)棧
- private void setTaskToCurrentTopOrCreateNewTask() {
- //...
- final ActivityRecord prev = mTargetStack.getTopActivity();
- final TaskRecord task = (prev != null) ? prev.getTask() : mTargetStack.createTaskRecord(
- mSupervisor.getNextTaskIdForUserLocked(mStartActivity.userId), mStartActivity.info,
- mIntent, null, null, true, mStartActivity, mSourceRecord, mOptions);
- addOrReparentStartingActivity(task, "setTaskToCurrentTopOrCreateNewTask");
- mTargetStack.positionChildWindowContainerAtTop(task);
- }
- //添加Ac到棧頂
- private void addOrReparentStartingActivity(TaskRecord parent, String reason) {
- if (mStartActivity.getTask() == null || mStartActivity.getTask() == parent) {
- parent.addActivityToTop(mStartActivity);
- } else {
- mStartActivity.reparent(parent, parent.mActivities.size() /* top */, reason);
- }
- }
從代碼中可知,當(dāng)我們啟動(dòng)的Activity需要一個(gè)新的任務(wù)棧的時(shí)候(比如啟動(dòng)模式為FLAG_ACTIVITY_NEW_TASK),我們會(huì)走到setTaskToCurrentTopOrCreateNewTask方法中,新建一個(gè)TaskRecord類,并且把當(dāng)前的Activity通過(guò)addActivityToTop方法添加到棧頂。
所以這個(gè)TaskRecord類就是一個(gè)任務(wù)棧類了,它的作用就是維護(hù)棧內(nèi)的所有Activity,進(jìn)去看看這個(gè)類有哪些變量:
- final int taskId; // Unique identifier for this task.
- /** List of all activities in the task arranged in history order */
- final ArrayList<ActivityRecord> mActivities;
- /** Current stack. Setter must always be used to update the value. */
- private ActivityStack mStack;
這里截取了一些,可以發(fā)現(xiàn)有任務(wù)id——taskId,任務(wù)棧的所有ActivityRecord——mActivities,以及這個(gè)還不知道是什么的但是我知道是用來(lái)管理所有Activity和任務(wù)棧的大管家——ActivityStack。
ActivityStack
啟動(dòng)流程再往后面走,就會(huì)走到的ActivityStackSupervisor的resumeFocusedStackTopActivityLocked方法:
- //ActivityStackSupervisor.java
- /** The stack containing the launcher app. Assumed to always be attached to
- * Display.DEFAULT_DISPLAY. */
- ActivityStack mHomeStack;
- /** The stack currently receiving input or launching the next activity. */
- ActivityStack mFocusedStack;
- /** If this is the same as mFocusedStack then the activity on the top of the focused stack has
- * been resumed. If stacks are changing position this will hold the old stack until the new
- * stack becomes resumed after which it will be set to mFocusedStack. */
- private ActivityStack mLastFocusedStack;
- public ActivityStackSupervisor(ActivityManagerService service, Looper looper) {
- mService = service;
- mLooper = looper;
- mHandler = new ActivityStackSupervisorHandler(looper);
- }
- boolean resumeFocusedStackTopActivityLocked(
- ActivityStack targetStack, ActivityRecord target, ActivityOptions targetOptions) {
- if (targetStack != null && isFocusedStack(targetStack)) {
- return targetStack.resumeTopActivityUncheckedLocked(target, targetOptions);
- }
- final ActivityRecord r = mFocusedStack.topRunningActivityLocked();
- if (r == null || !r.isState(RESUMED)) {
- mFocusedStack.resumeTopActivityUncheckedLocked(null, null);
- } else if (r.isState(RESUMED)) {
- // Kick off any lingering app transitions form the MoveTaskToFront operation.
- mFocusedStack.executeAppTransition(targetOptions);
- }
- return false;
- }
ActivityStackSupervisor是一個(gè)管理ActivityStack的類,在AMS的構(gòu)造方法中被創(chuàng)建,這個(gè)類中可以看到有一些任務(wù)棧,比如mHomeStack——包含了Launcher APP的Activity。
然后再看看ActivityStack這個(gè)大管家家里存儲(chǔ)了什么好東西:
- enum ActivityState {
- INITIALIZING,
- RESUMED,
- PAUSING,
- PAUSED,
- STOPPING,
- STOPPED,
- FINISHING,
- DESTROYING,
- DESTROYED
- }
- private final ArrayList<TaskRecord> mTaskHistory = new ArrayList<>();
- final ArrayList<ActivityRecord> mLRUActivities = new ArrayList<>();
- ActivityRecord mPausingActivity = null;
- ActivityRecord mLastPausedActivity = null;
可以看到,在ActivityStack中:
- 有一個(gè)枚舉ActivityState,存儲(chǔ)了Activity的所有狀態(tài)。
- 有一些TaskRecord和ActivityRecord的列表,比如mTaskHistory——沒有被銷毀的任務(wù)棧列表,mLRUActivities——通過(guò)LRU計(jì)算的列表頭目是最近最少使用的Activity的ActivityRecord列表。
- 還有一些特殊狀態(tài)的Activity對(duì)應(yīng)的ActivityRecord,比如正在暫停的Activity,上一個(gè)暫停過(guò)的Activity。
最后,啟動(dòng)流程會(huì)走到AMS的startProcessLocked方法,然后跟Zygote進(jìn)程通信,fork進(jìn)程。后續(xù)就不說(shuō)了。
總結(jié)
到此,AMS中重要的三個(gè)組件我們都接觸過(guò)了,分別是:
- 管理Activity所有信息的ActivityRecord。
- 管理一個(gè)或者多個(gè)ActivityRecord的任務(wù)棧TaskRecord.
- 管理一個(gè)或者多個(gè)任務(wù)棧的管理者ActivityStack。
再來(lái)畫個(gè)圖總結(jié)下:
其實(shí)AMS里面的邏輯還有很多很多,不僅是Activity,還有其他三大組件的一些啟動(dòng)調(diào)度流程都是通過(guò)AMS完成的,還有Activity任務(wù)棧相關(guān)的內(nèi)容(包括taskAffinity、allowTaskReparenting),后續(xù)具體涉及到的時(shí)候會(huì)再細(xì)談。
本文轉(zhuǎn)載自微信公眾號(hào)「碼上積木」,可以通過(guò)以下二維碼關(guān)注。轉(zhuǎn)載本文請(qǐng)聯(lián)系碼上積木公眾號(hào)。