一 AMS是什么,和ATMS什么关系?
1.1 AMS是什么?
ActivityManagerService 是 Android 系统中一个特别重要的系统服务,也是我们上层 APP 打交道最多的系统服务之一。ActivityManagerService(以下简称AMS) 主要负责四大组件的启动、切换、调度以及应用进程的管理和调度工作。
- 从 java 角度来看,AMS 就是一个 java 对象,实现了 Ibinder 接口,所以它是一个用于进程之间通信的接口,这个对象初始化是在 SystemServer.java 的 run() 方法里面;
- 从名字就可以看出,ActivityManagerService它是一个服务,用来管理 Activity,而且是一个系统服务,就是包管理服务,电池管理服务,震动管理服务等;
- AMS 实现了 Ibinder 接口,所以它是一个 Binder,这意味着他不但可以用于进程间通信,还是一个线程,因为一个 Binder 就是一个线程;
- 从系统运行的角度看,AMS可以分为Client端和Service端:
Client端运行在各个app进程,app进程实现了具体的 Activity,Service等,告诉系统我有那些Activity,Service等,并且调用系统接口来完成显示;
Service端运行在 SystemServer进程,是系统级别的ActivityManagerService的具体实现,其响应Client端的系统调用请求,并且管理 Client端各个app进程的生命周期。
1.2 AMS基本类图
App与ActivityManagerService之间是通过Binder通信的,具体涉及到的类调用关系通过几张图片总结如下。
1.2.1 APP如何调用AMS方法
例如:
ActivityManager activityManger = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE); List<ActivityManager.RunningAppProcessInfo> runningAppProcesses = activityManger.getRunningAppProcesses();
1.2.2 AMS如何调用App方法
1.2.3 APP与AMS通信框架
1.3 AMS内部主要数据结构类图
1.4 AMS与ATMS关系
从 Android10 的代码变更看,谷歌最终的目的是把 activity 和 window 融合,目前发布的版本虽然做了大量的代码变更,但和 P 之前的版本的流程变化不大,目前只是简单的把代码整理到一起了,还属于中间状态,按 android 文档介绍,完全融合在 M 甚至更靠后的版本才能完成。目前已完成的工作:
- 把 AMS 下面只和 activity 管理相关的代码移到 WMS 的目录下,actvityStack、activityRecord 等文件,全部移到 WMS 目录下,和 window 统一管理.
- AMS 中部分文件拆分,把原来 activity 和其他组件融合在一起处理的文件进行拆分,activity 相关部分单独拆分,移到 WMS 中统一管理。比如 ActivityManagerService.java 拆分成了 ActivityManagerService.java 和 ActivityTaskManagerService.java 两个文件,activity 的启动由ActivityTaskManagerService.java 负责。
- 因为 Activity 和 window 的管理统一由 WMS 完成,不再需要之前DispayWindowController、stackWindowController 来居中协调,可以把 display、stack、task 等统一管理。最终要做到完全融合,以 stack 为例,完成后会把 taskstack 的功能完全融合进 activityStack,目前只做到了在 activityStack 中包含 taskstack。创建、管理流程也随之发生变化。
1.5 AMS与ServiceManager什么关系?
ServiceManager其实就是用来获取AMS、PMS等服务的Binder对象,然后就可以通过AMS等服务的IBinder对象与对应的AMS进行跨进程通信。AMS等服务在启动的时候就会把其IBinder对象注册到ServiceManager中(见4.6,ATMS把IBinder注册到ServiceManager见4.4.1),然后客户端找到ServiceManager,然后通过ServiceManager找到AMS的IBinder返回给客户端,然后客户端就可以通过该AMS的IBinder与AMS进行跨进程通信。
ServiceManager是什么?
AMS把注册服务到ServiceManager:
客户端通过ServiceManager获取AMS服务:
二 假如让你设计多种服务管理,架构怎么设计?
首先定义抽象服务类
public abstract class SystemService {
public abstract void onStart();
}
定义具体服务类比如PowerManagerService
public class PowerManagerService extends SystemService{
private Context mContext;
public PowerManagerService(Context mContext) {
this.mContext = mContext;
}
@Override
public void onStart() {
Log.w("chric", "PowerManagerService start");
}
}
定义具体服务类ActivityManagerService ActivityTaskManagerService但是AMS和ATMS都已经继承IActivityTaskManager.Stub和 IActivityManger.Stub了,java不能多继承,如何实现呢?
采用静态内部类:
public class ActivityManagerService extends IActivityManger.Stub{
public ActivityManagerService(Context context) {
}
private void start() {
Log.w("chric", "ActivityManagerService start");
}
public static final class Lifecycle extends SystemService {
private final ActivityManagerService mService;
public Lifecycle(Context context) {
mService = new ActivityManagerService(context);
}
@Override
public void onStart() {
mService.start();
}
public ActivityManagerService getService() {
return mService;
}
}
}
public class ActivityTaskManagerService extends IActivityTaskManager.Stub{
public ActivityTaskManagerService(Context context) {
}
private void start() {
Log.w("chric", "ActivityTaskManagerService start");
}
public static final class Lifecycle extends SystemService {
private final ActivityTaskManagerService mService;
public Lifecycle(Context context) {
mService = new ActivityTaskManagerService(context);
}
@Override
public void onStart() {
mService.start();
}
public ActivityTaskManagerService getService() {
return mService;
}
}
}
定义系统服务管理类SystemServiceManager
public class SystemServiceManager {
private Context mContext;
private final ArrayList<SystemService> mServices = new ArrayList<SystemService>();
SystemServiceManager(Context context) {
mContext = context;
}
public <T extends SystemService> T startService(Class<T> serviceClass) {
final String name = serviceClass.getName();
final T service;
try {
Constructor<T> constructor = serviceClass.getConstructor(Context.class);
service = constructor.newInstance(mContext);
} catch (InstantiationException ex) {
throw new RuntimeException("Failed to create service " + name
+ ": service could not be instantiated", ex);
} catch (IllegalAccessException ex) {
throw new RuntimeException("Failed to create service " + name
+ ": service must have a public constructor with a Context argument", ex);
} catch (NoSuchMethodException ex) {
throw new RuntimeException("Failed to create service " + name
+ ": service must have a public constructor with a Context argument", ex);
} catch (InvocationTargetException ex) {
throw new RuntimeException("Failed to create service " + name
+ ": service constructor threw an exception", ex);
}
startService(service);
return service;
}
public void startService(final SystemService service) {
mServices.add(service);
service.onStart();
}
}
定义服务启动类SystemServer
public class SystemServer {
private SystemServiceManager mSystemServiceManager;
private Context mSystemContext;
public SystemServer(Context context) {
mSystemContext = context;
}
public void run() {
mSystemServiceManager = new SystemServiceManager(mSystemContext);
startBootstrapServices();
}
private void startBootstrapServices() {
ActivityTaskManagerService atm = mSystemServiceManager.startService(
ActivityTaskManagerService.Lifecycle.class).getService();
ActivityManagerService ams = mSystemServiceManager.startService(
ActivityManagerService.Lifecycle.class).getService();
PowerManagerService powerManagerService = mSystemServiceManager.startService(
PowerManagerService.class);
}
}
run一下试试,日志如下:
2024-05-09 23:23:21.750 8691-8691/com.example.sourcecode W/chric: ActivityTaskManagerService start
2024-05-09 23:23:21.750 8691-8691/com.example.sourcecode W/chric: ActivityManagerService start
2024-05-09 23:23:21.751 8691-8691/com.example.sourcecode W/chric: PowerManagerService start
这样我们学习到了,抽象类、静态内部类、反射、泛型,这样我们不断学习源码将这些知识运用到我们自己的项目中,才是真正的掌握。
三 AMS启动时序概览
AMS 启动主要分为以下4个阶段:
阶段1:SystemSerer 进程创建 Android 运行环境。AMS 运行在 SystemServer 进程中,它的许多工作依赖于该运行环境
createSystemContext() -> new ActvityThread()->attach ->getSystemContext ->createSystemContext
阶段2:启动 AMS,主要进行一些初始化工作
new ActivityManagerService()
start()
阶段3:将 SystemServer 进程纳入到 AMS 的进程管理体系中
//将framework-res.apk的信息加入到SystemServer进程的LoadedApk中
//构建SystemServer进程的ProcessRecord,保存到AMS中,以便AMS进程统一管理
setSystemProcess()
installSystemProviders() //安装SystemServer进程中的SettingsProvider.apk
阶段4:AMS 启动完成,通知服务或应用完成后续的工作,或直接启动一些进程AMS.systemReady() 许多服务或应用进程必须等待 AMS 完成启动工作后,才能启动或进行一些后续工作;AMS 就是在 systemReady 中,通知或者启动这些等待的服务和应用进程,例如启动桌面等。
ActivityManagerService时序图如下:
四 AMS启动详细流程
4.1 SystemServer.run
frameworks/base/services/java/com/android/server/SystemServer.java
public static void main(String[] args) {
new SystemServer().run();
}
private void run() {
........
createSystemContext();//初始化 System Context
//初始化SystemServiceManager,用来管理后面的服务
mSystemServiceManager = new SystemServiceManager(mSystemContext);
mSystemServiceManager.setStartInfo(mRuntimeRestart,
mRuntimeStartElapsedTime, mRuntimeStartUptime);
LocalServices.addService(SystemServiceManager.class, mSystemServiceManager);
........
startBootstrapServices(); //启动引导服务(相互依赖关系复杂的服务)
startCoreServices(); //启动核心服务(相互独立的基本服务)
startOtherServices(); //启动其他服务
........
}
4.1.1 SystemServer.startBootstrapServices
private void startBootstrapServices() {
........
//启动ActivityTaskManagerService服务,简称ATM
atm = mSystemServiceManager.startService(
ActivityTaskManagerService.Lifecycle.class).getService();
//启动ActivityManagerService,简称AMS
mActivityManagerService = ActivityManagerService.Lifecycle.startService(
mSystemServiceManager, atm);
//设置AMS服务的系统服务管理器
mActivityManagerService.setSystemServiceManager(mSystemServiceManager);
mActivityManagerService.setInstaller(installer);//设置AMS的App安装器
mActivityManagerService.initPowerManagement();//初始化PWS
//设置系统进程的应用程序实例
mActivityManagerService.setSystemProcess();
........
}
启动引导服务,在其中启动了 ATM 和 AMS 服务,其中的 ATM 是 Android10 新引入的功能,用来管理 Activity 的启动、调度等功能.并且通过 AMS 安装 Installer、初始化 Power,设置系统进程等。
4.1.2 SystemServer.startOtherServices
private void startOtherServices() {
........
//安装SettingsProvider.apk
mActivityManagerService.installSystemProviders();
//创建并设置WMS和IMS
inputManager = new InputManagerService(context);
wm = WindowManagerService.main(context, inputManager, !mFirstBoot, mOnlyCore,
new PhoneWindowManager(), mActivityManagerService.mActivityTaskManager);
ServiceManager.addService(Context.WINDOW_SERVICE, wm, /* allowIsolated= */ false,
DUMP_FLAG_PRIORITY_CRITICAL | DUMP_FLAG_PROTO);
ServiceManager.addService(Context.INPUT_SERVICE, inputManager,
/* allowIsolated= */ false, DUMP_FLAG_PRIORITY_CRITICAL);
mActivityManagerService.setWindowManager(wm);
//AMS启动完成,完成后续的工作,例如启动桌面等
mActivityManagerService.systemReady(() -> {
........
}, BOOT_TIMINGS_TRACE_LOG);
........
}
启动其他服务,AMS 启动后,完成后续桌面启动,SystemUI 启动等操作.
4.2 SystemServer.createSystemContext
private void createSystemContext() {
ActivityThread activityThread = ActivityThread.systemMain();
mSystemContext = activityThread.getSystemContext();
mSystemContext.setTheme(DEFAULT_SYSTEM_THEME);
final Context systemUiContext = activityThread.getSystemUiContext();
systemUiContext.setTheme(DEFAULT_SYSTEM_THEME);
}
public static ActivityThread systemMain() {
if (!ActivityManager.isHighEndGfx()) {
ThreadedRenderer.disable(true);
} else {
ThreadedRenderer.enableForegroundTrimming();
}
ActivityThread thread = new ActivityThread();
thread.attach(true, 0);
return thread;
}
在 SystemServer 的 run 函数中,在启动 AMS 之前,调用了 createSystemContext 函数,主要用来初始化 System Context 和 SystemUI Context,并设置主题.当调用 createSystemContext() 完毕后,主要完成以下两个工作:
- 得到了一个 ActivityThread 对象,它代表当前进程 (此时为系统进程) 的主线程;
- 得到了一个 Context 对象,对于 SystemServer 而言,它包含的 Application 运行环境与 framework-res.apk 有关
4.2.1 ActivityThread对象创建
public final class ActivityThread extends ClientTransactionHandler {
........
//定义了AMS与应用通信的接口,拿到ApplicationThread的对象
final ApplicationThread mAppThread = new ApplicationThread();
//拥有自己的looper,说明ActivityThread确实可以代表事件处理线程
final Looper mLooper = Looper.myLooper();
//H继承Handler,ActivityThread中大量事件处理依赖此Handler
final H mH = new H();
//用于保存该进程的ActivityRecord
final ArrayMap<IBinder, ActivityClientRecord> mActivities = new ArrayMap<>();
//用于保存进程中的Service
final ArrayMap<IBinder, Service> mServices = new ArrayMap<>();
//用于保存进程中的Application
final ArrayList<Application> mAllApplications
= new ArrayList<Application>();
//构造函数
@UnsupportedAppUsage
ActivityThread() {
mResourcesManager = ResourcesManager.getInstance();
}
}
ActivityThread 是 Android Framework 中一个非常重要的类,它代表一个应用进程的主线程,其职责就是调度及执行在该线程中运行的四大组件。 注意此处的 ActivityThread 创建于 SystemServer 进程中。 由于 SystemServer 中也运行着一些系统 APK,例如 framework-res.apk、SettingsProvider.apk 等,因此也可以认为 SystemServer 是一个特殊的应用进程。
AMS 负责管理和调度进程,因此 AMS 需要通过 Binder 机制和应用进程通信.为此,Android 提供了一个 IApplicationThread 接口,该接口定义了 AMS 和应用进程之间的交互函数。ActivityThread 的构造函数比较简单,获取 ResourcesManager 的单例对象,需要重点关注的是它的成员变量.
4.2.2 ActivityThread.attach
private void attach(boolean system, long startSeq) {
mSystemThread = system;
if (!system) {
//应用进程的处理流程
........
} else {//传入的system为true
//系统进程的处理流程,该情况只在SystemServer中处理
//创建ActivityThread中的重要成员:Instrumentation、 Application 和 Context
mInstrumentation = new Instrumentation();
mInstrumentation.basicInit(this);
//创建系统的Context
ContextImpl context = ContextImpl.createAppContext(
this, getSystemContext().mPackageInfo);
//调用LoadedApk的makeApplication函数
mInitialApplication = context.mPackageInfo.makeApplication(true, null);
mInitialApplication.onCreate();
}
}
对于系统进程而言,ActivityThread 的 attach 函数最重要的工作就是创建了 Instrumentation、Application 和 Context.
Instrumentation 是 Android 中的一个工具类,当该类被启用时,它将优先于应用中其它的类被初始化。 此时,系统先创建它,再通过它创建其它组件。
mInstrumentation = new Instrumentation();
mInstrumentation.basicInit(this);
Context 是 Android 中的一个抽象类,用于维护应用运行环境的全局信息。通过 Context 可以访问应用的资源和类,甚至进行系统级的操作,例如启动 Activity、发送广播等。ActivityThread 的 attach 函数中,通过下面的代码创建出系统应用对应的 Context:
ContextImpl context = ContextImpl.createAppContext(
this, getSystemContext().mPackageInfo);
Application 是用于保存应用的全局状态。在 ActivityThread 中,针对系统进程,通过下面的代码创建初始的 Application:
mInitialApplication = context.mPackageInfo.makeApplication(true, null);
mInitialApplication.onCreate();
4.2.3 ContextImpl.getSystemContext
public ContextImpl getSystemContext() {
synchronized (this) {
if (mSystemContext == null) {
//调用ContextImpl的静态函数createSystemContext
mSystemContext = ContextImpl.createSystemContext(this);
}
return mSystemContext;
}
}
createSystemContext 的内容就是创建一个 LoadedApk,然后初始化一个 ContextImpl 对象。 注意在 createSystemContext 函数中,创建的 LoadApk 对应 packageName 为 ”android”,也就是 framwork-res.apk.由于该 APK 仅供 SystemServer 进程使用,因此创建的 Context 被定义为 System Context。 现在该 LoadedApk 还没有得到 framwork-res.apk 实际的信息。当 PKMS 启动,完成对应的解析后,AMS 将重新设置这个 LoadedApk。
static ContextImpl createSystemContext(ActivityThread mainThread) {
//创建LoadedApk类,代表一个加载到系统中的APK
//注意此时的LoadedApk只是一个空壳
//PKMS还没有启动,无法得到有效的ApplicationInfo
LoadedApk packageInfo = new LoadedApk(mainThread);
//拿到ContextImpl 的对象
ContextImpl context = new ContextImpl(null, mainThread, packageInfo,
null, null, null, 0, null, null);
context.setResources(packageInfo.getResources());//初始化资源信息
context.mResources.updateConfiguration(
context.mResourcesManager.getConfiguration(),
context.mResourcesManager.getDisplayMetrics());
return context;
}
4.3 SystemServiceManager创建
private void run() {
........
//创建SystemServiceManager对象
mSystemServiceManager = new SystemServiceManager(mSystemContext);
mSystemServiceManager.setStartInfo(mRuntimeRestart,
mRuntimeStartElapsedTime, mRuntimeStartUptime);
LocalServices.addService(SystemServiceManager.class, mSystemServiceManager);
........
}
通过 SystemServiceManager 的构造方法创建一个 SystemServiceManager 对象,并将该对象添加到 LocalServices 中
4.3.1 SystemServiceManager
public class SystemServiceManager {
........
private final Context mContext;
private final ArrayList<SystemService> mServices = new ArrayList<SystemService>();
........
SystemServiceManager(Context context) {
mContext = context;
}
public SystemService startService(String className) {
final Class<SystemService> serviceClass;
try {
//通过反射根据类名,拿到类对象
serviceClass = (Class<SystemService>)Class.forName(className);
} catch (ClassNotFoundException ex) {
Slog.i(TAG, "Starting " + className);
........
}
return startService(serviceClass);
}
public <T extends SystemService> T startService(Class<T> serviceClass) {
try {
final String name = serviceClass.getName();
// Create the service.
final T service;
........
service = constructor.newInstance(mContext);
........
startService(service);
return service;
} finally {
Trace.traceEnd(Trace.TRACE_TAG_SYSTEM_SERVER);
}
}
public void startService(@NonNull final SystemService service) {
mServices.add(service);// Register it.
long time = SystemClock.elapsedRealtime();// Start it.
try {
service.onStart(); //调用各个服务中的onStart()方法完成服务启动
} catch (RuntimeException ex) {
........
}
}
}
SystemServiceManager 主要用于管理 SystemService 的创建、启动等生命周期,SystemService 类是一个抽象类,在 SystemServiceManager 中都是通过反射创建 SystemService 对象的,然后在 startService 方法中,会将 SystemService 添加到 mServices 中,并调用 onStart() 方法.SystemServiceManager 构造函数没有多少内容,主要是把传进来的 system Context 赋值给 mContext,供后续服务创建使用.
4.3.2 LocalServices.addService
public final class LocalServices {
private LocalServices() {}
private static final ArrayMap<Class<?>, Object> sLocalServiceObjects =
new ArrayMap<Class<?>, Object>();
//返回实现指定接口的本地服务实例对象
@SuppressWarnings("unchecked")
public static <T> T getService(Class<T> type) {
synchronized (sLocalServiceObjects) {
return (T) sLocalServiceObjects.get(type);
}
}
//将指定接口的服务实例添加到本地服务的全局注册表中
public static <T> void addService(Class<T> type, T service) {
synchronized (sLocalServiceObjects) {
if (sLocalServiceObjects.containsKey(type)) {
throw new IllegalStateException("Overriding service registration");
}
sLocalServiceObjects.put(type, service);
}
}
//删除服务实例,只能在测试中使用。
public static <T> void removeServiceForTest(Class<T> type) {
synchronized (sLocalServiceObjects) {
sLocalServiceObjects.remove(type);
}
}
}
把 SystemServiceManager 对象加入到本地服务的全局注册表中
4.4 ActivityTaskManagerService启动
private void startBootstrapServices() {
........
atm = mSystemServiceManager.startService(
ActivityTaskManagerService.Lifecycle.class).getService();
........
}
ActivityTaskManagerService 简称 ATM,Android10 中引入的新功能,用来管理 Activity 的启动、调度等.
4.4.1 ATM服务启动过程
public static final class Lifecycle extends SystemService {
private final ActivityTaskManagerService mService;
public Lifecycle(Context context) {
super(context);
//创建ActivityTaskManagerService,得到对象
mService = new ActivityTaskManagerService(context);
}
@Override
public void onStart() {
publishBinderService(Context.ACTIVITY_TASK_SERVICE, mService);
//启动ATM服务
mService.start();
}
........
public ActivityTaskManagerService getService() {
return mService;
}
}
我们知道 SystemServiceManager.startService 最终调用的是启动对象中的 onStart 方法,因此 ATM 启动,最终会调用 ActivityTaskManagerService.Lifecycle.onStart() 来启动 ATM 服务.
onStart中调用父类SystemService的publishBinderService(Context.ACTIVITY_TASK_SERVICE, mService)把ATMS的IBinder注册到serviceManager中 ServiceManager.addService(name, service, allowIsolated, dumpPriority);
4.4.2 ActivityTaskManagerService 对象创建
public class ActivityTaskManagerService extends IActivityTaskManager.Stub {
final Context mUiContext;
final ActivityThread mSystemThread;
final ActivityTaskManagerInternal mInternal;
//ActivityStackSupervisor 是ATM中用来管理Activity启动和调度的核心类
public ActivityStackSupervisor mStackSupervisor;
//Activity 容器的根节点
RootActivityContainer mRootActivityContainer;
//WMS 负责窗口的管理
WindowManagerService mWindowManager;
//这是我们目前认为是"Home" Activity的过程
WindowProcessController mHomeProcess;
public ActivityTaskManagerService(Context context) {
//拿到System Context
mContext = context;
mFactoryTest = FactoryTest.getMode();
//取出的是ActivityThread的静态变量sCurrentActivityThread
//这意味着mSystemThread与SystemServer中的ActivityThread一致
mSystemThread = ActivityThread.currentActivityThread();
//拿到System UI Context
mUiContext = mSystemThread.getSystemUiContext();
mLifecycleManager = new ClientLifecycleManager();
//拿到LocalService的对象
mInternal = new LocalService();
GL_ES_VERSION =
SystemProperties.getInt("ro.opengles.version", GL_ES_VERSION_UNDEFINED);
}
}
Android10 把原先在 AMS 中的 Activity 的管理移到了 ATM 中,从 Android10 的代码路徑可以看出,管理 Activity 的 ATM 被放入到的 wm 路徑中,这个路径原先归 WindowManagerService -WMS 控制,谷歌的目的也是希望在将来把 activity 和 window 融合在一起,减少冗余代码以及 AMS 和 WMS 的协调工作.
ATM的路徑为:frameworks\base\services\core\java\com\android\server\wm
AMS的路徑为:frameworks\base\services\core\java\com\android\server\am
4.4.2 ActivityTaskManagerService start
private void start() {
LocalServices.addService(ActivityTaskManagerInternal.class, mInternal);
}
将 ActivityTaskManagerInternal 添加到本地服务的全局注册表中,ActivityTaskManagerInternal 为抽象类
4.5 ActivityManagerService 启动
private void startBootstrapServices() {
........
//启动AMS
mActivityManagerService =
ActivityManagerService.Lifecycle.startService(mSystemServiceManager, atm);
........
}
ActivityManagerService 简称 AMS,在 Android10 的版本中,Activity 的管理和调度移到 ATM 中,AMS 负责 service,broadcast,provider 的管理和调度
4.5.1 AMS服务启动过程
public static final class Lifecycle extends SystemService {
private final ActivityManagerService mService;
private static ActivityTaskManagerService sAtm;
public Lifecycle(Context context) {
super(context);
//创建ActivityManagerService,得到对象,传入ATM的对象
mService = new ActivityManagerService(context, sAtm);
}
@Override
public void onStart() {
mService.start();
}
........
public ActivityManagerService getService() {
return mService;
}
}
我们知道 SystemServiceManager.startService 最终调用的是启动对象中的 onStart 方法,因此 AMS 服务启动,最终会调用ActivityManagerService.Lifecycle.onStart() 来启动 AMS 服务
4.5.2 AMS对象创建
public class ActivityManagerService extends IActivityManager.Stub
implements Watchdog.Monitor, BatteryStatsImpl.BatteryCallback {
public ActivityManagerService(Context systemContext, ActivityTaskManagerService atm) {
........
//AMS的运行上下文与SystemServer一致
mContext = systemContext; ...
//取出的是ActivityThread的静态变量sCurrentActivityThread
//这意味着mSystemThread与SystemServer中的ActivityThread一致
mSystemThread = ActivityThread.currentActivityThread();
mUiContext = mSystemThread.getSystemUiContext();
//创建并启动名称为"ActivityManager"的线程
mHandlerThread = new ServiceThread(TAG,
THREAD_PRIORITY_FOREGROUND, false /*allowIo*/);
mHandlerThread.start();
//处理AMS中消息的主力
mHandler = new MainHandler(mHandlerThread.getLooper());
//通过UiThread,创建名称为"android.ui"的线程,用于显示UI
mUiHandler = mInjector.getUiHandler(this);
// 创建并启动名称为"ActivityManager:procStart"的线程
mProcStartHandlerThread = new ServiceThread(TAG + ":procStart",
THREAD_PRIORITY_FOREGROUND, false /* allowIo */);
mProcStartHandlerThread.start();
mProcStartHandler = new Handler(mProcStartHandlerThread.getLooper());
........
//创建 BroadcastQueue 前台广播对象,处理超时时长是 10s
mFgBroadcastQueue = new BroadcastQueue(this, mHandler,
"foreground", foreConstants, false);
//创建 BroadcastQueue 后台广播对象,处理超时时长是 60s
mBgBroadcastQueue = new BroadcastQueue(this, mHandler,
"background", backConstants, true);
//创建 BroadcastQueue 离线广播对象,处理超时时长是 60s
mOffloadBroadcastQueue = new BroadcastQueue(this, mHandler,
"offload", offloadConstants, true);
mBroadcastQueues[0] = mFgBroadcastQueue;
mBroadcastQueues[1] = mBgBroadcastQueue;
mBroadcastQueues[2] = mOffloadBroadcastQueue;
//启动ActiveServices, 设置后台最大服务启动数mMaxStartingBackground.
//低内存时为1, 非低内存时为8
mServices = new ActiveServices(this);
// 创建 ProviderMap 对象,用于管理 ContentProviderRecord 对象
mProviderMap = new ProviderMap(this);
// 创建电池统计服务BatteryStatsService
mBatteryStatsService = new BatteryStatsService(systemContext, systemDir,
BackgroundThread.get().getHandler());
mBatteryStatsService.getActiveStatistics().readLocked();
mBatteryStatsService.scheduleWriteToDisk();
mBatteryStatsService.getActiveStatistics().setCallback(this);
// 创建进程统计服务ProcessStatsService, 信息保存在目录/data/system/procstats
mProcessStats = new ProcessStatsService(this, new File(systemDir, "procstats"));
//初始化ATM
mActivityTaskManager = atm;
mActivityTaskManager.initialize(mIntentFirewall, mPendingIntentController,
DisplayThread.get().getLooper());
//得到ATM的服务信息
mAtmInternal = LocalServices.getService(vityTaskManagerInternal.class);
// 创建名称为"CpuTracker"的线程
mProcessCpuThread = new Thread("CpuTracker") {
@Override
public void run() {
synchronized (mProcessCpuTracker) {
mProcessCpuInitLatch.countDown();
mProcessCpuTracker.init();
}
while (true) {
synchronized(this) {
final long now = SystemClock.uptimeMillis();
long nextCpuDelay = (mLastCpuTime.get()+MONITOR_CPU_MAX_TIME)-now;
long nextWriteDelay = (mLastWriteTime+BATTERY_STATS_TIME)-now;
if (nextWriteDelay < nextCpuDelay) {
nextCpuDelay = nextWriteDelay;
}
if (nextCpuDelay > 0) {
mProcessCpuMutexFree.set(true);
this.wait(nextCpuDelay);
}
}
// 更新CPU状态信息
updateCpuStatsNow();
}
}
};
//加入Watchdog的监控
Watchdog.getInstance().addMonitor(this);
Watchdog.getInstance().addThread(mHandler);
}
}
构造函数主要工作就是初始化一些变量,供之后的 service,broadcast,provider 的管理和调度
4.5.3 ActivityManagerService start
private void start() {
removeAllProcessGroups();//移除所有进程组
mProcessCpuThread.start();//启动CPU监控线程
//启动电池状态统计服务
mBatteryStatsService.publish();
mAppOpsService.publish(mContext);//启动AppOpsService
Slog.d("AppOps", "AppOpsService published");
LocalServices.addService(ActivityManagerInternal.class, new LocalService());
mActivityTaskManager.onActivityManagerInternalAdded();
mUgmInternal.onActivityManagerInternalAdded();
mPendingIntentController.onActivityManagerInternalAdded();
try {
mProcessCpuInitLatch.await();
} catch (InterruptedException e) {
Slog.wtf(TAG, "Interrupted wait during start", e);
Thread.currentThread().interrupt();
throw new IllegalStateException("Interrupted wait during start");
}
}
start 中主要做了两件事
- 启动 CPU 监控线程,在启动 CPU 监控线程之前,首先将进程复位
- 启动电池状态服务和权限管理服务
4.6 SystemServer.setSystemProcess
private void startOtherServices() {
//Set up the Application instance for the system process and get started.
mActivityManagerService.setSystemProcess();
}
public void setSystemProcess() {
try {
//注册一些服务到ServiceManager,包括 activity、procstats、meminfo等
ServiceManager.addService(Context.ACTIVITY_SERVICE, this, /* allowIsolated= */ true,
DUMP_FLAG_PRIORITY_CRITICAL | DUMP_FLAG_PRIORITY_NORMAL | DUMP_FLAG_PROTO);
ServiceManager.addService(ProcessStats.SERVICE_NAME, mProcessStats);
ServiceManager.addService("meminfo", new MemBinder(this), /* allowIsolated= */ false,
DUMP_FLAG_PRIORITY_HIGH);
ServiceManager.addService("gfxinfo", new GraphicsBinder(this));
ServiceManager.addService("dbinfo", new DbBinder(this));
if (MONITOR_CPU_USAGE) {
ServiceManager.addService("cpuinfo", new CpuBinder(this),
/* allowIsolated= */ false, DUMP_FLAG_PRIORITY_CRITICAL);
}
ServiceManager.addService("permission", new PermissionController(this));
ServiceManager.addService("processinfo", new ProcessInfoService(this));
//通过解析framework-res.apk里的AndroidManifest.xml获得ApplicationInfo
ApplicationInfo info = mContext.getPackageManager().getApplicationInfo(
"android", STOCK_PM_FLAGS | MATCH_SYSTEM_ONLY);
//为ActivityThread安装system application相关信息,将framework-res.apk
//对应的ApplicationInfo安装到LoadedApk中的mApplicationInfo
mSystemThread.installSystemApplicationInfo(info, getClass().getClassLoader());
//为systemserver进程创建ProcessRecord来维护进程的相关信息
synchronized (this) {
ProcessRecord app = mProcessList.newProcessRecordLocked(info, info.processName,
false,
0,
new HostingRecord("system"));
app.setPersistent(true); //设置进程常驻
app.pid = MY_PID; //为ProcessRecord赋值当前进程ID,即system_server进程ID
app.getWindowProcessController().setPid(MY_PID);
app.maxAdj = ProcessList.SYSTEM_ADJ;
app.makeActive(mSystemThread.getApplicationThread(), mProcessStats);
mPidsSelfLocked.put(app); //将ProcessRecord放到mPidSelfLocked里统一管理
mProcessList.updateLruProcessLocked(app, false, null);//更新lru进程列表
updateOomAdjLocked(OomAdjuster.OOM_ADJ_REASON_NONE);//更新adj
}
} catch (PackageManager.NameNotFoundException e) {
throw new RuntimeException(
"Unable to find android system package", e);
}
// Start watching app ops after we and the package manager are up and running.
mAppOpsService.startWatchingMode(AppOpsManager.OP_RUN_IN_BACKGROUND, null,
new IAppOpsCallback.Stub() {
@Override public void opChanged(int op, int uid, String packageName) {
if (op == AppOpsManager.OP_RUN_IN_BACKGROUND && packageName != null) {
if (mAppOpsService.checkOperation(op, uid, packageName)
!= AppOpsManager.MODE_ALLOWED) {
runInBackgroundDisabled(uid);
}
}
}
});
}
AMS把自己的IBinder公布到ServiceManager中 ServiceManager.addService(Context.ACTIVITY_SERVICE, this, /* allowIsolated= */ true, DUMP_FLAG_PRIORITY_CRITICAL | DUMP_FLAG_PRIORITY_NORMAL | DUMP_FLAG_PROTO)
AMS 的 setSystemProcess 主要有以下五个功能:
- 注册一些服务:包括 activity、procstats、meminfo、gfxinfo、dbinfo、permission、processinfo
- 获取 package 名为 “android” 的应用的 ApplicationInfo
- 为 ActivityThread 安装 system application 相关信息,将 framework-res.apk 对应的 ApplicationInfo 安装到 LoadedApk 中的 mApplicationInfo
- 为 systemserver 主进程开辟一个 ProcessRecord 来维护进程的相关信息
- AMS 进程管理相关的操作
4.7 ActivityManagerService.systemReady
private void startOtherServices() {
mActivityManagerService.systemReady(() -> {xxxxxgoingCallbackxxx,
BOOT_TIMINGS_TRACE_LOG);
}
public void systemReady(final Runnable goingCallback, TimingsTraceLog traceLog) {
阶段1:关键服务的初始化
阶段2:goingCallback处理
阶段3:启动Home Activity,完成AMS启动
}
AMS 的 systemReady 处理主要分为三个阶段
- 阶段1:主要是调用一些关键服务的初始化函数, 然后杀死那些没有 FLAG_PERSISTENT 却在 AMS 启动完成前已经存在的进程,同时获取一些配置参数。 需要注意的是,由于只有 Java 进程才会向 AMS 注册,而一般的 Native 进程不会向 AMS 注册,因此此处杀死的进程是 Java 进程。
- 阶段2:执行 goingCallback 的处理,主要的工作就是通知一些服务可以进行 systemReady、systemRunning 相关的工作,并进行启动服务或应用进程的工作
- 阶段3:启动 Home Activity,当启动结束,并发送 ACTION_BOOT_COMPLETED 广播,AMS 的启动过程告一段落
4.7.1 systemReady阶段1
public void systemReady(final Runnable goingCallback, TimingsTraceLog traceLog) {
synchronized(this) {
//第一次进入mSystemReady为false,不走该流程
if (mSystemReady) {
if (goingCallback != null) {
goingCallback.run();
}
return;
}
/** PowerSaveMode_start */
Settings.System.putInt(mContext.getContentResolver(),
ActivityTaskManagerService.SUPER_POWER_SAVE_MODE,
ActivityTaskManagerService.SUPER_POWER_SAVE_MODE_NORMAL);
/** PowerSaveMode_end */
//这一部分主要是调用一些关键服务SystemReady相关的函数,
//进行一些等待AMS初始完,才能进行的工作
mActivityTaskManager.onSystemReady();
mUserController.onSystemReady();
mAppOpsService.systemReady();
........
mSystemReady = true;
}
try {
sTheRealBuildSerial = IDeviceIdentifiersPolicyService.Stub.asInterface(
ServiceManager.getService(Context.DEVICE_IDENTIFIERS_SERVICE))
.getSerial();
} catch (RemoteException e) {}
//非persistent进程添加到procsToKill列表
ArrayList<ProcessRecord> procsToKill = null;
synchronized(mPidsSelfLocked) {
//mPidsSelfLocked中保存当前正在运行的所有进程的信息
for (int i=mPidsSelfLocked.size()-1; i>=0; i--) {
ProcessRecord proc = mPidsSelfLocked.valueAt(i);
//在AMS启动完成前,如果没有FLAG_PERSISTENT标志的进程已经启动了,
//就将这个进程加入到procsToKill中
if (!isAllowedWhileBooting(proc.info)){
if (procsToKill == null) {
procsToKill = new ArrayList<ProcessRecord>();
}
procsToKill.add(proc);
}
}
}
//收集已经启动的进程并杀死,排除persistent常驻进程
synchronized(this) {
//利用removeProcessLocked关闭procsToKill中的进程
if (procsToKill != null) {
for (int i=procsToKill.size()-1; i>=0; i--) {
ProcessRecord proc = procsToKill.get(i);
Slog.i(TAG, "Removing system update proc: " + proc);
mProcessList.removeProcessLocked(proc, true, false, "system update done");
}
}
//至此系统准备完毕
mProcessesReady = true;
}
........
mUgmInternal.onSystemReady();
}
主要是调用一些关键服务的初始化函数, 然后杀死那些没有 FLAG_PERSISTENT 却在 AMS 启动完成前已经存在的进程, 同时获取一些配置参数。 需要注意的是,由于只有 Java 进程才会向 AMS 注册,而一般的 Native 进程不会向 AMS 注册,因此此处杀死的进程是 Java 进程。
4.7.2 systemReady阶段2
public void systemReady(final Runnable goingCallback, TimingsTraceLog traceLog) {
........
//调用参数传入的runnable对象,SystemServer中有具体的定义
if (goingCallback != null) goingCallback.run();
........
//调用所有系统服务的onStartUser接口
mSystemServiceManager.startUser(currentUserId);
synchronized (this) {
//启动persistent为1的application所在的进程
startPersistentApps(PackageManager.MATCH_DIRECT_BOOT_AWARE);
//设置启动中
mBooting = true;
........
}
执行 goingCallback 的处理,主要的工作就是通知一些服务可以进行 systemReady 相关的工作,并进行启动服务或应用进程的工作.
4.7.2.1 goingCallback.run()
private void startOtherServices() {
mActivityManagerService.systemReady(() -> {
//阶段 550
mSystemServiceManager.startBootPhase(
SystemService.PHASE_ACTIVITY_MANAGER_READY);
........
//监控Native的crash
mActivityManagerService.startObservingNativeCrashes();
, BOOT_TIMINGS_TRACE_LOG);
........
//启动WebView
mWebViewUpdateService.prepareWebViewInSystemServer();
//启动systemUI,参考[4.7.2.3]
startSystemUi(context, windowManagerF);
// 执行一系列服务的systemReady方法
networkManagementF.systemReady();
ipSecServiceF.systemReady();
networkStatsF.systemReady();
connectivityF.systemReady();
networkPolicyF.systemReady(networkPolicyInitReadySignal);
........
//阶段 600
mSystemServiceManager.startBootPhase(
SystemService.PHASE_THIRD_PARTY_APPS_CAN_START);
//执行一系列服务的systemRunning方法
locationF.systemRunning();
countryDetectorF.systemRunning();
networkTimeUpdaterF.systemRunning();
inputManagerF.systemRunning();
telephonyRegistryF.systemRunning();
mediaRouterF.systemRunning();
mmsServiceF.systemRunning();
........
}
监控 Native 的 crash,启动 WebView,执行一些服务的 systemReady 和 systemRunning 方法.
4.7.2.2 startPersistentApps()
void startPersistentApps(int matchFlags) {
if (mFactoryTest == FactoryTest.FACTORY_TEST_LOW_LEVEL) return;
synchronized (this) {
try {
//从PKMS中得到persistent为1的ApplicationInfo
final List<ApplicationInfo> apps = AppGlobals.getPackageManager()
.getPersistentApplications(STOCK_PM_FLAGS | matchFlags).getList();
for (ApplicationInfo app : apps) {
//由于framework-res.apk已经由系统启动,所以此处不再启动它
if (!"android".equals(app.packageName)) {
//addAppLocked中将启动application所在进程
addAppLocked(app, null, false, null /* ABI override */);
}
}
} catch (RemoteException ex) {
}
}
}
启动 systemUI,服务名称 ”com.android.systemui/.SystemUIService”
4.7.3 systemReady阶段3
public void systemReady(final Runnable goingCallback, TimingsTraceLog traceLog) {
........
//通过ATM,启动Home Activity
mAtmInternal.startHomeOnAllDisplays(currentUserId, "systemReady");
........
//发送一些广播消息
try {
//system发送广播 ACTION_USER_STARTED = "android.intent.action.USER_STARTED";
Intent intent = new Intent(Intent.ACTION_USER_STARTED);
intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY
| Intent.FLAG_RECEIVER_FOREGROUND);
intent.putExtra(Intent.EXTRA_USER_HANDLE, currentUserId);
broadcastIntentLocked(null, null, intent,
null, null, 0, null, null, null, OP_NONE,
null, false, false, MY_PID, SYSTEM_UID, callingUid, callingPid,
currentUserId);
//system发送广播 ACTION_USER_STARTING= "android.intent.action.USER_STARTING";
intent = new Intent(Intent.ACTION_USER_STARTING);
intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
intent.putExtra(Intent.EXTRA_USER_HANDLE, currentUserId);
broadcastIntentLocked(null, null, intent,
null, new IIntentReceiver.Stub() {
@Override
public void performReceive(Intent intent, int resultCode, String data,
Bundle extras, boolean ordered, boolean sticky, int sendingUser)
throws RemoteException {
}
}, 0, null, null,
new String[] {INTERACT_ACROSS_USERS}, OP_NONE,
null, true, false, MY_PID, SYSTEM_UID, callingUid, callingPid,
UserHandle.USER_ALL);
} catch (Throwable t) {
Slog.wtf(TAG, "Failed sending first user broadcasts", t);
} finally {
Binder.restoreCallingIdentity(ident);
}
}
启动 Home Activity,当启动结束,并发送 ACTION_BOOT_COMPLETED 广播时,AMS 的启动过程告一段落.
4.7.3.1 ATM.startHomeOnAllDisplays
ActivityTaskManagerService.java
public boolean startHomeOnAllDisplays(int userId, String reason) {
synchronized (mGlobalLock) {
//调用RootActivityContainer的startHomeOnAllDisplays(),最终到startHomeOnDisplay()
return mRootActivityContainer.startHomeOnAllDisplays(userId, reason);
}
}
启动 Home Activity
RootActivityContainer.java
boolean startHomeOnDisplay(int userId, String reason, int displayId, boolean allowInstrumenting,
boolean fromHomeKey) {
// Fallback to top focused display if the displayId is invalid.
if (displayId == INVALID_DISPLAY) {
displayId = getTopDisplayFocusedStack().mDisplayId;
}
Intent homeIntent = null;
ActivityInfo aInfo = null;
if (displayId == DEFAULT_DISPLAY) {
//home intent有CATEGORY_HOME
homeIntent = mService.getHomeIntent();
//根据intent中携带的ComponentName,利用PKMS得到ActivityInfo
aInfo = resolveHomeActivity(userId, homeIntent);
} else if (shouldPlaceSecondaryHomeOnDisplay(displayId)) {
Pair<ActivityInfo, Intent> info =
RootActivityContainerMifavor.resolveSecondaryHomeActivityPcMode(this, userId, displayId);
aInfo = info.first;
homeIntent = info.second;
}
if (aInfo == null || homeIntent == null) {
return false;
}
if (!canStartHomeOnDisplay(aInfo, displayId, allowInstrumenting)) {
return false;
}
// Updates the home component of the intent.
homeIntent.setComponent(new ComponentName(aInfo.applicationInfo.packageName, aInfo.name));
homeIntent.setFlags(homeIntent.getFlags() | FLAG_ACTIVITY_NEW_TASK);
// Updates the extra information of the intent.
if (fromHomeKey) {
homeIntent.putExtra(WindowManagerPolicy.EXTRA_FROM_HOME_KEY, true);
}
// Update the reason for ANR debugging to verify if the user activity is the one that
// actually launched.
final String myReason = reason + ":" + userId + ":" + UserHandle.getUserId(
aInfo.applicationInfo.uid) + ":" + displayId;
//启动Home Activity--Luncher
mService.getActivityStartController().startHomeActivity(homeIntent, aInfo, myReason,
displayId);
return true;
}