在SystemServer启动的时候会去执行run函数,函数里面有startBootstrapServices();是去启动引导级服务
主要启动以下10个服务:
还有在启动这些服务之前会去启动Watchdog,它的作用就是去监听SystemServer是否发生死锁,会就把SystemServer进程杀掉。
本文重点是ActivityManagerService
frameworks\base\services\java\com\android\server\SystemServer.java:
- Installer installer = mSystemServiceManager.startService(Installer.class);
- // Activity manager runs the show.
- traceBeginAndSlog("StartActivityManager");
- // TODO: Might need to move after migration to WM.
- ActivityTaskManagerService atm = mSystemServiceManager.startService(
- ActivityTaskManagerService.Lifecycle.class).getService();
- mActivityManagerService = ActivityManagerService.Lifecycle.startService(
- mSystemServiceManager, atm);
- mActivityManagerService.setSystemServiceManager(mSystemServiceManager);
- mActivityManagerService.setInstaller(installer);
- mWindowManagerGlobalLock = atm.getGlobalLock();
- traceEnd();
上面是SystemServer的startBootstrapServices函数中关于ActivityManagerService的内容,
- public SystemService startService(String className) {
- final Class
serviceClass; - try {
- serviceClass = (Class
)Class.forName(className); - } catch (ClassNotFoundException ex) {
- ....
- }
- return startService(serviceClass);
- }
-
- public
extends SystemService> T startService(Class serviceClass) { - try {
- final String name = serviceClass.getName();
- .....
- final T service;
- try {
- Constructor
constructor = serviceClass.getConstructor(Context.class); - service = constructor.newInstance(mContext);
- } catch (InstantiationException ex) {
- .....
- }
-
- startService(service);
- return service;
- } finally {
- Trace.traceEnd(Trace.TRACE_TAG_SYSTEM_SERVER);
- }
- }
-
- public void startService(@NonNull final SystemService service) {
- // Register it.
- mServices.add(service);
- // Start it.
- long time = SystemClock.elapsedRealtime();
- try {
- 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");
- }
mSystemServiceManager.startService(Installer.class);一路跟下来就是去反射获取Installer对象然后调用它的onStart方法,且Installer类继承了SystemService。
- @Override
- public void onStart() {
- if (mIsolated) {
- mInstalld = null;
- } else {
- connect();
- }
- }
-
- private void connect() {
- IBinder binder = ServiceManager.getService("installd");
- if (binder != null) {
- try {
- binder.linkToDeath(new DeathRecipient() {
- @Override
- public void binderDied() {
- Slog.w(TAG, "installd died; reconnecting");
- connect();
- }
- }, 0);
- } catch (RemoteException e) {
- binder = null;
- }
- }
-
- if (binder != null) {
- mInstalld = IInstalld.Stub.asInterface(binder);
- try {
- invalidateMounts();
- } catch (InstallerException ignored) {
- }
- } else {
- Slog.w(TAG, "installd not found; trying again");
- BackgroundThread.getHandler().postDelayed(() -> {
- connect();
- }, DateUtils.SECOND_IN_MILLIS);
- }
- }
-
- public void invalidateMounts() throws InstallerException {
- if (!checkBeforeRemote()) return;
- try {
- mInstalld.invalidateMounts();
- } catch (Exception e) {
- throw InstallerException.from(e);
- }
- }
onStart里面去调用了connect,然后获取installd服务的BInder对象,最后执行了该Binder对象的invalidateMounts方法。我们可以知道mInstalld对象的服务名叫installd,全局搜一下。
frameworks\native\cmds\installd\InstalldNativeService.h:
- class InstalldNativeService : public BinderService
, public os::BnInstalld { - public:
- static status_t start();
- static char const* getServiceName() { return "installd"; }
- ....
- }
发现这个就是我们找的mInstalld对象所对应的类,接下来进入cpp文件查看它的方法。

可以看出installd服务的方法基本都是在操作应用数据的,apk应用的安装和卸载主要是由它来完成。
- binder::Status InstalldNativeService::invalidateMounts() {
- ENFORCE_UID(AID_SYSTEM);
- std::lock_guard
lock(mMountsLock) ; -
- mStorageMounts.clear();
-
- #if !BYPASS_QUOTA
- if (!InvalidateQuotaMounts()) {
- return error("Failed to read mounts");
- }
- #endif
-
- std::ifstream in("/proc/mounts");
- if (!in.is_open()) {
- return error("Failed to read mounts");
- }
-
- std::string source;
- std::string target;
- std::string ignored;
- while (!in.eof()) {
- std::getline(in, source, ' ');
- std::getline(in, target, ' ');
- std::getline(in, ignored);
-
- #if !BYPASS_SDCARDFS
- if (target.compare(0, 21, "/mnt/runtime/default/") == 0) {
- LOG(DEBUG) << "Found storage mount " << source << " at " << target;
- mStorageMounts[source] = target;
- }
- #endif
- }
- return ok();
- }
invalidateMounts就是去查看设备挂载的存储空间是否可读等,以此判断自己能否对应用存储空间进行操作。
ActivityTaskManagerService简称ATM,Android10中引入新功能,用来管理Activity的启动、调度等功能。
我们从上面知道了startService会实例化对应Service,然后调用onStart方法,这里直接看ActivityTaskManagerService.Lifecycle的onStart方法
- public static final class Lifecycle extends SystemService {
- private final ActivityTaskManagerService mService;
-
- public Lifecycle(Context context) {
- super(context);
- mService = new ActivityTaskManagerService(context);
- }
-
- @Override
- public void onStart() {
- publishBinderService(Context.ACTIVITY_TASK_SERVICE, mService);
- mService.start();
- }
-
- ....
-
- public ActivityTaskManagerService getService() {
- return mService;
- }
- }
Lifecycle是ActivityTaskManagerService的内部类,也继承了SystemService,而且内部持有外部类ActivityTaskManagerService的对象,可以看到Lifecycle构造函数里面也构建了外部类对象,并且在onStart的时候也调了它的start方法。
我们看一下ActivityTaskManagerService有什么内容:
-
- public class ActivityTaskManagerService extends IActivityTaskManager.Stub {
- final Context mUiContext;
- final ActivityThread mSystemThread;
- final ActivityTaskManagerInternal mInternal;
-
- //ActivityStackSupervisor 原本是ATM中用来管理Activity启动和调度的核心类
- public ActivityStackSupervisor mStackSupervisor;
- //Activity 容器的根节点
- RootActivityContainer mRootActivityContainer;
- //WMS 负责窗口的管理
- WindowManagerService mWindowManager;
-
- WindowProcessController mHomeProcess;
-
- public ActivityTaskManagerService(Context context) {
- //拿到System Context
- mContext = context;
- mFactoryTest = FactoryTest.getMode();
-
- //取出的是ActivityThread的静态变量sCurrentActivityThread
- //这意味着mSystemThread与SystemServer中的ActivityThread一致
- mSystemThread = ActivityThread.currentActivityThread();
-
- //拿到System UI Context
- mUiContext = mSystemThread.getSystemUiContext();
- mLifecycleManager = new ClientLifecycleManager();
- //拿到LocalService的对象
- mInternal = new LocalService();
- GL_ES_VERSION = SystemProperties.getInt("ro.opengles.version", GL_ES_VERSION_UNDEFINED);
- }
- }
-
-
接下来看publishBinderService
- protected final void publishBinderService(String name, IBinder service) {
- publishBinderService(name, service, false);
- }
-
- protected final void publishBinderService(String name, IBinder service,
- boolean allowIsolated) {
- publishBinderService(name, service, allowIsolated, DUMP_FLAG_PRIORITY_DEFAULT);
- }
-
- protected final void publishBinderService(String name, IBinder service,
- boolean allowIsolated, int dumpPriority) {
- ServiceManager.addService(name, service, allowIsolated, dumpPriority);
- }
frameworks\base\core\java\android\os\ServiceManager.java:
- @UnsupportedAppUsage
- public static void addService(String name, IBinder service, boolean allowIsolated,
- int dumpPriority) {
- try {
- getIServiceManager().addService(name, service, allowIsolated, dumpPriority);
- } catch (RemoteException e) {
- Log.e(TAG, "error in addService", e);
- }
- }
-
- @UnsupportedAppUsage
- private static IServiceManager getIServiceManager() {
- if (sServiceManager != null) {
- return sServiceManager;
- }
-
- // Find the service manager
- sServiceManager = ServiceManagerNative
- .asInterface(Binder.allowBlocking(BinderInternal.getContextObject()));
- return sServiceManager;
- }
-
- public static final native IBinder getContextObject();
可以看到publishBinderService(Context.ACTIVITY_TASK_SERVICE, mService);跟到后面是 getIServiceManager().addService(name, service, allowIsolated, dumpPriority);
这个ServiceManager是通过BinderInternal.getContextObject()获取IBinder对象然后再asInterface封装成IServiceManager,跟我们之前分析的Binder非常相似,这里也只是一个BpBinder而已,不是真正处理工作的地方。
我们全局搜一下哪里动态注册了这个getContextObject方法,
frameworks\base\core\java\com\android\internal\os\BinderInternal.java:
{ "getContextObject", "()Landroid/os/IBinder;", (void*)android_os_BinderInternal_getContextObject }
- static jobject android_os_BinderInternal_getContextObject(JNIEnv* env, jobject clazz)
- {
- sp
b = ProcessState::self()->getContextObject(NULL); - return javaObjectForIBinder(env, b);
- }
果然这里就是去调用了ProcessState的getContextObject方法,不熟悉这里的可以去看前文:
Android_Binder—分析MediaServer解析服务的初始化和注册
ProcessState的getContextObject方法就是返回了一个BPBinder。
- //如果参数是JavaBBinder,返回用于创建它的Java对象。
- //否则返回IBinder的绑定代理。如果传递了之前的呼叫
- //如果原来的绑定代理仍然存在,则返回原来的绑定代理。
- jobject javaObjectForIBinder(JNIEnv* env, const sp
& val) - {
- if (val == NULL) return NULL;
-
- if (val->checkSubclass(&gBinderOffsets)) {
- // It's a JavaBBinder created by ibinderForJavaObject. Already has Java object.
- jobject object = static_cast
(val.get())->object(); - LOGDEATH("objectForBinder %p: it's our own %p!\n", val.get(), object);
- return object;
- }
-
- BinderProxyNativeData* nativeData = new BinderProxyNativeData();
- nativeData->mOrgue = new DeathRecipientList;
- nativeData->mObject = val;
-
- jobject object = env->CallStaticObjectMethod(gBinderProxyOffsets.mClass,
- gBinderProxyOffsets.mGetInstance, (jlong) nativeData, (jlong) val.get());
- if (env->ExceptionCheck()) {
- // In the exception case, getInstance still took ownership of nativeData.
- return NULL;
- }
- BinderProxyNativeData* actualNativeData = getBPNativeData(env, object);
- if (actualNativeData == nativeData) {
- // Created a new Proxy
- uint32_t numProxies = gNumProxies.fetch_add(1, std::memory_order_relaxed);
- uint32_t numLastWarned = gProxiesWarned.load(std::memory_order_relaxed);
- if (numProxies >= numLastWarned + PROXY_WARN_INTERVAL) {
- // Multiple threads can get here, make sure only one of them gets to
- // update the warn counter.
- if (gProxiesWarned.compare_exchange_strong(numLastWarned,
- numLastWarned + PROXY_WARN_INTERVAL, std::memory_order_relaxed)) {
- ALOGW("Unexpectedly many live BinderProxies: %d\n", numProxies);
- }
- }
- } else {
- delete nativeData;
- }
-
- return object;
- }
这个方法注释已经写得很清楚了,因为我们这里传进去的是一个BPBinder而不是JavaBBinder,所以返回的是由这个BPBinder对象生成的BinderProxy(Java)对象,BpBinder对象地址保存到BinderProxy.mObject成员变量,实现了Java对象拥有了native对象的引用。
sServiceManager = ServiceManagerNative
.asInterface(Binder.allowBlocking(BinderInternal.getContextObject()));
分析完 getContextObject,allowBlocking没什么作用,我们继续看ServiceManagerNative.asInterface,
- static public IServiceManager asInterface(IBinder obj)
- {
- if (obj == null) {
- return null;
- }
- IServiceManager in =
- (IServiceManager)obj.queryLocalInterface(descriptor);
- if (in != null) {
- return in;
- }
-
- return new ServiceManagerProxy(obj);
- }
-
- /**
- * Retrieve a local interface - always null in case of a proxy
- */
- public IInterface queryLocalInterface(String descriptor) {
- return null;
- }
我们可以知道这个IBinder是BinderProxy,我们要知道一个代理对象的queryLocalInterface方法一直是返回null,所以最终返回的是ServiceManagerProxy对象。
getIServiceManager().addService(name, service, allowIsolated, dumpPriority);
所以getIServiceManager()就是获取一个BpServiceManager然后封装成ServiceManagerProxy,接下来我们看看addService
- @UnsupportedAppUsage
- public static void addService(String name, IBinder service, boolean allowIsolated,
- int dumpPriority) {
- try {
- getIServiceManager().addService(name, service, allowIsolated, dumpPriority);
- } catch (RemoteException e) {
- Log.e(TAG, "error in addService", e);
- }
- }
frameworks\base\core\java\android\os\ServiceManagerNative.java:
- public ServiceManagerProxy(IBinder remote) {
- mRemote = remote;
- }
- public void addService(String name, IBinder service, boolean allowIsolated, int dumpPriority)
- throws RemoteException {
- Parcel data = Parcel.obtain();
- Parcel reply = Parcel.obtain();
- data.writeInterfaceToken(IServiceManager.descriptor);
- data.writeString(name);
- data.writeStrongBinder(service);
- data.writeInt(allowIsolated ? 1 : 0);
- data.writeInt(dumpPriority);
- mRemote.transact(ADD_SERVICE_TRANSACTION, data, reply, 0);
- reply.recycle();
- data.recycle();
- }
这里就是熟悉的Binder通讯了,明显可以看出这个ServiceManagerProxy就是代理调用transact方法,mRemote就是BinderProxy,分析它的transcat方法。
- public boolean transact(int code, Parcel data, Parcel reply, int flags) throws RemoteException {
- ....
- try {
- return transactNative(code, data, reply, flags);
- } finally {
- ....
- }
- }
-
- public native boolean transactNative(int code, Parcel data, Parcel reply,
- int flags) throws RemoteException;
{"transactNative", "(ILandroid/os/Parcel;Landroid/os/Parcel;I)Z", (void*)android_os_BinderProxy_transact}
- static jboolean android_os_BinderProxy_transact(JNIEnv* env, jobject obj,
- jint code, jobject dataObj, jobject replyObj, jint flags) // throws RemoteException
- {
- ....
- IBinder* target = getBPNativeData(env, obj)->mObject.get();
- ....
- status_t err = target->transact(code, *data, reply, flags);
- ....
- if (err == NO_ERROR) {
- return JNI_TRUE;
- } else if (err == UNKNOWN_TRANSACTION) {
- return JNI_FALSE;
- }
- return JNI_FALSE;
- }
这里又从 BinderProxy中拿回Native层的BPBinder调用它的transact方法。
所以publishBinderService(Context.ACTIVITY_TASK_SERVICE, mService);就是把ActivityTaskManagerService添加到ServiceManager里面。相比于Native就是多了一层ServiceManagerProxy和BinderProxy用来连接Java与Native。
@Override
public void onStart() {
publishBinderService(Context.ACTIVITY_TASK_SERVICE, mService);
mService.start();
}
接下来分析mService.start();
- private void start() {
- LocalServices.addService(ActivityTaskManagerInternal.class, mInternal);
- }
这个 LocalServices和mInternal是什么呢?
- /**
- * 该类的使用方式与ServiceManager类似,只是这里注册的服务不是Binder对象,
- * 只能在同一个进程中使用。
- *
- * 一旦所有服务都转换为SystemService接口,这个类就可以被SystemServiceManager吸收。
- */
- public final class LocalServices {
- private LocalServices() {}
-
- private static final ArrayMap
, Object> sLocalServiceObjects = - new ArrayMap
, Object>(); -
- /**
- * Returns a local service instance that implements the specified interface.
- *
- * @param type The type of service.
- * @return The service object.
- */
- @SuppressWarnings("unchecked")
- public static
T getService(Class type) { - synchronized (sLocalServiceObjects) {
- return (T) sLocalServiceObjects.get(type);
- }
- }
-
- /**
- * Adds a service instance of the specified interface to the global registry of local services.
- */
- public static
void addService(Class type, T service) { - synchronized (sLocalServiceObjects) {
- if (sLocalServiceObjects.containsKey(type)) {
- throw new IllegalStateException("Overriding service registration");
- }
- sLocalServiceObjects.put(type, service);
- }
- }
- .....
- }
LocalServices就是一个存放服务在SystemServer进程的地方,SystemServer进程下的服务可以获取其他服务来实现自己的功能。
mInternal的话我们看
- public Lifecycle(Context context) {
- super(context);
- mService = new ActivityTaskManagerService(context);
- }
-
- @VisibleForTesting(visibility = VisibleForTesting.Visibility.PACKAGE)
- public ActivityTaskManagerService(Context context) {
- mContext = context;
- mFactoryTest = FactoryTest.getMode();
- mSystemThread = ActivityThread.currentActivityThread();
- mUiContext = mSystemThread.getSystemUiContext();
- mLifecycleManager = new ClientLifecycleManager();
- mInternal = new LocalService();
- GL_ES_VERSION = SystemProperties.getInt("ro.opengles.version", GL_ES_VERSION_UNDEFINED);
- }
-
- final class LocalService extends ActivityTaskManagerInternal
所以mInternal就是ActivityTaskManagerInternal对象。
ATMS启动