在学习bindService()流程时注意到ActivityManagerService是一个Binder对象,就如同我们自定义服务MyService中的onBind()方法返回的Stub对象,那ActivityManagerService是在哪个系统服务的onBind方法中返回的?这个系统服务叫什么?即这个系统Service叫什么?
ActivityManagerService保存在SystemServer中,是SystemServer的成员属性mActivityManagerService:
public final class SystemServer {
private static final String TAG = "SystemServer";
...
// TODO: remove all of these references by improving dependency resolution and boot phases
private PowerManagerService mPowerManagerService;
private ActivityManagerService mActivityManagerService; //AMS
private DisplayManagerService mDisplayManagerService;
private PackageManagerService mPackageManagerService;
private PackageManager mPackageManager;
private ContentResolver mContentResolver;
...
/**
* Starts the small tangle of critical services that are needed to get
* the system off the ground. These services have complex mutual dependencies
* which is why we initialize them all in one place here. Unless your service
* is also entwined in these dependencies, it should be initialized in one of
* the other functions.
*/
private void startBootstrapServices() {
// Wait for installd to finish starting up so that it has a chance to
// create critical directories such as /data/user with the appropriate
// permissions. We need this to complete before we initialize other services.
Installer installer = mSystemServiceManager.startService(Installer.class);
// Activity manager runs the show.
mActivityManagerService = mSystemServiceManager.startService(
ActivityManagerService.Lifecycle.class).getService();
mActivityManagerService.setSystemServiceManager(mSystemServiceManager);
mActivityManagerService.setInstaller(installer);
...
}
}
ActivityManagerService在SystemServerstartBootstrapServices()方法中启动,最终是调用SystemServiceManager#startService方法创建并且启动的:
public class SystemServiceManager {
...
// Services that should receive lifecycle events.
private final ArrayList<SystemService> mServices = new ArrayList<SystemService>();
...
public <T extends SystemService> T startService(Class<T> serviceClass) {
...
Constructor<T> constructor = serviceClass.getConstructor(Context.class);
service = constructor.newInstance(mContext);
...
// Register it.
mServices.add(service);
// Start it.
try {
service.onStart();
} catch (RuntimeException ex) {
throw new RuntimeException("Failed to start service " + name
+ ": onStart threw an exception", ex);
}
...
}
}
参考:
https://www.androidos.net.cn/android/6.0.1_r16/xref/frameworks/base/services/java/com/android/server/SystemServer.java
https://www.androidos.net.cn/android/6.0.1_r16/xref/frameworks/base/services/core/java/com/android/server/SystemService.java
https://www.androidos.net.cn/android/6.0.1_r16/xref/frameworks/base/services/core/java/com/android/server/SystemServiceManager.java
https://www.androidos.net.cn/android/6.0.1_r16/xref/frameworks/base/core/java/android/os/ServiceManager.java