一. 概述
ActivityManagerService是Android系统中一个特别重要的系统服务,也是我们上层APP打交道最多的系统服务之一。ActivityManagerService(以下简称AMS) 主要负责四大组件的启动、切换、调度以及应用进程的管理和调度工作。所有的APP应用都需要与AMS打交道. 符合C/S通信模式.
Client:由ActivityManager封装一部分服务接口供Client调用
Server:由ActivityManagerService实现,提供Server端的系统服务
二. AMS启动过程
AMS是在SystemServer进程中fork出来的, 所以先到SystemServer中查看初始化
public static void main(String[] args) {
new SystemServer().run();
}
继续看run方法
private void run() {
// Start services.
try {
traceBeginAndSlog("StartServices");
//在startBootstrapServices()中去启动了AMS
startBootstrapServices();
startCoreServices();
startOtherServices();
SystemServerInitThreadPool.shutdown();
} catch (Throwable ex) {
Slog.e("System", "******************************************");
Slog.e("System", "************ Failure starting system services", ex);
throw ex;
} finally {
traceEnd();
}
}
调用startBootStrapServices()方法
private void startBootstrapServices() {
.....
//启动AMS
mActivityManagerService = ActivityManagerService.Lifecycle.startService(
mSystemServiceManager, atm);
// Set up the Application instance for the system process and get started.
//为系统进程设置应用程序实例并开始操作
traceBeginAndSlog("SetSystemProcess");
mActivityManagerService.setSystemProcess();
traceEnd();
....
}
public static ActivityManagerService startService(
SystemServiceManager ssm, ActivityTaskManagerService atm) {
sAtm = atm;
return
//传入的是ActivityManagerService.Lifecycle.class对象
ssm.startService(ActivityManagerService.Lifecycle.class).getService();
}
AMS是通过SystemServiceManager.startService去启动的,参数是
ActivityManagerService.Lifecycle.class, 首先看看startService方法
public <T extends SystemService> T startService(Class<T> serviceClass) {
....
final T service;
try {
//获取AMS.Lifecycle类中 带context参数的构造方法
Constructor<T> constructor = serviceClass.getConstructor(Context.class);
//通过构造器的newInstance方法
//实际上就是 new一个 AMSEx对象 而 AMSEx 是继承 AMS
service = constructor.newInstance(mContext);
....
startService(service);
return service;
}
用传入进来的ActivityManagerService.Lifecycle.class作为参数, 通过反射方式创建对应的service服务. 所以创建的是Lifecycle的实例, 然后通过startService来启动服务.
那AMS的 Lifecycle的实例是什么呢? 继续看源码,发现它是AMS中的一个静态内部类,并且继承于SystemService
public static final class Lifecycle extends SystemService {
private final ActivityManagerService mService;
private static ActivityTaskManagerService sAtm;
public Lifecycle(Context context) {
super(context);
mService = new ActivityManagerServiceEx(context, sAtm);
}
....
}
在Lifecycle的构造方法中, 通过new 一个 AMSEx对象(AMSEx是继承AMS)赋值给mService
实质上还是创建了AMS服务对象,然后通过 startService(service)方法启动AMS服务.
接着继续调用frameworks/base/services/core/java/com/android/server/SystemServiceManager.java中的
public void startService(@NonNull final SystemService service) {
// Register it.
mServices.add(service);
// Start it.
long time = SystemClock.elapsedRealtime();
try {
//走到这里,就执行到AMS中的onStart()方法了, 服务真正的启动起来
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");
}
在上面 new ActivityManagerServiceEx(context, sAtm)这句代码时, 先会执行AMS的构造方法
看看初始化的时候,做了什么事情
// Set up the Application instance for the system process and get started.
traceBeginAndSlog("SetSystemProcess");
mActivityManagerService.setSystemProcess();
traceEnd();
再看service.onStart()方法//走到这里,就执行到AMS中的onStart()方法了, 服务真正的启动起来
private void start() {
removeAllProcessGroups();
mProcessCpuThread.start();
mBatteryStatsService.publish();
mAppOpsService.publish(mContext);
Slog.d("AppOps", "AppOpsService published");
LocalServices.addService(ActivityManagerInternal.class, new LocalService());
mActivityTaskManager.onActivityManagerInternalAdded();
mUgmInternal.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.
try {
//等待mProcessCpuThread完成初始化后, 释放锁,初始化期间禁止访问
mProcessCpuInitLatch.await();
} catch (InterruptedException e) {
Slog.wtf(TAG, "Interrupted wait during start", e);
Thread.currentThread().interrupt();
throw new IllegalStateException("Interrupted wait during start");
}
}
再回过头来看看在startBootstrapServices()方法中的
mActivityManagerService.setSystemProcess()
public void setSystemProcess() {
try {
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));
ApplicationInfo info = mContext.getPackageManager().getApplicationInfo(
"android", STOCK_PM_FLAGS | MATCH_SYSTEM_ONLY);
mSystemThread.installSystemApplicationInfo(info, getClass().getClassLoader());
synchronized (this) {
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);
mPidsSelfLocked.put(app);
mProcessList.updateLruProcessLocked(app, false, null);
updateOomAdjLocked(OomAdjuster.OOM_ADJ_REASON_NONE);
}
} catch (PackageManager.NameNotFoundException e) {
throw new RuntimeException(
"Unable to find android system package", e);
}
看看这里面做的工作:
1. 注册服务。首先将ActivityManagerService注册到ServiceManager中,其次将几个与系统性能调试相关的服务(meminfo内存信息, cpuinfo CPU信息, permission 权限信息, processinfo进程信息等)注册到ServiceManager。
2. 查询并处理ApplicationInfo。首先调用PackageManagerService的接口,查询包名为android的应用程序的ApplicationInfo信息,对应于framework-res.apk。然后以该信息为参数调用ActivityThread上的installSystemApplicationInfo方法。
3. 创建并处理ProcessRecord。调用ActivityManagerService上的newProcessRecordLocked,创建一个ProcessRecord类型的对象,并保存该对象的信息。
三. 时序图
总结一下AMS启动时序图