AMS是什么?
AMS管理Activity,Service,provider broadcast
android10后引入ATMS,ActivityTaskManagerService,负责管理Activity
AMS如何被启动?
System_service的main函数启动run方法,这个方法执行startBootstrapServices,startBootstrapServices()中去启动了AMS
private void startBootstrapServices() {
...
//启动了AMS
ActivityTaskManagerService atm = mSystemServiceManager.startService(
ActivityTaskManagerService.Lifecycle.class).getService(); //启动atms
mActivityManagerService = ActivityManagerService.Lifecycle.startService(
mSystemServiceManager, atm); // 启动AMS
mActivityManagerService.setSystemServiceManager(mSystemServiceManager);
mActivityManagerService.setInstaller(installer);
mWindowManagerGlobalLock = atm.getGlobalLock();
t.traceEnd();
...
}
为什么启动AMS和ATMS是通过ActivityTaskManagerService.Lifecycle.class
SystemServiceManager是为SystemService进程提供服务管理的类,所有在SystemServiceManager启动的服务都需要继承SystemService(只是一个普通的类,里面有start,stop方法)。
所有在SystemServiceManager启动的服务都需要继承SystemService是因为方便管理,这里的SystemService只是一个普通的java类,不是SystemService进程。这个类里面有start,stop等方法。我们在使用SystemServiceManager对启动的服务进行管理的时候,就可以统一调用SystemService类里面的方法了。
public class SystemService {
........
/** Request that the init daemon start a named service. */
@UnsupportedAppUsage
public static void start(String name) {
SystemProperties.set("ctl.start", name);
}
/** Request that the init daemon stop a named service. */
@UnsupportedAppUsage
public static void stop(String name) {
SystemProperties.set("ctl.stop", name);
}
/** Request that the init daemon restart a named service. */
public static void restart(String name) {
SystemProperties.set("ctl.restart", name);
}
........
}
但是AMS和AMTS没有继承SystemService类,他们继承了IActivityManager.Stub。因为AMS和AMTS是需要提供服务给APP使用的,涉及到跨进程通信,所以需要继承IActivityManager.Stub。Java里面是单继承的,所以在AMS和ATMS里面创建了静态内部类Lifecycle extends SystemService。
public static final class Lifecycle extends SystemService {
private final ActivityTaskManagerService mService;
public Lifecycle(Context context) {
super(context);
mService = new ActivityTaskManagerService(context);
}
@Override
public void onStart() {
将ATMS保存到ServiceManager中
publishBinderService(Context.ACTIVITY_TASK_SERVICE, mService);
mService.start();
}
@Override
public void onUnlockUser(int userId) {
synchronized (mService.getGlobalLock()) {
mService.mStackSupervisor.onUserUnlocked(userId);
}
}
@Override
public void onCleanupUser(int userId) {
synchronized (mService.getGlobalLock()) {
mService.mStackSupervisor.mLaunchParamsPersister.onCleanupUser(userId);
}
}
public ActivityTaskManagerService getService() {
return mService;
}
}
所以SystemServiceManager对AMS和ATMS的管理并不是直接通过SystemService类,而是间接的调用这个继承了SystemService类的内部类Lifecycle,通过Lifecycle来实现对AMS和ATMS的管理。
所以当一个类有多个父类的时候,基于Java的单继承原则,只能继承一个父类。我们可以参考AMS里面的做法,定义一个内部类继承另外一个父类,内部类里面声明当前的类,通过这个内部类去操作我们的外部类对象。
SystemServiceManager里面启动服务的方法startService
public <T extends SystemService> T startService(Class<T> serviceClass) {
try {
final String name = serviceClass.getName();
Slog.i(TAG, "Starting " + name);
Trace.traceBegin(Trace.TRACE_TAG_SYSTEM_SERVER, "StartService " + name);
// Create the service.
if (!SystemService.class.isAssignableFrom(serviceClass)) {
throw new RuntimeException("Failed to create " + name
+ ": service must extend " + SystemService.class.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;
} finally {
Trace.traceEnd(Trace.TRACE_TAG_SYSTEM_SERVER);
}
}
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);
}
warnIfTooLong(SystemClock.elapsedRealtime() - time, service, "onStart");
}
可以看到是通过反射去创建SystemService对象,然后调用onStart方法。在AMS和ATMS里面,创建的就是Lifecycle对象,执行的是Lifecycle里面的onStart方法。startService会统一反射生成各类服务的SystemService对象,然后调用SystemService对象的onStart方法区启动服务,这也印证了继承SystemService类是为了SystemServiceManager对各种服务的管理。
ServiceManager保存服务的Binder
回到ATMS的Lifecycle中。
public Lifecycle(Context context) {
super(context);
mService = new ActivityTaskManagerService(context);
}
@Override
public void onStart() {
将ATMS保存到ServiceManager中
publishBinderService(Context.ACTIVITY_TASK_SERVICE, mService);
mService.start();
}
反射创建Lifecycle的时候就会创建ATMS,在onStart里面首先将ATMS保存到ServiceManager中,然后再启动ATMS。
protected final void publishBinderService(String name, IBinder service,
boolean allowIsolated, int dumpPriority) {
ServiceManager.addService(name, service, allowIsolated, dumpPriority);
}
ServiceManager的addService方法里面就是通过调用addService方法,把名字和对应服务的Binder添加到ServiceManager里面去。
@UnsupportedAppUsage
public static void addService(String name, IBinder service, boolean allowIsolated,
int dumpPriority) {
try {
getIServiceManager().addService(name, service, allowIsolated, dumpPriority);
} catch (RemoteException e) {
Log.e(TAG, "error in addService", e);
}
}
在ServiceManager里面保存服务的Binder,APP与SystemServer通信的时候可以到ServiceManager进程里面拿到AMS的Binder。
AMS和ATMS在启动时做了什么
首先来看ATMS,ATMS里面的Lifecycle在onStart时只做了两件事,将ATMS的Binder注册到ServiceManager里面,然后执行自己的start方法,把服务注册到LocalServices提供给SystemService进程使用。
//Lifecycle在onStart
@Override
public void onStart() {
将ATMS保存到ServiceManager中
publishBinderService(Context.ACTIVITY_TASK_SERVICE, mService);
mService.start();
}
//ATMS自己的start方法
private void start() {
LocalServices.addService(ActivityTaskManagerInternal.class, mInternal);
}
//LocalServices类
public final class LocalServices {
private LocalServices() {}
private static final ArrayMap<Class<?>, Object> sLocalServiceObjects =
new ArrayMap<Class<?>, Object>();
/**
* Returns a local service instance that implements the specified interface.
*
* @param type The type of service.
* @return The service object.
*/
@SuppressWarnings("unchecked")
public static <T> T getService(Class<T> type) {
synchronized (sLocalServiceObjects) {
return (T) sLocalServiceObjects.get(type);
}
}
/**
* Adds a service instance of the specified interface to the global registry of local services.
*/
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);
}
}
/**
* Remove a service instance, must be only used in tests.
*/
@VisibleForTesting
public static <T> void removeServiceForTest(Class<T> type) {
synchronized (sLocalServiceObjects) {
sLocalServiceObjects.remove(type);
}
}
}
再来看AMS的Lifecycle在onStart,只调用了AMS的start方法,在AMS的start方法里面,启动CPU监控线程,这个线程专门跟进cpu当前状态信息。AMS对当前cpu状态了如指掌,可以更加高效的安排其他工作。其次,注册电池状态和权限管理服务。
//AMS的Lifecycle在onStart
@Override
public void onStart() {
mService.start();
}
//AMS的start方法
private void start() {
removeAllProcessGroups();
mProcessCpuThread.start();启动 CPU 监控线程
mBatteryStatsService.publish();//注册电池状态和权限管理服务
mAppOpsService.publish();
Slog.d("AppOps", "AppOpsService published");
LocalServices.addService(ActivityManagerInternal.class, mInternal);
mActivityTaskManager.onActivityManagerInternalAdded();
mPendingIntentController.onActivityManagerInternalAdded();
// Wait for the synchronized block started in mProcessCpuThread,
// so that any other access to mProcessCpuTracker from main thread
// will be blocked during mProcessCpuTracker initialization.
// 等待mProcessCpuInitLatch完成初始化后,释放锁,初始化期间禁止访问
try {
mProcessCpuInitLatch.await();
} catch (InterruptedException e) {
Slog.wtf(TAG, "Interrupted wait during start", e);
Thread.currentThread().interrupt();
throw new IllegalStateException("Interrupted wait during start");
}
}
其实在System_service的main方法执行startBootstrapServices启动AMS后,还调用了一些AMS的方法。比如说启动电源服务,setSystemProcess为app进程安排系统进程的各种监控。
//startBootstrapServices方法
......
//启动电源服务
// Now that the power manager has been started, let the activity manager
// initialize power management features.
t.traceBegin("InitPowerManagement");
mActivityManagerService.initPowerManagement();
t.traceEnd();
......
// 核心内容,为app进程安排系统进程的各种监控
// Set up the Application instance for the system process and get started.
t.traceBegin("SetSystemProcess");
mActivityManagerService.setSystemProcess();
t.traceEnd();
......
//注册服务。首先将ActivityManagerService注册到ServiceManager中,其次将几个与系统性能调试相关
//的服务注册到ServiceManager。查询并处理ApplicationInfo。首先调用PackageManagerService的接口,查询包名为android的应用程
//序的ApplicationInfo信息,对应于framework-res.apk。然后以该信息为参数调用ActivityThread上的
//installSystemApplicationInfo方法。
//创建并处理ProcessRecord。调用ActivityManagerService上的newProcessRecordLocked,创建一个
//ProcessRecord类型的对象,并保存该对象的信息
public void setSystemProcess() {
try {
// 注册服务activity
ServiceManager.addService(Context.ACTIVITY_SERVICE, this, /* allowIsolated= */ true, DUMP_FLAG_PRIORITY_CRITICAL | DUMP_FLAG_PRIORITY_NORMAL | DUMP_FLAG_PROTO);
// 注册服务procstats,进程状态
ServiceManager.addService(ProcessStats.SERVICE_NAME, mProcessStats);
// 注册服务meminfo,内存信息
ServiceManager.addService("meminfo", new MemBinder(this),/* allowIsolated= */ false, DUMP_FLAG_PRIORITY_HIGH);
// 注册服务gfxinfo,图像信息
ServiceManager.addService("gfxinfo", new GraphicsBinder(this));
// 注册服务dbinfo,数据库信息
ServiceManager.addService("dbinfo", new DbBinder(this));
if (MONITOR_CPU_USAGE) {
//注册服务cpuinfo,cpu信息
ServiceManager.addService("cpuinfo", new CpuBinder(this),
/* allowIsolated= */ false, DUMP_FLAG_PRIORITY_CRITICAL);
}
//注册服务permission和processinfo,权限和进程信息
ServiceManager.addService("permission", new PermissionController(this));
// 注册进程信息
ServiceManager.addService("processinfo", new ProcessInfoService(this));
// 注册缓存信息
ServiceManager.addService("cacheinfo", new CacheBinder(this));
ApplicationInfo info = mContext.getPackageManager().getApplicationInfo(
"android", STOCK_PM_FLAGS | MATCH_SYSTEM_ONLY);
mSystemThread.installSystemApplicationInfo(info, getClass().getClassLoader());
synchronized (this) {
// 创建ProcessRecord维护进程的相关信息
ProcessRecord app = mProcessList.newProcessRecordLocked(info, info.processName,
false,
0,
new HostingRecord("system"));
app.setPersistent(true);
app.pid = MY_PID;
app.getWindowProcessController().setPid(MY_PID);
app.maxAdj = ProcessList.SYSTEM_ADJ;
app.makeActive(mSystemThread.getApplicationThread(), mProcessStats);
addPidLocked(app);
mProcessList.updateLruProcessLocked(app, false, null);
updateOomAdjLocked(OomAdjuster.OOM_ADJ_REASON_NONE); //手机进程杀死就与这个紧密相关
}
......
}
setSystemProcess方法里面首先将ActivityManagerService注册到ServiceManager中,其次将几个与系统性能调试相关的服务注册到ServiceManager。
ATMS主要是关于Activity的管理。
AMS管理Service,provider,broadcast。还有App运行时的信息,进程信息,图像信息,内存信息,数据库信息,cpu信息,权限管理信息等等(所以AMS在启动的时候会把这一些列信息对应的服务添加到ServiceManager,当App出现问题的时候,我们可以使用adb命令收集这一系列服务的信息,adb调用服务里面的dump方法)。