一、内容预览
内容预览.png二、概述
前面进程系列已经更新了三篇,本文(基于Android O源码),第三篇中System进程已经创建好了,本篇主要讲解SystemServer进程启动做了哪些事情,SystemServer中运行的服务有八十多种,包括ActivityManagerService(AMS),WindowManagerService(WMS),PackagManagerService(PMS)等;这些系统服务都是以一个线程的方式存在Systemserver进程中。
Android进程系列第一篇---进程基础
Android进程系列第二篇---Zygote进程的创建流程
Android进程系列第三篇---SystemServer进程创建流程
简要回顾上一篇的重点的内容
- SystemServer进程是Zygote进程的大弟子,是Zygote进程fork的第一个进程,因注册了SigChldHandler,SystemServer和Zygote共存亡。
- 在fork新进程的基础上,第一步:调用redirectLogStreams初始化Android LOG输出流,将system.out, system.err关闭, 将两者重新定向到Android log中 。
- 在fork新进程的基础上,第二步:调用redirectLogStreams初始化Android LOG输出流,将system.out, system.err关闭, 将两者重新定向到Android log中 。
- 在fork新进程的基础上,第三步:调用nativeZygoteInit,开启Binder线程池 。
- 在fork新进程的基础上,第四步:调用applicationInit,来到invokeStaticMain方法,抛出一个Zygote.MethodAndArgsCaller异常,以此调用SytemServer的main方法。
三、SystemServer进程的启动流程
3.1、SystemServer类的main方法
/frameworks/base/services/java/com/android/server/SystemServer.java
256 /**
257 * The main entry point from zygote.
258 */
259 public static void main(String[] args) {
260 new SystemServer().run();
261 }
/frameworks/base/services/java/com/android/server/SystemServer.java
270 private void run() {
271 try {
272 traceBeginAndSlog("InitBeforeStartServices");
273 // If a device's clock is before 1970 (before 0), a lot of
274 // APIs crash dealing with negative numbers, notably
275 // java.io.File#setLastModified, so instead we fake it and
276 // hope that time from cell towers or NTP fixes it shortly.
//1、首先判断系统当前时间,为防止一些和时间相关的初始化出错,若当前时间小于1970年1月1日,设置系统当前时间为该时间点。
277 if (System.currentTimeMillis() < EARLIEST_SUPPORTED_TIME) {
278 Slog.w(TAG, "System clock is before 1970; setting to 1970.");
279 SystemClock.setCurrentTimeMillis(EARLIEST_SUPPORTED_TIME);
280 }
281
...
291 // If the system has "persist.sys.language" and friends set, replace them with
292 // "persist.sys.locale". Note that the default locale at this point is calculated
293 // using the "-Duser.locale" command line flag. That flag is usually populated by
294 // AndroidRuntime using the same set of system properties, but only the system_server
295 // and system apps are allowed to set them.
296 //
297 // NOTE: Most changes made here will need an equivalent change to
298 // core/jni/AndroidRuntime.cpp
//2、设置系统的语言环境等
299 if (!SystemProperties.get("persist.sys.language").isEmpty()) {
300 final String languageTag = Locale.getDefault().toLanguageTag();
301
302 SystemProperties.set("persist.sys.locale", languageTag);
303 SystemProperties.set("persist.sys.language", "");
304 SystemProperties.set("persist.sys.country", "");
305 SystemProperties.set("persist.sys.localevar", "");
306 }
307
...
//3、设置当前虚拟机的运行库路径
326 SystemProperties.set("persist.sys.dalvik.vm.lib.2", VMRuntime.getRuntime().vmLibrary());
327
...
340 // Mmmmmm... more memory!
341 VMRuntime.getRuntime().clearGrowthLimit();
342
343 // The system server has to run all of the time, so it needs to be
344 // as efficient as possible with its memory usage.
//4、 设置虚拟机堆内存
345 VMRuntime.getRuntime().setTargetHeapUtilization(0.8f);
346
347 // Some devices rely on runtime fingerprint generation, so make sure
348 // we've defined it before booting further.
349 Build.ensureFingerprintProperty();
350
351 // Within the system server, it is an error to access Environment paths without
352 // explicitly specifying a user.
353 Environment.setUserRequired(true);
354
355 // Within the system server, any incoming Bundles should be defused
356 // to avoid throwing BadParcelableException.
357 BaseBundle.setShouldDefuse(true);
358
359 // Ensure binder calls into the system always run at foreground priority.
360 BinderInternal.disableBackgroundScheduling(true);
361
362 // Increase the number of binder threads in system_server
363 BinderInternal.setMaxThreads(sMaxBinderThreads);
364
365 // Prepare the main looper thread (this thread).
//5、设置线程优先级
366 android.os.Process.setThreadPriority(
367 android.os.Process.THREAD_PRIORITY_FOREGROUND);
368 android.os.Process.setCanSelfBackground(false);
//6、 初始化主线程Looper
369 Looper.prepareMainLooper();
370
371 // Initialize native services.
//7、 装载libandroid_servers.so库
372 System.loadLibrary("android_servers");
373
374 // Check whether we failed to shut down last time we tried.
375 // This call may not return.
376 performPendingShutdown();
377
378 // Initialize the system context.
//8、 创建System的context
379 createSystemContext();
380
381 // Create the system service manager.
//9、 创建SystemServiceManager,负责服务的启动
382 mSystemServiceManager = new SystemServiceManager(mSystemContext);
383 mSystemServiceManager.setRuntimeRestarted(mRuntimeRestart);
384 LocalServices.addService(SystemServiceManager.class, mSystemServiceManager);
385 // Prepare the thread pool for init tasks that can be parallelized
386 SystemServerInitThreadPool.get();
387 } finally {
388 traceEnd(); // InitBeforeStartServices
389 }
390
391 //10、Start services. 真正的开启服务了
392 try {
393 traceBeginAndSlog("StartServices");
394 startBootstrapServices();
395 startCoreServices();
396 startOtherServices();
397 SystemServerInitThreadPool.shutdown();
398 } catch (Throwable ex) {
399 Slog.e("System", "******************************************");
400 Slog.e("System", "************ Failure starting system services", ex);
401 throw ex;
402 } finally {
403 traceEnd();
404 }
405
...
419
420 //11、 进入Loop循环,处理消息循环
421 Looper.loop();
422 throw new RuntimeException("Main thread loop unexpectedly exited");
423 }
main里面做的事情大概如下。
- 检验时间:如果当前时间早于1970年,则设置当前时间为1970年,防止初始化出错。
- 设置系统的语言环境等
- 设置当前虚拟机的运行库路径为persist.sys.dalvik.vm.lib.2
- 设置虚拟机的堆内存,虚拟机堆利用率为0.8
- 调用prepareMainLooper()初始化当前线程的Looper
- 加载libandroid_servers.so库
- 调用createSystemContext()创建System的context,见【3.1.1小节】
- 创建大管家SystemServiceManager的对象mSystemServiceManager,负责系统Service的管理,见【3.1.2小节】
- 调用startBootstrapServices();startCoreServices();startOtherServices(),创建和运行系统中所有的服务,见【3.1.3小节】
- 调用Looper.loop(),开启消息循环;
3.1.1、调用createSystemContext创建Context
createSystemContext中创建了2个Context,一个是mSystemContext,另一个是systemUiContext。
/frameworks/base/services/java/com/android/server/SystemServer.java
475 private void createSystemContext() {
476 ActivityThread activityThread = ActivityThread.systemMain();
477 mSystemContext = activityThread.getSystemContext();
478 mSystemContext.setTheme(DEFAULT_SYSTEM_THEME);
479
480 final Context systemUiContext = activityThread.getSystemUiContext();
481 systemUiContext.setTheme(DEFAULT_SYSTEM_THEME);
482 }
/frameworks/base/core/java/android/app/ActivityThread.java
6444 public static ActivityThread systemMain() {
6445 // The system process on low-memory devices do not get to use hardware
6446 // accelerated drawing, since this can add too much overhead to the
6447 // process.
6448 if (!ActivityManager.isHighEndGfx()) {
6449 ThreadedRenderer.disable(true);
6450 } else {
6451 ThreadedRenderer.enableForegroundTrimming();
6452 }
6453 ActivityThread thread = new ActivityThread();
6454 thread.attach(true);
6455 return thread;
6456 }
/frameworks/base/core/java/android/app/ActivityThread.java
6361 private void attach(boolean system) {
6362 sCurrentActivityThread = this;
6363 mSystemThread = system;
6364 if (!system) {
//如果是个应用,走这里
6402 } else {
6403 // Don't set application object here -- if the system crashes,
6404 // we can't display an alert, we just want to die die die.
6405 android.ddm.DdmHandleAppName.setAppName("system_process",
6406 UserHandle.myUserId());
6407 try {
//对于一个应用进程,该类会优先被创建出来,然后通过他来创建其他组件;另外,它还是系统与组件交互的桥梁,因而通过他可以监听组件和系统之间的各种交互了。
6408 mInstrumentation = new Instrumentation();
//mPackageInfo是一个LoadedApk对象
6409 ContextImpl context = ContextImpl.createAppContext(
6410 this, getSystemContext().mPackageInfo);
6411 mInitialApplication = context.mPackageInfo.makeApplication(true, null);
//Application的onCreate回调,这个Application代表什么呢?
6412 mInitialApplication.onCreate();
6413 } catch (Exception e) {
6414 throw new RuntimeException(
6415 "Unable to instantiate Application():" + e.toString(), e);
6416 }
6417 }
.......
6442 }
Instrumentation:对于一个应用进程,该类会优先被创建出来,然后通过他来创建其他组件;另外,它还是系统与组件交互的桥梁,因而通过他可以监听组件和系统之间的各种交互。
/frameworks/base/core/java/android/app/ActivityThread.java
2192 public ContextImpl getSystemContext() {
2193 synchronized (this) {
2194 if (mSystemContext == null) {
2195 mSystemContext = ContextImpl.createSystemContext(this);
2196 }
2197 return mSystemContext;
2198 }
2199 }
/frameworks/base/core/java/android/app/ContextImpl.java
2215 static ContextImpl createSystemContext(ActivityThread mainThread) {
//创建LoadedApk
2216 LoadedApk packageInfo = new LoadedApk(mainThread);
2217 ContextImpl context = new ContextImpl(null, mainThread, packageInfo, null, null, null, 0,
2218 null);
2219 context.setResources(packageInfo.getResources());
2220 context.mResources.updateConfiguration(context.mResourcesManager.getConfiguration(),
2221 context.mResourcesManager.getDisplayMetrics());
2222 return context;
2223 }
LoadedApk的构造方法如下:
/frameworks/base/core/java/android/app/LoadedApk.java
182 /**
183 * Create information about the system package.
184 * Must call {@link #installSystemApplicationInfo} later.
185 */
186 LoadedApk(ActivityThread activityThread) {
187 mActivityThread = activityThread;
188 mApplicationInfo = new ApplicationInfo();
189 mApplicationInfo.packageName = "android";
190 mPackageName = "android";
......
208 }
LoadedAPK对象使用来保存一个apk文件的信息,这个构造方法中会将使用的包名指定为”android”,而framework-res.apk的包名正是”android”。意味着getSystemContext中创建的mSystemContext对象对应的apk文件是framework-res.apk。framework-res.apk文件位于/system/framework文件夹中,里面有着系统大部分的图片,包括图标,弹出对话框的样式,动作特效,界面布局。
framework-res.apk.png
更多的了解framework-res.apk请移步到ROM美化课堂之 framework-res.apk文件详解,介绍了framework-res.apk文件的具体包含的东西。同时我们也可以对这个framework-res.apk进行资源的修改,达到美化Rom的效果。
//mPackageInfo是一个LoadedApk对象
6409 ContextImpl context = ContextImpl.createAppContext(this, getSystemContext().mPackageInfo);
6411 mInitialApplication = context.mPackageInfo.makeApplication(true, null);
//Application的onCreate回调,这个Application代表什么呢?
6412 mInitialApplication.onCreate();
所以,getSystemContext().mPackageInfo是LoadedApk对象,对应的apk文件就是framework-res.apk。那么由mPackageInfo这个对象创建的mInitialApplication,代表的就是framework-res.apk的Application。
3.1.2、创建SystemServiceManager
System进程中运行的Service很多,有八十多种,每一个服务都要经历创建、启动。所以google搞了一个SystemServiceManager(系统服务管理者)一个人把这些事情都干完了。被SystemServiceManager管理的服务都必须继承com.android.server.SystemService或者该服务中的Lifecycle要继承com.android.server.SystemService。
mSystemServiceManager = new SystemServiceManager(mSystemContext);
比如启动电源服务,只要传PowerManagerService的字节码就可以了,内部帮忙创建并且启动。这种设计确实可以学习一波。
mPowerManagerService = mSystemServiceManager.startService(PowerManagerService.class);
/frameworks/base/services/core/java/com/android/server/SystemServiceManager.java
72 /**
73 * Creates and starts a system service. The class must be a subclass of
74 * {@link com.android.server.SystemService}.
75 *
76 * @param serviceClass A Java class that implements the SystemService interface.
77 * @return The service instance, never null.
78 * @throws RuntimeException if the service fails to start.
79 */
80 @SuppressWarnings("unchecked")
81 public <T extends SystemService> T startService(Class<T> serviceClass) {
82 try {
83 final String name = serviceClass.getName();
....
92 final T service;
93 try {
94 Constructor<T> constructor = serviceClass.getConstructor(Context.class);
95 service = constructor.newInstance(mContext);
96 } catch (InstantiationException ex) {
97 throw new RuntimeException("Failed to create service " + name
98 + ": service could not be instantiated", ex);
99 } catch (IllegalAccessException ex) {
100 throw new RuntimeException("Failed to create service " + name
101 + ": service must have a public constructor with a Context argument", ex);
102 } catch (NoSuchMethodException ex) {
103 throw new RuntimeException("Failed to create service " + name
104 + ": service must have a public constructor with a Context argument", ex);
105 } catch (InvocationTargetException ex) {
106 throw new RuntimeException("Failed to create service " + name
107 + ": service constructor threw an exception", ex);
108 }
109 //启动服务
110 startService(service);
111 return service;
112 } finally {
113 Trace.traceEnd(Trace.TRACE_TAG_SYSTEM_SERVER);
114 }
115 }
/frameworks/base/services/core/java/com/android/server/SystemServiceManager.java
117 public void startService(@NonNull final SystemService service) {
118 // Register it.
119 mServices.add(service);
120 // Start it.
121 long time = System.currentTimeMillis();
122 try {
//回调服务的onStart方法
123 service.onStart();
124 } catch (RuntimeException ex) {
125 throw new RuntimeException("Failed to start service " + service.getClass().getName()
126 + ": onStart threw an exception", ex);
127 }
128 warnIfTooLong(System.currentTimeMillis() - time, service, "onStart");
129 }
当服务创建成功并且启动之后,就会回调这个服务的onStart方法。
/frameworks/base/services/core/java/com/android/server/power/PowerManagerService.java
681 @Override
682 public void onStart() {
//将服务发布出去,交给ServiceManager大管家。
683 publishBinderService(Context.POWER_SERVICE, new BinderService());
684 publishLocalService(PowerManagerInternal.class, new LocalService());
685 //加入Watchdog监控
686 Watchdog.getInstance().addMonitor(this);
687 Watchdog.getInstance().addThread(mHandler);
688 }
/frameworks/base/services/core/java/com/android/server/SystemService.java
202 /**
203 * Publish the service so it is accessible to other services and apps.
204 */
205 protected final void publishBinderService(String name, IBinder service,
206 boolean allowIsolated) {
207 ServiceManager.addService(name, service, allowIsolated);
208 }
经过了上面的过程,一个服务才能说的上被创建完成,对于其他的服务如此,和上面是一样的套路!拿AMS举例。
SystemServer服务管理.png- 创建服务:SystemServiceManager把AMS通过反射创建出来
- 注册服务:首先AMS注册到ServiceManager。AMS所在进程(SystemServer)是客户端,ServiceManager是服务端。
- 获取服务:Client进程使用AMS前,须先向ServiceManager中获取AMS的代理类AMP。该过程。AMP所在进程(应用进程)是客户端,ServiceManager是服务端。
- 使用服务: app进程根据得到的代理类AMP,便可以直接与AMS所在进程交互。该过程,AMP所在进程(应用进程)是客户端,AMS所在进程(SystemServer)是服务端。
区别:
ServiceManager这个类的主要方法有addService(),getService(),listServices()。所以这个类的主要职责是控制用户访问服务,而SystemServiceManager负责服务的创建和启动。
延伸阅读:ServiceManager是在什么时候创建的?
和Zygote进程一样,也是init进程解析servicemanager.rc文件创建的,具体的在本文不深究了。
service servicemanager /system/bin/servicemanager
class core animation
user system
group system readproc
critical
onrestart restart healthd
onrestart restart zygote
onrestart restart audioserver
onrestart restart media
onrestart restart surfaceflinger
onrestart restart inputflinger
onrestart restart drm
onrestart restart cameraserver
writepid /dev/cpuset/system-background/tasks
3.1.3、核心服务的启动
上面介绍System中服务的启动方式,现在就到了启动一个个服务了。系统服务大概分成三类,引导服务,核心服务,其他服务,分别对于三个方法,startBootstrapServices、startCoreServices、startOtherServices。
启动引导服务
/frameworks/base/services/java/com/android/server/SystemServer.java
491 private void startBootstrapServices() {
.......
501 traceBeginAndSlog("StartInstaller");
502 Installer installer = mSystemServiceManager.startService(Installer.class);
503 traceEnd();
504
505 // In some cases after launching an app we need to access device identifiers,
506 // therefore register the device identifier policy before the activity manager.
507 traceBeginAndSlog("DeviceIdentifiersPolicyService");
508 mSystemServiceManager.startService(DeviceIdentifiersPolicyService.class);
509 traceEnd();
510
511 // Activity manager runs the show.
512 traceBeginAndSlog("StartActivityManager");
513 mActivityManagerService = mSystemServiceManager.startService(
514 ActivityManagerService.Lifecycle.class).getService();
515 mActivityManagerService.setSystemServiceManager(mSystemServiceManager);
516 mActivityManagerService.setInstaller(installer);
517 traceEnd();
.......
523 traceBeginAndSlog("StartPowerManager");
524 mPowerManagerService = mSystemServiceManager.startService(PowerManagerService.class);
525 traceEnd();
.......
545 // Manages LEDs and display backlight so we need it to bring up the display.
546 traceBeginAndSlog("StartLightsService");
547 mSystemServiceManager.startService(LightsService.class);
548 traceEnd();
549
550 // Display manager is needed to provide display metrics before package manager
551 // starts up.
552 traceBeginAndSlog("StartDisplayManager");
553 mDisplayManagerService = mSystemServiceManager.startService(DisplayManagerService.class);
554 traceEnd();
555
556 // We need the default display before we can initialize the package manager.
557 traceBeginAndSlog("WaitForDisplay");
558 mSystemServiceManager.startBootPhase(SystemService.PHASE_WAIT_FOR_DEFAULT_DISPLAY);
559 traceEnd();
560
.......
577 mPackageManagerService = PackageManagerService.main(mSystemContext, installer,
578 mFactoryTestMode != FactoryTest.FACTORY_TEST_OFF, mOnlyCore);
579 mFirstBoot = mPackageManagerService.isFirstBoot();
580 mPackageManager = mSystemContext.getPackageManager();
.......
604 traceBeginAndSlog("StartUserManagerService");
605 mSystemServiceManager.startService(UserManagerService.LifeCycle.class);
606 traceEnd();
607
608 // Initialize attribute cache used to cache resources from packages.
609 traceBeginAndSlog("InitAttributerCache");
610 AttributeCache.init(mSystemContext);
611 traceEnd();
612
613 // Set up the Application instance for the system process and get started.
614 traceBeginAndSlog("SetSystemProcess");
615 mActivityManagerService.setSystemProcess();
616 traceEnd();
617
618 // DisplayManagerService needs to setup android.display scheduling related policies
619 // since setSystemProcess() would have overridden policies due to setProcessGroup
620 mDisplayManagerService.setupSchedulerPolicies();
621
622 // Manages Overlay packages
623 traceBeginAndSlog("StartOverlayManagerService");
624 mSystemServiceManager.startService(new OverlayManagerService(mSystemContext, installer));
.......
638 }
大概知道哪些是属于引导服务,比如ActivityManagerService, PowerManagerService, LightsService, DisplayManagerService, PackageManagerService, UserManagerService, Sensor等,WMS是在other中启动的。
/frameworks/base/services/java/com/android/server/SystemServer.java
641 * Starts some essential services that are not tangled up in the bootstrap process.
642 */
643 private void startCoreServices() {
644 // Records errors and logs, for example wtf()
645 traceBeginAndSlog("StartDropBoxManager");
646 mSystemServiceManager.startService(DropBoxManagerService.class);
647 traceEnd();
648
649 traceBeginAndSlog("StartBatteryService");
650 // Tracks the battery level. Requires LightService.
651 mSystemServiceManager.startService(BatteryService.class);
652 traceEnd();
653
654 // Tracks application usage stats.
655 traceBeginAndSlog("StartUsageService");
656 mSystemServiceManager.startService(UsageStatsService.class);
657 mActivityManagerService.setUsageStatsManager(
658 LocalServices.getService(UsageStatsManagerInternal.class));
659 traceEnd();
660
661 // Tracks whether the updatable WebView is in a ready state and watches for update installs.
662 traceBeginAndSlog("StartWebViewUpdateService");
663 mWebViewUpdateService = mSystemServiceManager.startService(WebViewUpdateService.class);
664 traceEnd();
665 }
CoreService中比较少,主要有BatteryService,UsageStatsService,WebViewUpdateService
/**
668 * Starts a miscellaneous grab bag of stuff that has yet to be refactored
669 * and organized.
670 */
671 private void startOtherServices() {
......
722 try {
......
778 // The AccountManager must come before the ContentService
779 traceBeginAndSlog("StartAccountManagerService");
780 mSystemServiceManager.startService(ACCOUNT_SERVICE_CLASS);
781 traceEnd();
782
783 traceBeginAndSlog("StartContentService");
784 mSystemServiceManager.startService(CONTENT_SERVICE_CLASS);
785 traceEnd();
786
787 traceBeginAndSlog("InstallSystemProviders");
788 mActivityManagerService.installSystemProviders();
789 traceEnd();
790
791 traceBeginAndSlog("StartVibratorService");
792 vibrator = new VibratorService(context);
793 ServiceManager.addService("vibrator", vibrator);
794 traceEnd();
......
802
803 traceBeginAndSlog("StartAlarmManagerService");
804 mSystemServiceManager.startService(AlarmManagerService.class);
805 traceEnd();
806
807 traceBeginAndSlog("InitWatchdog");
808 final Watchdog watchdog = Watchdog.getInstance();
809 watchdog.init(context, mActivityManagerService);
810 traceEnd();
811
812 traceBeginAndSlog("StartInputManagerService");
813 inputManager = new InputManagerService(context);
814 traceEnd();
815
816 traceBeginAndSlog("StartWindowManagerService");
817 // WMS needs sensor service ready
818 ConcurrentUtils.waitForFutureNoInterrupt(mSensorServiceStart, START_SENSOR_SERVICE);
819 mSensorServiceStart = null;
820 wm = WindowManagerService.main(context, inputManager,
821 mFactoryTestMode != FactoryTest.FACTORY_TEST_LOW_LEVEL,
822 !mFirstBoot, mOnlyCore, new PhoneWindowManager());
823 ServiceManager.addService(Context.WINDOW_SERVICE, wm);
824 ServiceManager.addService(Context.INPUT_SERVICE, inputManager);
825 traceEnd();
826
827 // Start receiving calls from HIDL services. Start in in a separate thread
828 // because it need to connect to SensorManager. This have to start
829 // after START_SENSOR_SERVICE is done.
830 SystemServerInitThreadPool.get().submit(() -> {
831 traceBeginAndSlog(START_HIDL_SERVICES);
832 startHidlServices();
833 traceEnd();
834 }, START_HIDL_SERVICES);
835
......
1561 // Needed by DevicePolicyManager for initialization
1562 traceBeginAndSlog("StartBootPhaseLockSettingsReady");
1563 mSystemServiceManager.startBootPhase(SystemService.PHASE_LOCK_SETTINGS_READY);
1564 traceEnd();
1565
1566 traceBeginAndSlog("StartBootPhaseSystemServicesReady");
1567 mSystemServiceManager.startBootPhase(SystemService.PHASE_SYSTEM_SERVICES_READY);
1568 traceEnd();
1569
......
}
这里面启动的服务是最多的,不一一列举了,它的最后的一个环节是AMS.systemReady(),紧接着Home就被启动了。
虽然上面的逻辑简单,但是毕竟启动了这么多的服务,为了出了问题可以快速定位,也可以看见打印了不少log,此外不知道是否注意到startBootPhase这个方法,因为Sytem启动被划分成几个阶段,不同的阶段干了不同的事情,前面一个阶段的事情完成了才可以进入下一个阶段。这样在开不了机器,我们首先可以根据phase确定启动到哪一步的工作了。
131 /**
132 * Starts the specified boot phase for all system services that have been started up to
133 * this point.
134 *
135 * @param phase The boot phase to start.
136 */
137 public void startBootPhase(final int phase) {
138 if (phase <= mCurrentPhase) {
139 throw new IllegalArgumentException("Next phase must be larger than previous");
140 }
141 mCurrentPhase = phase;
142
143 Slog.i(TAG, "Starting phase " + mCurrentPhase);
144 try {
145 Trace.traceBegin(Trace.TRACE_TAG_SYSTEM_SERVER, "OnBootPhase " + phase);
146 final int serviceLen = mServices.size();
147 for (int i = 0; i < serviceLen; i++) {
148 final SystemService service = mServices.get(i);
149 long time = System.currentTimeMillis();
150 Trace.traceBegin(Trace.TRACE_TAG_SYSTEM_SERVER, service.getClass().getName());
151 try {
//回调每个Service中的onBootPhase方法
152 service.onBootPhase(mCurrentPhase);
153 } catch (Exception ex) {
154 throw new RuntimeException("Failed to boot service "
155 + service.getClass().getName()
156 + ": onBootPhase threw an exception during phase "
157 + mCurrentPhase, ex);
158 }
159 warnIfTooLong(System.currentTimeMillis() - time, service, "onBootPhase");
160 Trace.traceEnd(Trace.TRACE_TAG_SYSTEM_SERVER);
161 }
162 } finally {
163 Trace.traceEnd(Trace.TRACE_TAG_SYSTEM_SERVER);
164 }
165 }
SystemServer中定义了如下几个阶段。
/frameworks/base/services/java/com/android/server/SystemServer.java
/*
* Boot Phases
*/
public static final int PHASE_WAIT_FOR_DEFAULT_DISPLAY = 100; // maybe should be a dependency?
/**
* After receiving this boot phase, services can obtain lock settings data.
*/
在接收到这个引导阶段之后,服务可以获得锁设置数据。
public static final int PHASE_LOCK_SETTINGS_READY = 480;
/**
* After receiving this boot phase, services can safely call into core system services
* such as the PowerManager or PackageManager.
*/
接收这个启动阶段后,服务可以安全地调用核心系统服务,如PowerManager或器
public static final int PHASE_SYSTEM_SERVICES_READY = 500;
/**
* After receiving this boot phase, services can broadcast Intents.
*/
在接收到这个引导阶段后,服务可以广播意图。
public static final int PHASE_ACTIVITY_MANAGER_READY = 550;
/**
* After receiving this boot phase, services can start/bind to third party apps.
* Apps will be able to make Binder calls into services at this point.
*/
在接收到这个引导阶段之后,服务可以启动/绑定到第三方应用程序,此时应用程序将能够将绑定调用变成服务。
public static final int PHASE_THIRD_PARTY_APPS_CAN_START = 600;
/**
* After receiving this boot phase, services can allow user interaction with the device.
* This phase occurs when boot has completed and the home application has started.
* System services may prefer to listen to this phase rather than registering a
* broadcast receiver for ACTION_BOOT_COMPLETED to reduce overall latency.
*/
在接收到这个引导阶段之后,服务可以允许用户与设备交互。
此阶段发生在启动完成和家庭应用程序启动时。
系统服务可能更喜欢听这个阶段而不是注册的广播接收器,action_boot_completed降低整体延迟。
public static final int PHASE_BOOT_COMPLETED = 1000;
每个阶段做的事情都必须完成,假设某一个阶段执行的任务失败了,就会抛出异常。下面是启动网络服务失败的log。
E/AndroidRuntime( 5899): *** FATAL EXCEPTION IN SYSTEM PROCESS: main
E/AndroidRuntime( 5899): java.lang.RuntimeException: Failed to boot service com.android.server.ethernet.EthernetService: onBootPhase threw an exception during phase 500
E/AndroidRuntime( 5899): at com.android.server.SystemServiceManager.startBootPhase(SystemServiceManager.java:137)
E/AndroidRuntime( 5899): at com.android.server.SystemServer.startOtherServices(SystemServer.java:1071)
E/AndroidRuntime( 5899): at com.android.server.SystemServer.run(SystemServer.java:274)
E/AndroidRuntime( 5899): at com.android.server.SystemServer.main(SystemServer.java:186)
E/AndroidRuntime( 5899): at java.lang.reflect.Method.invoke(Native Method)
E/AndroidRuntime( 5899): at java.lang.reflect.Method.invoke(Method.java:372)
E/AndroidRuntime( 5899): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:909)
E/AndroidRuntime( 5899): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:704)
E/AndroidRuntime( 5899): Caused by: java.lang.IllegalStateException: command '1 interface list' failed with 'null'
E/AndroidRuntime( 5899): at com.android.server.NetworkManagementService.listInterfaces(NetworkManagementService.java:813)
E/AndroidRuntime( 5899): at com.android.server.ethernet.EthernetNetworkFactory.start(EthernetNetworkFactory.java:377)
E/AndroidRuntime( 5899): at com.android.server.ethernet.EthernetServiceImpl.start(EthernetServiceImpl.java:95)
E/AndroidRuntime( 5899): at com.android.server.ethernet.EthernetService.onBootPhase(EthernetService.java:42)
E/AndroidRuntime( 5899): at com.android.server.SystemServiceManager.startBootPhase(SystemServiceManager.java:135)
E/AndroidRuntime( 5899): ... 7 more
E/AndroidRuntime( 5899): Caused by: com.android.server.NativeDaemonConnector$NativeDaemonFailureException: command '1 interface list' failed with 'null'
E/AndroidRuntime( 5899): at com.android.server.NativeDaemonConnector.execute(NativeDaemonConnector.java:416)
E/AndroidRuntime( 5899): at com.android.server.NativeDaemonConnector.executeForList(NativeDaemonConnector.java:367)
E/AndroidRuntime( 5899): at com.android.server.NetworkManagementService.listInterfaces(NetworkManagementService.java:810)
E/AndroidRuntime( 5899): ... 11 more
最后拿一张我们组的大神辉辉老师的图,每个阶段干的主要的事情一目了然。
SystemServer进程的启动流程的大概总结:
-
SystemServer进程由Zygote进程启动
-
SystemServer进程的main入口中,首先会初始化一些系统变量,加载类库,创建Context对象,创建SystemServiceManager对象等,不要混淆SystemServiceManager和ServiceManager。
-
做完上面的事情之后,启动系统中的服务,高达八十多种
-
SystemServer进程将系统服务分为三类:boot服务,core服务、other服务,并逐步启动
-
把握启动阶段,方便定位问题
参考链接:
https://github.com/yipianfengye/androidSource
http://gityuan.com/2016/02/20/android-system-server-2/
网友评论