AMS启动过程
首先需要明白一点的是AMS的启动在SytemServer进程中启动的;
public static void main(String[] args) {
new SystemServer().run();
}
进入run()方法:
private void run() {
//1.创建消息Looper
Looper.prepareMainLooper();
// Initialize native services.
//2.加载了动态库libandroid_server.so
System.loadLibrary("android_servers");
// Check whether we failed to shut down last time we tried.
// This call may not return.
performPendingShutdown();
// Initialize the system context.
//3.创建系统的Context
createSystemContext();
// Create the system service manager.
//4.创建SystemServiceManager
mSystemServiceManager = new SystemServiceManager(mSystemContext);
// Start services.
try {
traceBeginAndSlog("StartServices");
//启动引导服务
startBootstrapServices();
//启动核心服务
startCoreServices();
//启动其他服务
startOtherServices();
SystemServerInitThreadPool.shutdown();
} catch (Throwable ex) {
Slog.e("System", "******************************************");
Slog.e("System", "************ Failure starting system services", ex);
throw ex;
} finally {
traceEnd();
}
// Loop forever.
Looper.loop();
throw new RuntimeException("Main thread loop unexpectedly exited");
}
这里会创建SystemServiceManager:用于系统服务创建、启动、管理生命周期;紧接着就会起启动系统服务;官方将系统服务分为三类:引导服务、核心服务、其他服务;这里的AMS属于引导服务:
接着进入startBootstrapService():
private void startBootstrapServices() {
mActivityManagerService = mSystemServiceManager.startService(
ActivityManagerService.Lifecycle.class).getService();
mActivityManagerService.setSystemServiceManager(mSystemServiceManager);
mActivityManagerService.setInstaller(installer);
.......启动一系列系统服务
}
利用SystemServiceManager启动服务,进入startService(Class clas):
public <T extends SystemService> T startService(Class<T> serviceClass) {
final String name = serviceClass.getName();
final T service;
Constructor<T> constructor = serviceClass.getConstructor(Context.class);
service = constructor.newInstance(mContext);
startService(service);
return service;
}
利用反射创建系统服务实例,进入startService(SystemServer service);
public void startService(@NonNull final SystemService service) {
// Register it.
mServices.add(service);
// Start it.
long time = System.currentTimeMillis();
try {
service.onStart();
} catch (RuntimeException ex) {
throw new RuntimeException("Failed to start service " + service.getClass().getName()
+ ": onStart threw an exception", ex);
}
}
很简单就是service添加到ArrayList类型的mService完成注册,接着就是调用service的onstart()来完成启动,这里的Lifecycle继承自SystemServer,构造器内部会创建ActivityManagerService对象,调用其onstart()方法,实际上调用的是AMS的start()方法;