开篇 本篇以android-11.0.0_r25作为基础解析
上一篇文章Android源码分析 - SystemServer(上) 我们分析了SystemServer
进程是怎么被启动起来的,今天这篇,我们来分析SystemServer
进程启动后做了什么
main 我们上一章中讲到,Zygote
进程fork
出子进程后,最终调用了SystemServer.main
方法,SystemServer
源代码在frameworks/base/services/java/com/android/server/SystemServer.java
中,我们来看看做了什么
1 2 3 public static void main (String[] args) { new SystemServer().run(); }
构造方法 非常简单,就是先new了一个SystemServer
对象,然后调用它的run
方法,我们先看一下构造方法
1 2 3 4 5 6 7 8 9 public SystemServer () { mFactoryTestMode = FactoryTest.getMode(); ... mRuntimeRestart = "1" .equals(SystemProperties.get("sys.boot_completed" )); }
工厂模式 首先,先从系统属性中获取工厂模式级别,有三种属性:
FACTORY_TEST_OFF
:正常模式
FACTORY_TEST_LOW_LEVEL
:低级别工厂模式,在此模式下,很多Service不会启动
FACTORY_TEST_HIGH_LEVEL
:高级别工厂模式,此模式与正常模式基本相同,略有区别
它们被定义在frameworks/base/core/java/android/os/FactoryTest.java
中
run 紧接着便开始执行run
方法
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 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 private void run () { ... String timezoneProperty = SystemProperties.get("persist.sys.timezone" ); if (timezoneProperty == null || timezoneProperty.isEmpty()) { Slog.w(TAG, "Timezone not set; setting to GMT." ); SystemProperties.set("persist.sys.timezone" , "GMT" ); } if (!SystemProperties.get("persist.sys.language" ).isEmpty()) { final String languageTag = Locale.getDefault().toLanguageTag(); SystemProperties.set("persist.sys.locale" , languageTag); SystemProperties.set("persist.sys.language" , "" ); SystemProperties.set("persist.sys.country" , "" ); SystemProperties.set("persist.sys.localevar" , "" ); } Binder.setWarnOnBlocking(true ); PackageItemInfo.forceSafeLabels(); ... SystemProperties.set("persist.sys.dalvik.vm.lib.2" , VMRuntime.getRuntime().vmLibrary()); VMRuntime.getRuntime().clearGrowthLimit(); Build.ensureFingerprintProperty(); Environment.setUserRequired(true ); BaseBundle.setShouldDefuse(true ); Parcel.setStackTraceParceling(true ); BinderInternal.disableBackgroundScheduling(true ); BinderInternal.setMaxThreads(sMaxBinderThreads); android.os.Process.setThreadPriority( android.os.Process.THREAD_PRIORITY_FOREGROUND); android.os.Process.setCanSelfBackground(false ); Looper.prepareMainLooper(); Looper.getMainLooper().setSlowLogThresholdMs( SLOW_DISPATCH_THRESHOLD_MS, SLOW_DELIVERY_THRESHOLD_MS); SystemServiceRegistry.sEnableServiceNotFoundWtf = true ; System.loadLibrary("android_servers" ); initZygoteChildHeapProfiling(); if (Build.IS_DEBUGGABLE) { spawnFdLeakCheckThread(); } performPendingShutdown(); createSystemContext(); ActivityThread.initializeMainlineModules(); mSystemServiceManager = new SystemServiceManager(mSystemContext); mSystemServiceManager.setStartInfo(mRuntimeRestart, mRuntimeStartElapsedTime, mRuntimeStartUptime); LocalServices.addService(SystemServiceManager.class , mSystemServiceManager ) ; SystemServerInitThreadPool.start(); ... RuntimeInit.setDefaultApplicationWtfHandler(SystemServer::handleEarlySystemWtf); ... startBootstrapServices(t); startCoreServices(t); startOtherServices(t); ... StrictMode.initVmDefaults(null ); ... Looper.loop(); throw new RuntimeException("Main thread loop unexpectedly exited" ); }
可以看到,run
方法主要做了以下工作
检查并设置各种参数handler
创建SystemContext
创建SystemServiceManager
启动服务
Looper
循环
其中,创建SystemContext
这一步是由ContextImpl
完成的,等后面分析到的时候在详细去看,Looper
也是,我们将重点放在启动服务上
启动服务 启动服务分为三步,首先是启动引导服务,其次是启动核心服务,最后是启动其他服务,我们先从引导服务开始
由于启动的服务太多了,我们只介绍一些我们比较熟悉的服务
startBootstrapServices 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 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 private void startBootstrapServices (@NonNull TimingsTraceAndSlog t) { ... final Watchdog watchdog = Watchdog.getInstance(); watchdog.start(); ... final String TAG_SYSTEM_CONFIG = "ReadingSystemConfig" ; SystemServerInitThreadPool.submit(SystemConfig::getInstance, TAG_SYSTEM_CONFIG); ... Installer installer = mSystemServiceManager.startService(Installer.class ) ; ... ActivityTaskManagerService atm = mSystemServiceManager.startService( ActivityTaskManagerService.Lifecycle.class ).getService () ; mActivityManagerService = ActivityManagerService.Lifecycle.startService( mSystemServiceManager, atm); mActivityManagerService.setSystemServiceManager(mSystemServiceManager); mActivityManagerService.setInstaller(installer); mWindowManagerGlobalLock = atm.getGlobalLock(); ... mPowerManagerService = mSystemServiceManager.startService(PowerManagerService.class ) ; ... mActivityManagerService.initPowerManagement(); ... mSystemServiceManager.startService(LightsService.class ) ; ... mDisplayManagerService = mSystemServiceManager.startService(DisplayManagerService.class ) ; ... mSystemServiceManager.startBootPhase(t, SystemService.PHASE_WAIT_FOR_DEFAULT_DISPLAY); ... try { Watchdog.getInstance().pauseWatchingCurrentThread("packagemanagermain" ); mPackageManagerService = PackageManagerService.main(mSystemContext, installer, mFactoryTestMode != FactoryTest.FACTORY_TEST_OFF, mOnlyCore); } finally { Watchdog.getInstance().resumeWatchingCurrentThread("packagemanagermain" ); } SystemServerDexLoadReporter.configureSystemServerDexReporter(mPackageManagerService); mFirstBoot = mPackageManagerService.isFirstBoot(); mPackageManager = mSystemContext.getPackageManager(); ... mSystemServiceManager.startService(UserManagerService.LifeCycle.class ) ; ... AttributeCache.init(mSystemContext); ... mActivityManagerService.setSystemProcess(); ... watchdog.init(mSystemContext, mActivityManagerService); ... mDisplayManagerService.setupSchedulerPolicies(); ... mSensorServiceStart = SystemServerInitThreadPool.submit(() -> { TimingsTraceAndSlog traceLog = TimingsTraceAndSlog.newAsyncLog(); traceLog.traceBegin(START_SENSOR_SERVICE); startSensorService(); traceLog.traceEnd(); }, START_SENSOR_SERVICE); ... }
startCoreServices 1 2 3 4 5 6 7 8 9 10 11 private void startCoreServices (@NonNull TimingsTraceAndSlog t) { ... mSystemServiceManager.startService(BatteryService.class ) ; ... mSystemServiceManager.startService(UsageStatsService.class ) ; mActivityManagerService.setUsageStatsManager( LocalServices.getService(UsageStatsManagerInternal.class )) ; ... }
startOtherServices 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 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 private void startOtherServices (@NonNull TimingsTraceAndSlog t) { ... mSystemServiceManager.startService(ACCOUNT_SERVICE_CLASS); ... mSystemServiceManager.startService(CONTENT_SERVICE_CLASS); ... mActivityManagerService.installSystemProviders(); ... mSystemServiceManager.startService(DropBoxManagerService.class ) ; ... vibrator = new VibratorService(context); ServiceManager.addService("vibrator" , vibrator); ... mSystemServiceManager.startService(new AlarmManagerService(context)); inputManager = new InputManagerService(context); ... ConcurrentUtils.waitForFutureNoInterrupt(mSensorServiceStart, START_SENSOR_SERVICE); mSensorServiceStart = null ; wm = WindowManagerService.main(context, inputManager, !mFirstBoot, mOnlyCore, new PhoneWindowManager(), mActivityManagerService.mActivityTaskManager); ServiceManager.addService(Context.WINDOW_SERVICE, wm, false , DUMP_FLAG_PRIORITY_CRITICAL | DUMP_FLAG_PROTO); ServiceManager.addService(Context.INPUT_SERVICE, inputManager, false , DUMP_FLAG_PRIORITY_CRITICAL); ... mActivityManagerService.setWindowManager(wm); ... wm.onInitReady(); ... SystemServerInitThreadPool.submit(() -> { startHidlServices(); }, START_HIDL_SERVICES); ... inputManager.setWindowManagerCallbacks(wm.getInputManagerCallback()); inputManager.start(); ... mDisplayManagerService.windowManagerAndInputReady(); ... if (mFactoryTestMode == FactoryTest.FACTORY_TEST_LOW_LEVEL) { ... } else if (!context.getPackageManager().hasSystemFeature (PackageManager.FEATURE_BLUETOOTH)) { ... } else { mSystemServiceManager.startService(BluetoothService.class ) ; } ... if (mFactoryTestMode != FactoryTest.FACTORY_TEST_LOW_LEVEL) { if (InputMethodSystemProperty.MULTI_CLIENT_IME_ENABLED) { mSystemServiceManager.startService( MultiClientInputMethodManagerService.Lifecycle.class ) ; } else { mSystemServiceManager.startService(InputMethodManagerService.Lifecycle.class ) ; } mSystemServiceManager.startService(ACCESSIBILITY_MANAGER_SERVICE_CLASS); } wm.displayReady(); if (mFactoryTestMode != FactoryTest.FACTORY_TEST_LOW_LEVEL) { if (!"0" .equals(SystemProperties.get("system_init.startmountservice" ))) { mSystemServiceManager.startService(STORAGE_MANAGER_SERVICE_CLASS); storageManager = IStorageManager.Stub.asInterface( ServiceManager.getService("mount" )); mSystemServiceManager.startService(STORAGE_STATS_SERVICE_CLASS); } } mSystemServiceManager.startService(UiModeManagerService.class ) ; ... mPackageManagerService.performFstrimIfNeeded(); if (mFactoryTestMode != FactoryTest.FACTORY_TEST_LOW_LEVEL) { ... final boolean hasPdb = !SystemProperties.get(PERSISTENT_DATA_BLOCK_PROP).equals("" ); ... if (hasPdb || OemLockService.isHalPresent()) { mSystemServiceManager.startService(OemLockService.class ) ; } ... if (!isWatch) { statusBar = new StatusBarManagerService(context); ServiceManager.addService(Context.STATUS_BAR_SERVICE, statusBar); } ConnectivityModuleConnector.getInstance().init(context); NetworkStackClient.getInstance().init(); networkManagement = NetworkManagementService.create(context); ServiceManager.addService(Context.NETWORKMANAGEMENT_SERVICE, networkManagement); ipSecService = IpSecService.create(context, networkManagement); ServiceManager.addService(Context.IPSEC_SERVICE, ipSecService); mSystemServiceManager.startService(TextServicesManagerService.Lifecycle.class ) ; mSystemServiceManager .startService(TextClassificationManagerService.Lifecycle.class ) ; mSystemServiceManager.startService(NetworkScoreService.Lifecycle.class ) ; networkStats = NetworkStatsService.create(context, networkManagement); ServiceManager.addService(Context.NETWORK_STATS_SERVICE, networkStats); networkPolicy = new NetworkPolicyManagerService(context, mActivityManagerService, networkManagement); ServiceManager.addService(Context.NETWORK_POLICY_SERVICE, networkPolicy); if (context.getPackageManager().hasSystemFeature( PackageManager.FEATURE_WIFI)) { mSystemServiceManager.startServiceFromJar( WIFI_SERVICE_CLASS, WIFI_APEX_SERVICE_JAR_PATH); mSystemServiceManager.startServiceFromJar( WIFI_SCANNING_SERVICE_CLASS, WIFI_APEX_SERVICE_JAR_PATH); } if (context.getPackageManager().hasSystemFeature( PackageManager.FEATURE_WIFI_RTT)) { mSystemServiceManager.startServiceFromJar( WIFI_RTT_SERVICE_CLASS, WIFI_APEX_SERVICE_JAR_PATH); } if (context.getPackageManager().hasSystemFeature( PackageManager.FEATURE_WIFI_AWARE)) { mSystemServiceManager.startServiceFromJar( WIFI_AWARE_SERVICE_CLASS, WIFI_APEX_SERVICE_JAR_PATH); } if (context.getPackageManager().hasSystemFeature( PackageManager.FEATURE_WIFI_DIRECT)) { mSystemServiceManager.startServiceFromJar( WIFI_P2P_SERVICE_CLASS, WIFI_APEX_SERVICE_JAR_PATH); } if (context.getPackageManager().hasSystemFeature( PackageManager.FEATURE_LOWPAN)) { mSystemServiceManager.startService(LOWPAN_SERVICE_CLASS); } if (mPackageManager.hasSystemFeature(PackageManager.FEATURE_ETHERNET) || mPackageManager.hasSystemFeature(PackageManager.FEATURE_USB_HOST)) { mSystemServiceManager.startService(ETHERNET_SERVICE_CLASS); } connectivity = new ConnectivityService( context, networkManagement, networkStats, networkPolicy); ServiceManager.addService(Context.CONNECTIVITY_SERVICE, connectivity, false , DUMP_FLAG_PRIORITY_HIGH | DUMP_FLAG_PRIORITY_NORMAL); networkPolicy.bindConnectivityManager(connectivity); ... ServiceManager.addService(Context.SYSTEM_UPDATE_SERVICE, new SystemUpdateManagerService(context)); ServiceManager.addService(Context.UPDATE_LOCK_SERVICE, new UpdateLockService(context)); mSystemServiceManager.startService(NotificationManagerService.class ) ; SystemNotificationChannels.removeDeprecated(context); SystemNotificationChannels.createAll(context); notification = INotificationManager.Stub.asInterface( ServiceManager.getService(Context.NOTIFICATION_SERVICE)); ... mSystemServiceManager.startService(LocationManagerService.Lifecycle.class ) ; ... if (context.getResources().getBoolean(R.bool.config_enableWallpaperService)) { mSystemServiceManager.startService(WALLPAPER_SERVICE_CLASS); } else { ... } if (!isArc) { mSystemServiceManager.startService(AudioService.Lifecycle.class ) ; } else { String className = context.getResources() .getString(R.string.config_deviceSpecificAudioService); mSystemServiceManager.startService(className + "$Lifecycle" ); } ... mSystemServiceManager.startService(ADB_SERVICE_CLASS); if (mPackageManager.hasSystemFeature(PackageManager.FEATURE_USB_HOST) || mPackageManager.hasSystemFeature( PackageManager.FEATURE_USB_ACCESSORY) || isEmulator) { mSystemServiceManager.startService(USB_SERVICE_CLASS); } if (mPackageManager.hasSystemFeature(PackageManager.FEATURE_APP_WIDGETS) || context.getResources().getBoolean(R.bool.config_enableAppWidgetService)) { mSystemServiceManager.startService(APPWIDGET_SERVICE_CLASS); } ... ServiceManager.addService("runtime" , new RuntimeService(context)); ... BackgroundDexOptService.schedule(context); ... } ... if (!disableCameraService) { mSystemServiceManager.startService(CameraServiceProxy.class ) ; } if (safeMode) { mActivityManagerService.enterSafeMode(); } mmsService = mSystemServiceManager.startService(MmsServiceBroker.class ) ; ... mSystemServiceManager.startService(ClipboardService.class ) ; ... vibrator.systemReady(); lockSettings.systemReady(); mSystemServiceManager.startBootPhase(t, SystemService.PHASE_LOCK_SETTINGS_READY); mSystemServiceManager.startBootPhase(t, SystemService.PHASE_SYSTEM_SERVICES_READY); wm.systemReady(); ... final Configuration config = wm.computeNewConfiguration(DEFAULT_DISPLAY); DisplayMetrics metrics = new DisplayMetrics(); context.getDisplay().getMetrics(metrics); context.getResources().updateConfiguration(config, metrics); final Theme systemTheme = context.getTheme(); if (systemTheme.getChangingConfigurations() != 0 ) { systemTheme.rebase(); } mPowerManagerService.systemReady(mActivityManagerService.getAppOpsService()); ... mPackageManagerService.systemReady(); mDisplayManagerService.systemReady(safeMode, mOnlyCore); mSystemServiceManager.setSafeMode(safeMode); mSystemServiceManager.startBootPhase(t, SystemService.PHASE_DEVICE_SPECIFIC_SERVICES_READY); ... mActivityManagerService.systemReady(() -> { mSystemServiceManager.startBootPhase(t, SystemService.PHASE_ACTIVITY_MANAGER_READY); ... mSystemServiceManager.startBootPhase(t, SystemService.PHASE_THIRD_PARTY_APPS_CAN_START); ... }, t); }
服务的启动是分阶段完成的,从0-100-480-500-520-550-600-1000,最后的阶段1000,是在AMS调用finishBooting
方法后进入
可以看到,启动的服务非常之多,不可能全看得完,其中最重要的几个:ActivityManagerService
、WindowManagerService
、PackageManagerService
和InputManagerService
,后面我们会慢慢看过去,在此之前,我们还是先看看服务启动的方式
SystemServiceManager 绝大部分的服务是通过SystemServiceManager
启动的,它的源码路径为frameworks/base/services/core/java/com/android/server/SystemServiceManager.java
startService 我们来看看这个类里的启动服务方法
这个类中有三个方法用于启动Serivce,分别是:
public SystemService startService(String className)
public SystemService startServiceFromJar(String className, String path)
public <T extends SystemService> T startService(Class<T> serviceClass)
public void startService(@NonNull final SystemService service)
实际上最后都是调用了最后一个方法
先看参数为String
的startService
方法
1 2 3 4 5 public SystemService startService (String className) { final Class<SystemService> serviceClass = loadClassFromLoader(className, this .getClass().getClassLoader()); return startService(serviceClass); }
1 2 3 4 5 6 7 8 private static Class<SystemService> loadClassFromLoader (String className, ClassLoader classLoader) { try { return (Class<SystemService>) Class.forName(className, true , classLoader); } catch (ClassNotFoundException ex) { ... } }
实际上就是通过反射拿到类名对应的Class
,再调用Class
为参的startService
方法
startServiceFromJar
实际上也是一样,只不过是先通过PathClassLoader
加载了jar而已
1 2 3 4 5 6 7 8 9 10 11 public SystemService startServiceFromJar (String className, String path) { PathClassLoader pathClassLoader = mLoadedPaths.get(path); if (pathClassLoader == null ) { pathClassLoader = new PathClassLoader(path, this .getClass().getClassLoader()); mLoadedPaths.put(path, pathClassLoader); } final Class<SystemService> serviceClass = loadClassFromLoader(className, pathClassLoader); return startService(serviceClass); }
接着我们看看Class
为参数的startService
方法
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 public <T extends SystemService> T startService (Class<T> serviceClass) { final String name = serviceClass.getName(); if (!SystemService.class .isAssignableFrom (serviceClass )) { throw new RuntimeException("Failed to create " + name + ": service must extend " + SystemService.class .getName ()) ; } final T service; try { Constructor<T> constructor = serviceClass.getConstructor(Context.class ) ; service = constructor.newInstance(mContext); } catch (...) { ... } startService(service); return service; }
看函数泛型我们就可以知道,这个方法只接受SystemService
的子类,并且在方法的开头,还使用了isAssignableFrom
方法做了类型校验,避免通过String
反射获取的Class
非SystemService
的子类
之后的逻辑也很简单,反射实例化对象,然后调用另一个以SystemService
对象为参数的重载方法
1 2 3 4 5 6 7 8 9 public void startService (@NonNull final SystemService service) { mServices.add(service); try { service.onStart(); } catch (RuntimeException ex) { throw new RuntimeException("Failed to start service " + service.getClass().getName() + ": onStart threw an exception" , ex); } }
这个方法会将SystemService
对象加入一个List
中,然后调用它的onStart
方法,通知SystemService
自行处理启动
startBootPhase 因为各种服务之间是存在依赖关系的,所以Android将服务的启动划分了8个阶段:0-100-480-500-520-550-600-1000,而startBootPhase
方法便是用来通知各个服务进行到哪一阶段了
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 public void startBootPhase (@NonNull TimingsTraceAndSlog t, int phase) { if (phase <= mCurrentPhase) { throw new IllegalArgumentException("Next phase must be larger than previous" ); } mCurrentPhase = phase; final int serviceLen = mServices.size(); for (int i = 0 ; i < serviceLen; i++) { final SystemService service = mServices.get(i); service.onBootPhase(mCurrentPhase); } if (phase == SystemService.PHASE_BOOT_COMPLETED) { SystemServerInitThreadPool.shutdown(); } }
每进入到一个阶段,便会调用Service List中所有SystemService
的onBootPhase
方法,通知SystemService
阶段变换,而当阶段达到1000 (PHASE_BOOT_COMPLETED) 时,就代表着所有的服务都已准备完毕,关闭SystemServerInitThreadPool
线程池
ServiceManager 当服务被创建出来后,会调用ServiceManager.addService
方法添加服务,以供其他地方使用这些服务
addService
有三个重载,最终调用的为:
1 2 3 4 5 6 7 8 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); } }
1 2 3 4 5 6 7 8 9 10 private static IServiceManager getIServiceManager () { if (sServiceManager != null ) { return sServiceManager; } sServiceManager = ServiceManagerNative .asInterface(Binder.allowBlocking(BinderInternal.getContextObject())); return sServiceManager; }
1 2 3 4 5 6 7 8 public static IServiceManager asInterface (IBinder obj) { if (obj == null ) { return null ; } return new ServiceManagerProxy(obj); }
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 class ServiceManagerProxy implements IServiceManager { public ServiceManagerProxy (IBinder remote) { mRemote = remote; mServiceManager = IServiceManager.Stub.asInterface(remote); } public IBinder asBinder () { return mRemote; } ... public void addService (String name, IBinder service, boolean allowIsolated, int dumpPriority) throws RemoteException { mServiceManager.addService(name, service, allowIsolated, dumpPriority); } ... private IBinder mRemote; private IServiceManager mServiceManager; }
从这里就能看出来ServiceManager
实际上是一个单独的进程,名为servicemanager
,它负责管理所有服务,使用了Binder
IPC机制,我们调用addService
方法实际上是调用了Binder Proxy的方法,他向/dev/binder
中写入消息,在servicemanager
进程中接收到了这个消息并处理这个请求
关于Binder
机制,我们随后便会分析它
最终调用了frameworks/native/cmds/servicemanager/ServiceManager.cpp
中的addService
函数
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 Status ServiceManager::addService (const std ::string & name, const sp<IBinder>& binder, bool allowIsolated, int32_t dumpPriority) { auto ctx = mAccess->getCallingContext(); ... auto entry = mNameToService.emplace(name, Service { .binder = binder, .allowIsolated = allowIsolated, .dumpPriority = dumpPriority, .debugPid = ctx.debugPid, }); auto it = mNameToRegistrationCallback.find (name); if (it != mNameToRegistrationCallback.end ()) { for (const sp<IServiceCallback>& cb : it->second) { entry.first->second.guaranteeClient = true ; cb->onRegistration(name, binder); } } return Status::ok(); }
可以看到,最终通过service name
和传过来的binder
对象构造出一个Service
结构体,并将其保存至mNameToService
这个Map中,以供后面使用
关于进程 SystemServer
启动的服务大多都运行在systemserver
进程中,但也有一些例外
譬如Installer
服务,便是从init
进程单独fork
出了一个installd
进程
下面是它的rc文件,frameworks/native/cmds/installd/installd.rc
1 2 3 service installd /system/bin/installd class main ...
而在SystemServer
进程中start的Installer
,便是通过binder
连接到installd
进程提供服务
源码路径frameworks/base/services/core/java/com/android/server/pm/Installer.java
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 @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); } }
结束 SystemServer
启动了非常多的服务,并将这些服务添加到了ServiceManager
中,我们又从中引申出了Binder
机制,我们下一章便开始分析Binder