谈谈AMS的诞生和使用

移动开发 Android
今天接着完善Android系统这一块的体系架构,说说在App启动流程中举足轻重的ActivityManagerService。

[[375159]]

前言

今天接着完善Android系统这一块的体系架构,说说在App启动流程中举足轻重的ActivityManagerService。

顾名思义,这个组件肯定是用来管理Activity的服务,其实不仅是Activity,它还负责四大组件相关的启动,切换,调度等等。

具体是怎么被启动的,又是怎么进行管理的呢?一起看看吧。

(代码基于Android9.0)

服务的启动

之前在SystemServer章节说过,系统的服务一般都是通过SystemServer进程启动的,AMS也不例外。

  1. //SystemServer.java 
  2.     private void startBootstrapServices() { 
  3.         //... 
  4.  
  5.         // Activity manager runs the show. 
  6.         traceBeginAndSlog("StartActivityManager"); 
  7.         mActivityManagerService = mSystemServiceManager.startService( 
  8.                 ActivityManagerService.Lifecycle.class).getService(); 
  9.         mActivityManagerService.setSystemServiceManager(mSystemServiceManager); 
  10.         mActivityManagerService.setInstaller(installer); 
  11.         traceEnd(); 
  12.     } 
  13.  
  14.     //中间用到了反射,之前说过。 
  15.  
  16.  
  17.     public void startService(@NonNull final SystemService service) { 
  18.         // Register it. 
  19.         mServices.add(service); 
  20.         // Start it. 
  21.         long time = SystemClock.elapsedRealtime(); 
  22.         try { 
  23.             service.onStart(); 
  24.         } catch (RuntimeException ex) { 
  25.             throw new RuntimeException("Failed to start service " + service.getClass().getName() 
  26.                     + ": onStart threw an exception", ex); 
  27.         } 
  28.     }     
  29.  
  30.  
  31. //ActivityManagerService.java 
  32.     public static final class Lifecycle extends SystemService { 
  33.         private final ActivityManagerService mService; 
  34.  
  35.         public Lifecycle(Context context) { 
  36.             super(context); 
  37.             mService = new ActivityManagerService(context); 
  38.         } 
  39.  
  40.         @Override 
  41.         public void onStart() { 
  42.             mService.start(); 
  43.         } 
  44.  
  45.         @Override 
  46.         public void onBootPhase(int phase) { 
  47.             mService.mBootPhase = phase; 
  48.             if (phase == PHASE_SYSTEM_SERVICES_READY) { 
  49.                 mService.mBatteryStatsService.systemServicesReady(); 
  50.                 mService.mServices.systemServicesReady(); 
  51.             } 
  52.         } 
  53.  
  54.         @Override 
  55.         public void onCleanupUser(int userId) { 
  56.             mService.mBatteryStatsService.onCleanupUser(userId); 
  57.         } 
  58.  
  59.         public ActivityManagerService getService() { 
  60.             return mService; 
  61.         } 
  62.     } 

可以看到,通过调用了ActivityManagerService.Lifecycle这个内部类中的onStart方法,启动了AMS,并调用了AMS的start方法。

再简单看看AMS的实例化方法和start方法:

  1. public ActivityManagerService(Context systemContext) { 
  2.        mContext = systemContext; 
  3.  
  4.        mFactoryTest = FactoryTest.getMode(); 
  5.        mSystemThread = ActivityThread.currentActivityThread(); 
  6.        mUiContext = mSystemThread.getSystemUiContext(); 
  7.  
  8.  
  9.        mHandlerThread = new ServiceThread(TAG, 
  10.                THREAD_PRIORITY_FOREGROUND, false /*allowIo*/); 
  11.        mHandlerThread.start(); 
  12.        mHandler = new MainHandler(mHandlerThread.getLooper()); 
  13.        mUiHandler = mInjector.getUiHandler(this); 
  14.  
  15.        //... 
  16.  
  17.        mServices = new ActiveServices(this); 
  18.        mProviderMap = new ProviderMap(this); 
  19.        mAppErrors = new AppErrors(mUiContext, this); 
  20.  
  21.     
  22.        // TODO: Move creation of battery stats service outside of activity manager service. 
  23.        mBatteryStatsService = new BatteryStatsService(systemContext, systemDir, mHandler); 
  24.        mBatteryStatsService.getActiveStatistics().readLocked(); 
  25.        mBatteryStatsService.scheduleWriteToDisk(); 
  26.        mOnBattery = DEBUG_POWER ? true 
  27.                : mBatteryStatsService.getActiveStatistics().getIsOnBattery(); 
  28.        mBatteryStatsService.getActiveStatistics().setCallback(this); 
  29.  
  30.  
  31.        mStackSupervisor = createStackSupervisor(); 
  32.        mStackSupervisor.onConfigurationChanged(mTempConfig); 
  33.         
  34.        mActivityStartController = new ActivityStartController(this); 
  35.        mRecentTasks = createRecentTasks(); 
  36.        mStackSupervisor.setRecentTasks(mRecentTasks); 
  37.        mLockTaskController = new LockTaskController(mContext, mStackSupervisor, mHandler); 
  38.        mLifecycleManager = new ClientLifecycleManager(); 
  39.  
  40.        mProcessCpuThread = new Thread("CpuTracker"
  41.        //... 
  42.  
  43.    } 
  44.  
  45.  
  46.    private void start() { 
  47.        removeAllProcessGroups(); 
  48.        mProcessCpuThread.start(); 
  49.  
  50.        mBatteryStatsService.publish(); 
  51.        mAppOpsService.publish(mContext); 
  52.        Slog.d("AppOps""AppOpsService published"); 
  53.        LocalServices.addService(ActivityManagerInternal.class, new LocalService()); 
  54.        // Wait for the synchronized block started in mProcessCpuThread, 
  55.        // so that any other acccess to mProcessCpuTracker from main thread 
  56.        // will be blocked during mProcessCpuTracker initialization. 
  57.        try { 
  58.            mProcessCpuInitLatch.await(); 
  59.        } catch (InterruptedException e) { 
  60.            Slog.wtf(TAG, "Interrupted wait during start", e); 
  61.            Thread.currentThread().interrupt(); 
  62.            throw new IllegalStateException("Interrupted wait during start"); 
  63.        } 
  64.    }     

代码很长,我只截取了一部分。

在构造函数中,主要初始化了一些对象,比如Context、ActivityThrad、Handler、CPU监控线程,还有一些后文要用到的ActivityStackSupervisor、ActivityStarter等对象,

在start方法中,主要就是启动了CPU监控线程,然后注册了电池状态服务和权限管理服务。

初始工作

AMS被启动之后,还会在SystemServer启动三大服务的时候偷偷干一些工作,我们搜索下mActivityManagerService变量就可以看到:

  1. private void startBootstrapServices() { 
  2.    //1、初始化电源管理器 
  3.       mActivityManagerService.initPowerManagement(); 
  4.       //2、为系统进程设置应用程序实例并启动。 
  5.       mActivityManagerService.setSystemProcess(); 
  6.   } 
  7.  
  8.   private void startCoreServices() { 
  9.       // 启动UsageStatsManager,用于查询应用的使用情况 
  10.       mSystemServiceManager.startService(UsageStatsService.class); 
  11.       mActivityManagerService.setUsageStatsManager( 
  12.               LocalServices.getService(UsageStatsManagerInternal.class)); 
  13.       traceEnd(); 
  14.   } 
  15.  
  16.   private void startOtherServices() { 
  17.  
  18.    //安装系统的Providers 
  19.       mActivityManagerService.installSystemProviders(); 
  20.  
  21.       //启动WMS,并为AMS设置WMS关系 
  22.       wm = WindowManagerService.main(context, inputManager, 
  23.                   mFactoryTestMode != FactoryTest.FACTORY_TEST_LOW_LEVEL, 
  24.                   !mFirstBoot, mOnlyCore, new PhoneWindowManager()); 
  25.       mActivityManagerService.setWindowManager(wm); 
  26.  
  27.       //... 
  28.   } 
  29.  
  30.  
  31.  
  32.   public void setSystemProcess() { 
  33.       try { 
  34.           ServiceManager.addService(Context.ACTIVITY_SERVICE, this, /* allowIsolated= */ true
  35.                   DUMP_FLAG_PRIORITY_CRITICAL | DUMP_FLAG_PRIORITY_NORMAL | DUMP_FLAG_PROTO); 
  36.       } 
  37.   } 

其中第二步setSystemProcess方法中,会注册AMS到ServiceManager中,这样后续如果需要用到AMS的时候就可以通过ServiceManager进行获取,下面马上就要讲到。

启动就说这么多,都是比较枯燥的内容,所以也没有深入下去,有个印象就行,以后如果需要用到相关知识就知道去哪里找了。

从启动流程看AMS工作内容

为了了解AMS的具体工作,我们就从Activity的启动过程看起。

上文app启动流程中说过,startActivityForResult方法会转到mInstrumentation.execStartActivity方法:

  1. //mInstrumentation.execStartActivity 
  2.     int result = ActivityManager.getService() 
  3.                 .startActivity(whoThread, who.getBasePackageName(), intent, 
  4.                         intent.resolveTypeIfNeeded(who.getContentResolver()), 
  5.                         token, target != null ? target.mEmbeddedID : null
  6.                         requestCode, 0, null, options); 
  7.     checkStartActivityResult(result, intent); 
  8.  
  9.  
  10.     public static IActivityManager getService() { 
  11.         return IActivityManagerSingleton.get(); 
  12.     } 
  13.  
  14.     private static final Singleton<IActivityManager> IActivityManagerSingleton = 
  15.             new Singleton<IActivityManager>() { 
  16.                 @Override 
  17.                 protected IActivityManager create() { 
  18.                     final IBinder b = ServiceManager.getService(Context.ACTIVITY_SERVICE); 
  19.                     final IActivityManager am = IActivityManager.Stub.asInterface(b); 
  20.                     return am; 
  21.                 } 
  22.             }; 

可以看到,最终要拿到AMS的IBinder类型引用,这里的ServiceManager.getService(Context.ACTIVITY_SERVICE)是不是有点熟悉,没错,就是刚才专门调用了setSystemProcess方法对AMS进行了注册在ServiceManager中。然后我们要使用相关服务的方法的时候,就通过Servermanager拿到对应服务的引用。

这里也就是拿到了IActivityManager对象,IActivityManager其实就是AMS在当前进程的代理,这里的逻辑就是通过AIDL做了一个进程间的通信。因为这些服务,包括我们今天说的AMS都是在SystemServer进程中的,而我们实际用到的时候是在我们自己的应用进程中,所以就涉及到进程间通信了,这里是用的Binder机制进行通信。

Binder,ServiceManager,这是Binder通信一整套流程,不光是AMS,包括其他的WMS等服务基本上都是通过Binder机制进行进程间通信的,具体内容可以期待下后面说到的Binder章节。

接着看启动流程,通过Binder调用到了AMS的startActivity方法,然后会调用到ActivityStarter的startActivity方法,在这个方法中,我们发现一个新的类:

  1. //ActivityStarter.java 
  2. private int startActivity(...){ 
  3.         ActivityRecord r = new ActivityRecord(mService, callerApp, callingPid, callingUid, 
  4.                 callingPackage, intent, resolvedType, aInfo, mService.getGlobalConfiguration(), 
  5.                 resultRecord, resultWho, requestCode, componentSpecified, voiceSession != null
  6.                 mSupervisor, checkedOptions, sourceRecord); 
  7.         if (outActivity != null) { 
  8.             outActivity[0] = r; 
  9.         } 
  10.  
  11.         //... 
  12.  
  13.         return startActivity(r, sourceRecord, voiceSession, voiceInteractor, startFlags, 
  14.                 true /* doResume */, checkedOptions, inTask, outActivity);     

ActivityRecord

这个类翻译过来是Activity的记录,所以猜测是和Activity有关,我们点进去看看它里面包含了什么:

  1. final ActivityManagerService service; // owner 
  2.     final IApplicationToken.Stub appToken; // window manager token 
  3.   
  4.     final ActivityInfo info; // all about me 
  5.     ApplicationInfo appInfo; // information about activity's app 
  6.     final int userId;          // Which user is this running for
  7.     final String packageName; // the package implementing intent's component 
  8.     final String processName; // process where this component wants to run 
  9.     final String taskAffinity; // as per ActivityInfo.taskAffinity 
  10.  
  11.     private int icon;               // resource identifier of activity's icon. 
  12.     private int logo;               // resource identifier of activity's logo. 
  13.     private int theme;              // resource identifier of activity's theme. 
  14.     int launchMode;         // the launch mode activity attribute. 

我保留了一些比较常用的属性,大家应该都看得出来是什么了吧,比如当前Activity的主题——theme,当前Activity的token——apptoken,当前Activity的包名——packageName。

所以这个ActivityRecord其实就是保存记录了Activity的所有信息。

接着看流程,后续会执行到startActivityUnchecked方法,这个方法中,我们又可以看到一个新的类——TaskRecord.

TaskRecord

  1. private int startActivityUnchecked(final ActivityRecord r, ActivityRecord sourceRecord, 
  2.             IVoiceInteractionSession voiceSession, IVoiceInteractor voiceInteractor, 
  3.             int startFlags, boolean doResume, ActivityOptions options, TaskRecord inTask, 
  4.             ActivityRecord[] outActivity) { 
  5.  
  6.         if (mStartActivity.resultTo == null && mInTask == null && !mAddingToTask 
  7.                 && (mLaunchFlags & FLAG_ACTIVITY_NEW_TASK) != 0) { 
  8.             newTask = true
  9.             result = setTaskFromReuseOrCreateNewTask(taskToAffiliate, topStack); 
  10.         } else if (mSourceRecord != null) { 
  11.             result = setTaskFromSourceRecord(); 
  12.         } else if (mInTask != null) { 
  13.             result = setTaskFromInTask(); 
  14.         } else { 
  15.             // This not being started from an existing activity, and not part of a new task... 
  16.             // just put it in the top task, though these days this case should never happen. 
  17.             setTaskToCurrentTopOrCreateNewTask(); 
  18.         } 
  19.  
  20.  
  21. // 新建一个任务栈 
  22.     private void setTaskToCurrentTopOrCreateNewTask() { 
  23.         //... 
  24.         final ActivityRecord prev = mTargetStack.getTopActivity(); 
  25.         final TaskRecord task = (prev != null) ? prev.getTask() : mTargetStack.createTaskRecord( 
  26.                 mSupervisor.getNextTaskIdForUserLocked(mStartActivity.userId), mStartActivity.info, 
  27.                 mIntent, nullnulltrue, mStartActivity, mSourceRecord, mOptions); 
  28.         addOrReparentStartingActivity(task, "setTaskToCurrentTopOrCreateNewTask"); 
  29.         mTargetStack.positionChildWindowContainerAtTop(task); 
  30.     } 
  31.  
  32.     //添加Ac到栈顶 
  33.     private void addOrReparentStartingActivity(TaskRecord parent, String reason) { 
  34.         if (mStartActivity.getTask() == null || mStartActivity.getTask() == parent) { 
  35.             parent.addActivityToTop(mStartActivity); 
  36.         } else { 
  37.             mStartActivity.reparent(parent, parent.mActivities.size() /* top */, reason); 
  38.         } 
  39.     } 

从代码中可知,当我们启动的Activity需要一个新的任务栈的时候(比如启动模式为FLAG_ACTIVITY_NEW_TASK),我们会走到setTaskToCurrentTopOrCreateNewTask方法中,新建一个TaskRecord类,并且把当前的Activity通过addActivityToTop方法添加到栈顶。

所以这个TaskRecord类就是一个任务栈类了,它的作用就是维护栈内的所有Activity,进去看看这个类有哪些变量:

  1. final int taskId;       // Unique identifier for this task. 
  2.  
  3.    /** List of all activities in the task arranged in history order */ 
  4.    final ArrayList<ActivityRecord> mActivities; 
  5.  
  6.    /** Current stack. Setter must always be used to update the value. */ 
  7.    private ActivityStack mStack; 

这里截取了一些,可以发现有任务id——taskId,任务栈的所有ActivityRecord——mActivities,以及这个还不知道是什么的但是我知道是用来管理所有Activity和任务栈的大管家——ActivityStack。

ActivityStack

启动流程再往后面走,就会走到的ActivityStackSupervisor的resumeFocusedStackTopActivityLocked方法:

  1. //ActivityStackSupervisor.java 
  2.  
  3.     /** The stack containing the launcher app. Assumed to always be attached to 
  4.      * Display.DEFAULT_DISPLAY. */ 
  5.     ActivityStack mHomeStack; 
  6.  
  7.     /** The stack currently receiving input or launching the next activity. */ 
  8.     ActivityStack mFocusedStack; 
  9.  
  10.     /** If this is the same as mFocusedStack then the activity on the top of the focused stack has 
  11.      * been resumed. If stacks are changing position this will hold the old stack until the new 
  12.      * stack becomes resumed after which it will be set to mFocusedStack. */ 
  13.     private ActivityStack mLastFocusedStack; 
  14.  
  15.  
  16.     public ActivityStackSupervisor(ActivityManagerService service, Looper looper) { 
  17.         mService = service; 
  18.         mLooper = looper; 
  19.         mHandler = new ActivityStackSupervisorHandler(looper); 
  20.     } 
  21.  
  22.  
  23.     boolean resumeFocusedStackTopActivityLocked( 
  24.             ActivityStack targetStack, ActivityRecord target, ActivityOptions targetOptions) { 
  25.  
  26.  
  27.         if (targetStack != null && isFocusedStack(targetStack)) { 
  28.             return targetStack.resumeTopActivityUncheckedLocked(target, targetOptions); 
  29.         } 
  30.  
  31.         final ActivityRecord r = mFocusedStack.topRunningActivityLocked(); 
  32.         if (r == null || !r.isState(RESUMED)) { 
  33.             mFocusedStack.resumeTopActivityUncheckedLocked(nullnull); 
  34.         } else if (r.isState(RESUMED)) { 
  35.             // Kick off any lingering app transitions form the MoveTaskToFront operation. 
  36.             mFocusedStack.executeAppTransition(targetOptions); 
  37.         } 
  38.  
  39.         return false
  40.     } 

ActivityStackSupervisor是一个管理ActivityStack的类,在AMS的构造方法中被创建,这个类中可以看到有一些任务栈,比如mHomeStack——包含了Launcher APP的Activity。

然后再看看ActivityStack这个大管家家里存储了什么好东西:

  1. enum ActivityState { 
  2.      INITIALIZING, 
  3.      RESUMED, 
  4.      PAUSING, 
  5.      PAUSED, 
  6.      STOPPING, 
  7.      STOPPED, 
  8.      FINISHING, 
  9.      DESTROYING, 
  10.      DESTROYED 
  11.  } 
  12.  
  13.  
  14.  
  15.  private final ArrayList<TaskRecord> mTaskHistory = new ArrayList<>(); 
  16.  
  17.  final ArrayList<ActivityRecord> mLRUActivities = new ArrayList<>(); 
  18.  
  19.  ActivityRecord mPausingActivity = null
  20.  
  21.  ActivityRecord mLastPausedActivity = null;     

可以看到,在ActivityStack中:

  • 有一个枚举ActivityState,存储了Activity的所有状态。
  • 有一些TaskRecord和ActivityRecord的列表,比如mTaskHistory——没有被销毁的任务栈列表,mLRUActivities——通过LRU计算的列表头目是最近最少使用的Activity的ActivityRecord列表。
  • 还有一些特殊状态的Activity对应的ActivityRecord,比如正在暂停的Activity,上一个暂停过的Activity。

最后,启动流程会走到AMS的startProcessLocked方法,然后跟Zygote进程通信,fork进程。后续就不说了。

总结

到此,AMS中重要的三个组件我们都接触过了,分别是:

  • 管理Activity所有信息的ActivityRecord。
  • 管理一个或者多个ActivityRecord的任务栈TaskRecord.
  • 管理一个或者多个任务栈的管理者ActivityStack。

再来画个图总结下:

其实AMS里面的逻辑还有很多很多,不仅是Activity,还有其他三大组件的一些启动调度流程都是通过AMS完成的,还有Activity任务栈相关的内容(包括taskAffinity、allowTaskReparenting),后续具体涉及到的时候会再细谈。

 本文转载自微信公众号「码上积木」,可以通过以下二维码关注。转载本文请联系码上积木公众号。

 

责任编辑:武晓燕 来源: 码上积木
相关推荐

2021-08-05 10:30:44

FlutterRunApp流程

2012-08-27 16:20:10

Windows 7操作系统

2009-10-09 14:55:02

VB.NET数组

2012-06-29 13:45:53

XML

2023-08-07 14:52:33

WindowsExplorer进程

2012-03-26 11:32:45

Java

2017-08-22 16:25:14

CSSHTML选择器

2016-09-09 12:51:23

PhxSQL原则局限性

2017-11-09 15:38:26

OpenRTB 3.0演化

2021-01-21 15:36:27

AndroidAMSSDK

2021-10-29 16:36:53

AMSAndroidActivityMan

2012-04-16 15:08:33

2016-07-01 16:13:13

AWSLambda

2022-01-04 20:52:50

函数异步Promise

2015-06-29 13:54:46

WLANWi-FiWiMax

2020-07-01 07:44:06

javaSE==equals

2018-12-26 13:22:05

NVMeNVMe-oF数据

2012-07-09 14:25:04

程序集加载

2022-10-08 00:00:02

Docker项目技术

2020-10-05 21:38:35

pythonprettyprintpprint
点赞
收藏

51CTO技术栈公众号