AMS 由 SystemServer.java 启动,后者负责诸多 Service 的启动,比如 WMS,PWS 等。
private void run(){
...
startBootstrapServices();
startCoreServices();
startOtherServices();
...
}
启动我们的 AMS 在startBootstrapServices()方法中初始化:
...
mActivityManagerService = mySystemServiceManager.startService(ActivityManagerService.Lifecycle.class).getService();
mActivityManagerService.setSystemServiceManager(mSystemServiceManager);
...
//重点有将 AMS 的服务注册到 SM
mActivityManagerService.setSystemProcess();
首先这个mSystemServiceManager 是 SystemServiceManager.java,可以看到,这里是利用反射实例化一个 SystemService对象并且加入内部的 ArrayList中
@SuppressWarnings("unchecked")
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);
...
// Register it.
mServices.add(service);
// Start it.
...
service.onStart();
...
return service;
}
//以下是 ActivityManagerService.Lifecycle
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();
}
public ActivityManagerService getService() {
return mService;
}
}
由上面可以知道,实例化了一个 Lifecycle 对象,后者的构造函数实例化了 AMS,并且通过Lifecycle 的onStart()调用了 AMS.start()
private void start() {
Process.removeAllProcessGroups();
//启动 CpuTracker 线程
mProcessCpuThread.start();
//启动电池统计服务
mBatteryStatsService.publish(mContext);
mAppOpsService.publish(mContext);
Slog.d("AppOps", "AppOpsService published");
//创建 LocalService 并且添加
LocalServices.addService(ActivityManagerInternal.class, new LocalService());
}
随后的一个关键函数是在 SystemServer.java 中startOtherServices()方法中:
...
private void startOtherServices(){
mActivityManagerService.systemReady(new Runnable(){
...
}
);
}
...
在ActivityManagerService.java 中,通过 startHomeActivityLocked()启动桌面程序,即 Launcher
public void systemReady(final Runnable goingCallback){
...
startHomeActivityLocked(mCurrentUserid,"systemReady");
...
}
private void start() {
Process.removeAllProcessGroups();
//启动 CpuTracker 线程
mProcessCpuThread.start();
//启动电池统计服务
mBatteryStatsService.publish(mContext);
mAppOpsService.publish(mContext);
Slog.d("AppOps", "AppOpsService published");
//创建 LocalService 并且天机
LocalServices.addService(ActivityManagerInternal.class, new LocalService());
}
public void setSystemProcess(){
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));
...//注册各种子服务
//创建了 ProcessRecord 对象
ProcessRecord app = newProcessRecordLocked(info, info.processName, false, o);
...
}
AMS 在system 进程,主要负责 和其他进程进行通信处理 Activity(主页),其通信机制是利用 Binder 驱动进行转发。因此在研究 AMS 时,要主要所研究的对象所在的进程。