AMS启动流程

在SystemServer中简单分析了AMS的流程,这篇就详细地讲解AMS的启动流程

注意一点:AMS所在的进程是属于SystemServer中的

时序图

AMS流程

  • 创建AMS对象
  • 调用ams.setSystemProcess
  • 调用ams.installSystemProviders
  • 调用ams.systemReady

ActivityThread创建

在startBootstrapServices之前有一个流程是 createSystemContext,该过程会创建对象有ActivityThread,Instrumentation, ContextImpl,LoadedApk,Application,这些都是后面AMS要用到的对象,请注意它们是在这里创建的

1
2
3
4
5
6
7
8
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);
}

创建AMS对象

startBootstrapServices

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
private void startBootstrapServices() {
...
//启动AMS服务
mActivityManagerService = mSystemServiceManager.startService(
ActivityManagerService.Lifecycle.class).getService();

//设置AMS的系统服务管理器
mActivityManagerService.setSystemServiceManager(mSystemServiceManager);
//设置AMS的APP安装器
mActivityManagerService.setInstaller(installer);
//初始化AMS相关的PMS
mActivityManagerService.initPowerManagement();
...

//设置SystemServer
mActivityManagerService.setSystemProcess();
}

startService

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
public SystemService startService(String className) {
final Class<SystemService> serviceClass;
try {
serviceClass = (Class<SystemService>)Class.forName(className);
} catch (ClassNotFoundException ex) {
......
}
return startService(serviceClass);
}

public void startService(@NonNull final SystemService service) {
// Register it.
mServices.add(service);
// Start it.
long time = SystemClock.elapsedRealtime();
try {
service.onStart();
} catch (RuntimeException ex) {
.....
}
warnIfTooLong(SystemClock.elapsedRealtime() - time, service, "onStart");
}

这部分比较简单,主要是添加服务,并调用服务的 onStart 函数

ActivityManagerService.Lifecycle.class

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
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 onCleanupUser(int userId) {
mService.mBatteryStatsService.onCleanupUser(userId);
}

public ActivityManagerService getService() {
return mService;
}
}

继承SystemService,代表是一个系统服务,里面主要是创建 ActivityManagerService

ActivityManagerService对象创建

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
public ActivityManagerService(Context systemContext) {
mContext = systemContext;
mFactoryTest = FactoryTest.getMode();
mSystemThread = ActivityThread.currentActivityThread();

//创建名为"ActivityManager"的前台线程,并获取mHandler
mHandlerThread = new ServiceThread(TAG, android.os.Process.THREAD_PRIORITY_FOREGROUND, false);
mHandlerThread.start();

mHandler = new MainHandler(mHandlerThread.getLooper());

//通过UiThread类,创建名为"android.ui"的线程
mUiHandler = new UiHandler();

......

//创建目录/data/system
File dataDir = Environment.getDataDirectory();
File systemDir = new File(dataDir, "system");
systemDir.mkdirs();

//创建服务BatteryStatsService
mBatteryStatsService = new BatteryStatsService(systemDir, mHandler);
mBatteryStatsService.getActiveStatistics().readLocked();
......

//创建进程统计服务,信息保存在目录/data/system/procstats,
mProcessStats = new ProcessStatsService(this, new File(systemDir, "procstats"));
......
//CPU使用情况的追踪器执行初始化
mProcessCpuTracker.init();
......
mRecentTasks = new RecentTasks(this);
// 创建ActivityStackSupervisor对象
mStackSupervisor = new ActivityStackSupervisor(this, mRecentTasks);
mTaskPersister = new TaskPersister(systemDir, mStackSupervisor, mRecentTasks);

//创建名为"CpuTracker"的线程
mProcessCpuThread = new Thread("CpuTracker") {
public void run() {
......
}
};
......
}

该过程共创建了3个线程

  • ActivityManager
  • android.ui
  • CpuTracker

start

mSystemServiceManager.startService 会调用服务的onStart,在AMS里onStart会调用他的start

1
2
3
4
5
6
7
8
9
private void start() {
Process.removeAllProcessGroups(); //移除所有的进程组
mProcessCpuThread.start(); //开启CpuTracker线程

mBatteryStatsService.publish(mContext); //启动电池统计服务
mAppOpsService.publish(mContext);
//创建LocalService,并添加到LocalServices
LocalServices.addService(ActivityManagerInternal.class, new LocalService());
}

调用ams.setSystemProcess

这个步骤还是在 startBootstrapServices 中执行的

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
public void setSystemProcess() {
try {
ServiceManager.addService(Context.ACTIVITY_SERVICE, this, true);
ServiceManager.addService(ProcessStats.SERVICE_NAME, mProcessStats);
ServiceManager.addService("meminfo", new MemBinder(this));
ServiceManager.addService("gfxinfo", new GraphicsBinder(this));
ServiceManager.addService("dbinfo", new DbBinder(this));
if (MONITOR_CPU_USAGE) {
ServiceManager.addService("cpuinfo", new CpuBinder(this));
}
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());

......
} catch (PackageManager.NameNotFoundException e) {
throw new RuntimeException(
"Unable to find android system package", e);
}
}

如果之前看过笔者写的binder系列,应该知道 ServiceManager.addService 主要就是添加服务

该函数的主要作用是注册服务,以及为系统进程设置Application单例并启动,是由 installSystemApplicationInfo 函数完成的

该函数最终会执行到 LoadedApk 的 installSystemApplicationInfo 函数,来设置包名为 ‘android’ 的 package 信息

1
2
3
4
5
6
7
8
/**
* Sets application info about the system package.
*/
void installSystemApplicationInfo(ApplicationInfo info, ClassLoader classLoader) {
assert info.packageName.equals("android");
mApplicationInfo = info;
mClassLoader = classLoader;
}

调用ams.installSystemProviders

在执行完startBootstrapServices后,最后会运行 startOtherServices 函数

1
2
3
4
5
6
7
8
9
10
11
12
private void startOtherServices() {
......
//安装系统Provider
mActivityManagerService.installSystemProviders();
......

mActivityManagerService.systemReady(new Runnable() {
public void run() {
......
}
}
}

安装服务,就是在某某链表中添加

installSystemProviders 中会调用 mSystemThread.installSystemProviders(providers)

1
2
3
4
5
6
try {
ActivityManager.getService().publishContentProviders(
getApplicationThread(), results);
} catch (RemoteException ex) {
throw ex.rethrowFromSystemServer();
}

那最终调用到 AMS的 publishContentProviders 函数,这个函数就是把providers放到map里等等操作

调用ams.systemReady

关于 systemReady 在SystemServer的启动流程中介绍过了

AMS是最后一个启动的服务,会调用 mActivityManagerService.systemReady

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
mActivityManagerService.systemReady(new Runnable() {
public void run() {
//启动WebView
WebViewFactory.prepareWebViewInSystemServer();
//启动系统UI
startSystemUi(context);

// 执行一系列服务的systemReady方法
networkScoreF.systemReady();
networkManagementF.systemReady();
networkStatsF.systemReady();

......

//执行一系列服务的systemRunning方法
wallpaper.systemRunning();
inputMethodManager.systemRunning(statusBarF);
location.systemRunning();

}
});

systemReady大致流程

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
public final class ActivityManagerService{

public void systemReady(final Runnable goingCallback) {
...//更新操作
mSystemReady = true; //系统处于ready状态
removeProcessLocked(proc, true, false, "system update done");//杀掉所有非persistent进程
mProcessesReady = true; //进程处于ready状态

goingCallback.run(); //这里有可能启动进程

addAppLocked(info, false, null); //启动所有的persistent进程
mBooting = true; //正在启动中
startHomeActivityLocked(mCurrentUserId, "systemReady"); //启动桌面
mStackSupervisor.resumeTopActivitiesLocked(); //恢复栈顶的Activity
}
}