前引
在android framework或者应用程序开发中所需要的主要API都是以系统服务的形式存在的,例如获取终端的当前位置,读取感应器的数值,拨打电话等,这些基本的功能在framework中都是以服务的形式存在的。
在android系统中,服务是没有UI界面的,它作为一个后台进程,周期性地执行某些特定任务。在开发一些用于处理无需用户干预的数据的后台应用程序时,经常会使用这类android应用程序服务,例如通过网络对数据进行周期性的监控,或接收RSS反馈分析XML数据。在开发android程序时,引入适当的服务,从而开发出更灵活、更健康、更便捷的优秀程序来。
android服务的种类主要有两类,一类是系统服务,它们是由framework提供的;另一类是应用程序服务,它们是应用程序开发者继承并实现Service类后开发出来的。
SystemServer系统服务概要
SystemServer服务进程是android系统Java层框架的核心,它维护这android的核心服务,比如AMS、WMS、PMS等,是android系统中一个非常重要的进程。
init进程、zygote进程和SystemServer进程都非常重要,因为其中任何一个系统死机都会重启。在android系统中,应用程序出现问题,对系统的影响不大,因为应用程序出现问题不会引起系统重启。
init进程、zygote进程和SystemServer进程三者有着密切的联系。
12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758private static boolean startSystemServer(String abiList, String socketName)throws MethodAndArgsCaller, RuntimeException {long capabilities = posixCapabilitiesAsBits(OsConstants.CAP_IPC_LOCK,OsConstants.CAP_KILL,OsConstants.CAP_NET_ADMIN,OsConstants.CAP_NET_BIND_SERVICE,OsConstants.CAP_NET_BROADCAST,OsConstants.CAP_NET_RAW,OsConstants.CAP_SYS_MODULE,OsConstants.CAP_SYS_NICE,OsConstants.CAP_SYS_RESOURCE,OsConstants.CAP_SYS_TIME,OsConstants.CAP_SYS_TTY_CONFIG);if (!SystemProperties.getBoolean(PROPERTY_RUNNING_IN_CONTAINER, false)) {capabilities |= posixCapabilitiesAsBits(OsConstants.CAP_BLOCK_SUSPEND);}String args[] = {"--setuid=1000","--setgid=1000","--setgroups=1001,1002,1003,1004,1005,1006,1007,1008,1009,1010,1018,1021,1032,3001,3002,3003,3006,3007,3009,3010","--capabilities=" + capabilities + "," + capabilities,"--nice-name=system_server","--runtime-args","com.android.server.SystemServer",};ZygoteConnection.Arguments parsedArgs = null;int pid;try {parsedArgs = new ZygoteConnection.Arguments(args);ZygoteConnection.applyDebuggerSystemProperty(parsedArgs);ZygoteConnection.applyInvokeWithSystemProperty(parsedArgs);//pid = Zygote.forkSystemServer(parsedArgs.uid, parsedArgs.gid,parsedArgs.gids,parsedArgs.debugFlags,null,parsedArgs.permittedCapabilities,parsedArgs.effectiveCapabilities);} catch (IllegalArgumentException ex) {throw new RuntimeException(ex);}if (pid == 0) {if (hasSecondZygote(abiList)) {waitForSecondaryZygote(socketName);}handleSystemServerProcess(parsedArgs);}return true;}SystemServer系统服务进程是由zygote进程启动的,从ZygoteInit类的startSystemServer()方法开始,在startSystemServer()方法中调用了两个方法,分别是zygote的forkSystemServer()方法和handleSystemServerProcess()方法,其中,handleSystemServerProcess()是子进程即SystemServer进程的方法,而forkSystemServer()方法是在父进程即zygote进程的方法,handleSystemServerProcess()在android启动过程分析——zygote进程已经分析过了,接下来就来分析forkSystemServer()这个方法。
123456789101112public static int forkSystemServer(int uid, int gid, int[] gids, int debugFlags,int[][] rlimits, long permittedCapabilities, long effectiveCapabilities) {VM_HOOKS.preFork();int pid = nativeForkSystemServer(uid, gid, gids, debugFlags, rlimits, permittedCapabilities, effectiveCapabilities);if (pid == 0) {Trace.setTracingEnabled(true);}VM_HOOKS.postForkCommon();return pid;}forkSystemServer()方法调用了nativeForkSystemServer()方法来做进一步处理,它是一个native的方法。
12345678910111213141516171819202122static jint com_android_internal_os_Zygote_nativeForkSystemServer(JNIEnv* env, jclass, uid_t uid, gid_t gid, jintArray gids,jint debug_flags, jobjectArray rlimits, jlong permittedCapabilities,jlong effectiveCapabilities) {// 传入众多参数来fork一个新的进程pid_t pid = ForkAndSpecializeCommon(env, uid, gid, gids,debug_flags, rlimits,permittedCapabilities, effectiveCapabilities,MOUNT_EXTERNAL_DEFAULT, NULL, NULL, true, NULL,NULL, NULL);if (pid > 0) {ALOGI("System server process %d has been created", pid);gSystemServerPid = pid;int status;if (waitpid(pid, &status, WNOHANG) == pid) {ALOGE("System server process %d has died. Restarting Zygote!", pid);RuntimeAbort(env, __LINE__, "System server process has died. Restarting Zygote!");}}return pid;}在这个jni文件里的com_android_internal_os_Zygote_nativeForkSystemServer函数调用了ForkAndSpecializeCommon()函数来做进一步操作。
1234567891011121314static pid_t ForkAndSpecializeCommon(JNIEnv* env, uid_t uid, gid_t gid, jintArray javaGids,jint debug_flags, jobjectArray javaRlimits,jlong permittedCapabilities, jlong effectiveCapabilities,jint mount_external,jstring java_se_info, jstring java_se_name,bool is_system_server, jintArray fdsToClose,jstring instructionSet, jstring dataDir) {SetSigChldHandler();....pid_t pid = fork();.......return pid;}ForkAndSpecializeCommon()函数调用了两个非常重要的函数,分别是SetSigChldHandler()函数和fork()函数,fork()函数用来创建一个新的子进程,SetSigChldHandler()函数设置了信号处理函数SigChldHandler。
1234567891011static void SetSigChldHandler() {struct sigaction sa;memset(&sa, 0, sizeof(sa));// 当子进程死亡之后,就会产生一个信号,zygote进程收到这个信号之后就会调用SigChldHandler()函数处理。sa.sa_handler = SigChldHandler;int err = sigaction(SIGCHLD, &sa, NULL);if (err < 0) {ALOGW("Error setting SIGCHLD handler: %s", strerror(errno));}}接下来看看SigChldHandler()函数信号处理函数捕获异常的实现。
12345678910111213141516171819202122232425262728293031323334static void SigChldHandler(int /*signal_number*/) {pid_t pid;int status;int saved_errno = errno;while ((pid = waitpid(-1, &status, WNOHANG)) > 0) {if (WIFEXITED(status)) {if (WEXITSTATUS(status)) {ALOGI("Process %d exited cleanly (%d)", pid, WEXITSTATUS(status));}} else if (WIFSIGNALED(status)) {if (WTERMSIG(status) != SIGKILL) {ALOGI("Process %d exited due to signal (%d)", pid, WTERMSIG(status));}if (WCOREDUMP(status)) {ALOGI("Process %d dumped core.", pid);}}// gSystemServerPid表示SystemServer进程的pid,前面已经为它赋过值了。如果SystemServer进程停止工作,首先通过getpid()来获取zygote进程的pid,然后调用kill函数杀死它。即SystemServer停止工作后,zygote自杀,以达到zygote与SystemServer生死与共的目的if (pid == gSystemServerPid) {ALOGE("Exit zygote because system server (%d) has terminated", pid);kill(getpid(), SIGKILL);}}if (pid < 0 && errno != ECHILD) {ALOGW("Zygote SIGCHLD error in waitpid: %s", strerror(errno));}errno = saved_errno;}最后会看一下init进程的main()函数里的死循环,如果它的子进程zygote停止工作,就会去重启子进程。
12345678910111213int main(int argc, char** argv) {...while (true) {if (!waiting_for_exec) {// 执行子进程对应的命令,即执行init.rc文件里配置的命令am.ExecuteOneCommand();// 这个函数用于重启死掉的servicerestart_processes();}...}...}从上面的过程可知,init进程、zygote进程、SystemServer进程紧密相连,任何一个都不能出问题。
SystemServer创建框架核心服务
SystemServer进程在android运行环境中扮演着“神经中枢”的作用,APK应用中能够直接交互的大部分系统服务都在该进程中运行,它创建了很多android系统核心服务,核心服务比如AMS、WMS、PMS等,这些系统服务都是以一个线程的方式存在于SystemServer进程中。
SystemServer进程由zygote进程创建,它是zygote进程的子进程,也是zygote的第一个子进程。当SystemServer启动后,就会进入main()方法,又在它的main()方法中调用run()方法。android系统的核心服务AMS、WMS、PMS等都是在run()方法中进行创建和初始化,当它们创建之后,会通过ServiceManager的add_service()方法把它们加入到ServiceManager中统一管理。
SystemServer创建服务的大致流程如下:
创建系统核心服务过程
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101public final class SystemServer {...public static void main(String[] args) {new SystemServer().run();}public SystemServer() {mFactoryTestMode = FactoryTest.getMode();}private void run() {try {Trace.traceBegin(Trace.TRACE_TAG_SYSTEM_SERVER, "InitBeforeStartServices");if (System.currentTimeMillis() < EARLIEST_SUPPORTED_TIME) {Slog.w(TAG, "System clock is before 1970; setting to 1970.");SystemClock.setCurrentTimeMillis(EARLIEST_SUPPORTED_TIME);}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", "");}Slog.i(TAG, "Entered the Android system server!");EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_SYSTEM_RUN, SystemClock.uptimeMillis());SystemProperties.set("persist.sys.dalvik.vm.lib.2", VMRuntime.getRuntime().vmLibrary());if (SamplingProfilerIntegration.isEnabled()) {SamplingProfilerIntegration.start();mProfilerSnapshotTimer = new Timer();mProfilerSnapshotTimer.schedule(new TimerTask() {public void run() {SamplingProfilerIntegration.writeSnapshot("system_server", null);}}, SNAPSHOT_INTERVAL, SNAPSHOT_INTERVAL);}VMRuntime.getRuntime().clearGrowthLimit();VMRuntime.getRuntime().setTargetHeapUtilization(0.8f);Build.ensureFingerprintProperty();Environment.setUserRequired(true);BaseBundle.setShouldDefuse(true);BinderInternal.disableBackgroundScheduling(true);BinderInternal.setMaxThreads(sMaxBinderThreads);// 设置SystemServer进程线程的优先级,这个优先级非常高android.os.Process.setThreadPriority(android.os.Process.THREAD_PRIORITY_FOREGROUND);android.os.Process.setCanSelfBackground(false);// 创建消息队列Looper.prepareMainLooper();// 加载SystemServer需要的android_servers库System.loadLibrary("android_servers");performPendingShutdown();// 创建系统ContextcreateSystemContext();mSystemServiceManager = new SystemServiceManager(mSystemContext);LocalServices.addService(SystemServiceManager.class, mSystemServiceManager);} finally {Trace.traceEnd(Trace.TRACE_TAG_SYSTEM_SERVER);}try {Trace.traceBegin(Trace.TRACE_TAG_SYSTEM_SERVER, "StartServices");// 接下来这三个方法是创建系统核心服务的实现startBootstrapServices();startCoreServices();startOtherServices();} catch (Throwable ex) {Slog.e("System", "******************************************");Slog.e("System", "************ Failure starting system services", ex);throw ex;} finally {Trace.traceEnd(Trace.TRACE_TAG_SYSTEM_SERVER);}if (StrictMode.conditionallyEnableDebugLogging()) {Slog.i(TAG, "Enabled StrictMode for system server main thread.");}// 进入消息循环Looper.loop();throw new RuntimeException("Main thread loop unexpectedly exited");}...}run()方法调用了三个非常重要的方法来创建和启动核心服务,分别是startBootstrapServices(),startCoreServices(), startOtherServices()。
1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162private void startBootstrapServices() {// installer链接installd,请求installd安装apkInstaller installer = mSystemServiceManager.startService(Installer.class);// 启动ActivityManagerService服务mActivityManagerService = mSystemServiceManager.startService(ActivityManagerService.Lifecycle.class).getService();mActivityManagerService.setSystemServiceManager(mSystemServiceManager);mActivityManagerService.setInstaller(installer);// 启动电源管理服务mPowerManagerService = mSystemServiceManager.startService(PowerManagerService.class);Trace.traceBegin(Trace.TRACE_TAG_SYSTEM_SERVER, "InitPowerManagement");mActivityManagerService.initPowerManagement();Trace.traceEnd(Trace.TRACE_TAG_SYSTEM_SERVER);mSystemServiceManager.startService(LightsService.class);mDisplayManagerService = mSystemServiceManager.startService(DisplayManagerService.class);mSystemServiceManager.startBootPhase(SystemService.PHASE_WAIT_FOR_DEFAULT_DISPLAY);String cryptState = SystemProperties.get("vold.decrypt");if (ENCRYPTING_STATE.equals(cryptState)) {Slog.w(TAG, "Detected encryption in progress - only parsing core apps");mOnlyCore = true;} else if (ENCRYPTED_STATE.equals(cryptState)) {Slog.w(TAG, "Device encrypted - only parsing core apps");mOnlyCore = true;}traceBeginAndSlog("StartPackageManagerService");// 启动PackageManagerService服务,用来安装apk,分配权限mPackageManagerService = PackageManagerService.main(mSystemContext, installer,mFactoryTestMode != FactoryTest.FACTORY_TEST_OFF, mOnlyCore);mFirstBoot = mPackageManagerService.isFirstBoot();mPackageManager = mSystemContext.getPackageManager();Trace.traceEnd(Trace.TRACE_TAG_SYSTEM_SERVER);if (!mOnlyCore) {boolean disableOtaDexopt = SystemProperties.getBoolean("config.disable_otadexopt",false);if (!disableOtaDexopt) {traceBeginAndSlog("StartOtaDexOptService");try {OtaDexoptService.main(mSystemContext, mPackageManagerService);} catch (Throwable e) {reportWtf("starting OtaDexOptService", e);} finally {Trace.traceEnd(Trace.TRACE_TAG_SYSTEM_SERVER);}}}traceBeginAndSlog("StartUserManagerService");mSystemServiceManager.startService(UserManagerService.LifeCycle.class);Trace.traceEnd(Trace.TRACE_TAG_SYSTEM_SERVER);AttributeCache.init(mSystemContext);mActivityManagerService.setSystemProcess();startSensorService();}startBootstrapServices()用来启动一些critical服务,这些服务有着复杂的互相依赖关系,所以把它们放在一个地方初始化。
123456789private void startCoreServices() {mSystemServiceManager.startService(BatteryService.class);mSystemServiceManager.startService(UsageStatsService.class);mActivityManagerService.setUsageStatsManager(LocalServices.getService(UsageStatsManagerInternal.class));mWebViewUpdateService = mSystemServiceManager.startService(WebViewUpdateService.class);}startCoreServices()启动的是一些重要服务,如BatteryService,UsageStatsService等。
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854private void startOtherServices() {final Context context = mSystemContext;VibratorService vibrator = null;IMountService mountService = null;NetworkManagementService networkManagement = null;NetworkStatsService networkStats = null;NetworkPolicyManagerService networkPolicy = null;ConnectivityService connectivity = null;NetworkScoreService networkScore = null;NsdService serviceDiscovery= null;WindowManagerService wm = null;SerialService serial = null;NetworkTimeUpdateService networkTimeUpdater = null;CommonTimeManagementService commonTimeMgmtService = null;InputManagerService inputManager = null;TelephonyRegistry telephonyRegistry = null;ConsumerIrService consumerIr = null;MmsServiceBroker mmsService = null;HardwarePropertiesManagerService hardwarePropertiesService = null;boolean disableStorage = SystemProperties.getBoolean("config.disable_storage", false);boolean disableBluetooth = SystemProperties.getBoolean("config.disable_bluetooth", false);boolean disableLocation = SystemProperties.getBoolean("config.disable_location", false);boolean disableSystemUI = SystemProperties.getBoolean("config.disable_systemui", false);boolean disableNonCoreServices = SystemProperties.getBoolean("config.disable_noncore", false);boolean disableNetwork = SystemProperties.getBoolean("config.disable_network", false);boolean disableNetworkTime = SystemProperties.getBoolean("config.disable_networktime", false);boolean disableRtt = SystemProperties.getBoolean("config.disable_rtt", false);boolean disableMediaProjection = SystemProperties.getBoolean("config.disable_mediaproj",false);boolean disableSerial = SystemProperties.getBoolean("config.disable_serial", false);boolean disableSearchManager = SystemProperties.getBoolean("config.disable_searchmanager",false);boolean disableTrustManager = SystemProperties.getBoolean("config.disable_trustmanager",false);boolean disableTextServices = SystemProperties.getBoolean("config.disable_textservices", false);boolean disableSamplingProfiler = SystemProperties.getBoolean("config.disable_samplingprof",false);boolean isEmulator = SystemProperties.get("ro.kernel.qemu").equals("1");try {Slog.i(TAG, "Reading configuration...");SystemConfig.getInstance();traceBeginAndSlog("StartSchedulingPolicyService");ServiceManager.addService("scheduling_policy", new SchedulingPolicyService());Trace.traceEnd(Trace.TRACE_TAG_SYSTEM_SERVER);mSystemServiceManager.startService(TelecomLoaderService.class);traceBeginAndSlog("StartTelephonyRegistry");telephonyRegistry = new TelephonyRegistry(context);ServiceManager.addService("telephony.registry", telephonyRegistry);Trace.traceEnd(Trace.TRACE_TAG_SYSTEM_SERVER);traceBeginAndSlog("StartEntropyMixer");mEntropyMixer = new EntropyMixer(context);Trace.traceEnd(Trace.TRACE_TAG_SYSTEM_SERVER);mContentResolver = context.getContentResolver();Slog.i(TAG, "Camera Service");mSystemServiceManager.startService(CameraService.class);traceBeginAndSlog("StartAccountManagerService");mSystemServiceManager.startService(ACCOUNT_SERVICE_CLASS);Trace.traceEnd(Trace.TRACE_TAG_SYSTEM_SERVER);traceBeginAndSlog("StartContentService");mSystemServiceManager.startService(CONTENT_SERVICE_CLASS);Trace.traceEnd(Trace.TRACE_TAG_SYSTEM_SERVER);traceBeginAndSlog("InstallSystemProviders");mActivityManagerService.installSystemProviders();Trace.traceEnd(Trace.TRACE_TAG_SYSTEM_SERVER);traceBeginAndSlog("StartVibratorService");vibrator = new VibratorService(context);ServiceManager.addService("vibrator", vibrator);Trace.traceEnd(Trace.TRACE_TAG_SYSTEM_SERVER);traceBeginAndSlog("StartConsumerIrService");consumerIr = new ConsumerIrService(context);ServiceManager.addService(Context.CONSUMER_IR_SERVICE, consumerIr);Trace.traceEnd(Trace.TRACE_TAG_SYSTEM_SERVER);traceBeginAndSlog("StartAlarmManagerService");mSystemServiceManager.startService(AlarmManagerService.class);Trace.traceEnd(Trace.TRACE_TAG_SYSTEM_SERVER);traceBeginAndSlog("InitWatchdog");final Watchdog watchdog = Watchdog.getInstance();watchdog.init(context, mActivityManagerService);Trace.traceEnd(Trace.TRACE_TAG_SYSTEM_SERVER);traceBeginAndSlog("StartInputManagerService");inputManager = new InputManagerService(context);Trace.traceEnd(Trace.TRACE_TAG_SYSTEM_SERVER);traceBeginAndSlog("StartWindowManagerService");wm = WindowManagerService.main(context, inputManager,mFactoryTestMode != FactoryTest.FACTORY_TEST_LOW_LEVEL,!mFirstBoot, mOnlyCore);ServiceManager.addService(Context.WINDOW_SERVICE, wm);ServiceManager.addService(Context.INPUT_SERVICE, inputManager);Trace.traceEnd(Trace.TRACE_TAG_SYSTEM_SERVER);traceBeginAndSlog("StartVrManagerService");mSystemServiceManager.startService(VrManagerService.class);Trace.traceEnd(Trace.TRACE_TAG_SYSTEM_SERVER);mActivityManagerService.setWindowManager(wm);inputManager.setWindowManagerCallbacks(wm.getInputMonitor());inputManager.start();mDisplayManagerService.windowManagerAndInputReady();if (isEmulator) {Slog.i(TAG, "No Bluetooth Service (emulator)");} else if (mFactoryTestMode == FactoryTest.FACTORY_TEST_LOW_LEVEL) {Slog.i(TAG, "No Bluetooth Service (factory test)");} else if (!context.getPackageManager().hasSystemFeature(PackageManager.FEATURE_BLUETOOTH)) {Slog.i(TAG, "No Bluetooth Service (Bluetooth Hardware Not Present)");} else if (disableBluetooth) {Slog.i(TAG, "Bluetooth Service disabled by config");} else {mSystemServiceManager.startService(BluetoothService.class);}traceBeginAndSlog("ConnectivityMetricsLoggerService");mSystemServiceManager.startService(MetricsLoggerService.class);Trace.traceEnd(Trace.TRACE_TAG_SYSTEM_SERVER);traceBeginAndSlog("PinnerService");mSystemServiceManager.startService(PinnerService.class);Trace.traceEnd(Trace.TRACE_TAG_SYSTEM_SERVER);} catch (RuntimeException e) {Slog.e("System", "******************************************");Slog.e("System", "************ Failure starting core service", e);}StatusBarManagerService statusBar = null;INotificationManager notification = null;LocationManagerService location = null;CountryDetectorService countryDetector = null;ILockSettings lockSettings = null;AssetAtlasService atlas = null;MediaRouterService mediaRouter = null;if (mFactoryTestMode != FactoryTest.FACTORY_TEST_LOW_LEVEL) {mSystemServiceManager.startService(InputMethodManagerService.Lifecycle.class);traceBeginAndSlog("StartAccessibilityManagerService");try {ServiceManager.addService(Context.ACCESSIBILITY_SERVICE,new AccessibilityManagerService(context));} catch (Throwable e) {reportWtf("starting Accessibility Manager", e);}Trace.traceEnd(Trace.TRACE_TAG_SYSTEM_SERVER);}try {wm.displayReady();} catch (Throwable e) {reportWtf("making display ready", e);}if (mFactoryTestMode != FactoryTest.FACTORY_TEST_LOW_LEVEL) {if (!disableStorage &&!"0".equals(SystemProperties.get("system_init.startmountservice"))) {try {mSystemServiceManager.startService(MOUNT_SERVICE_CLASS);mountService = IMountService.Stub.asInterface(ServiceManager.getService("mount"));} catch (Throwable e) {reportWtf("starting Mount Service", e);}}}mSystemServiceManager.startService(UiModeManagerService.class);if (!mOnlyCore) {Trace.traceBegin(Trace.TRACE_TAG_SYSTEM_SERVER, "UpdatePackagesIfNeeded");try {mPackageManagerService.updatePackagesIfNeeded();} catch (Throwable e) {reportWtf("update packages", e);}Trace.traceEnd(Trace.TRACE_TAG_SYSTEM_SERVER);}Trace.traceBegin(Trace.TRACE_TAG_SYSTEM_SERVER, "PerformFstrimIfNeeded");try {mPackageManagerService.performFstrimIfNeeded();} catch (Throwable e) {reportWtf("performing fstrim", e);}Trace.traceEnd(Trace.TRACE_TAG_SYSTEM_SERVER);try {ActivityManagerNative.getDefault().showBootMessage(context.getResources().getText(com.android.internal.R.string.android_upgrading_starting_apps),false);} catch (RemoteException e) {}if (mFactoryTestMode != FactoryTest.FACTORY_TEST_LOW_LEVEL) {if (!disableNonCoreServices) {traceBeginAndSlog("StartLockSettingsService");try {mSystemServiceManager.startService(LOCK_SETTINGS_SERVICE_CLASS);lockSettings = ILockSettings.Stub.asInterface(ServiceManager.getService("lock_settings"));} catch (Throwable e) {reportWtf("starting LockSettingsService service", e);}Trace.traceEnd(Trace.TRACE_TAG_SYSTEM_SERVER);if (!SystemProperties.get(PERSISTENT_DATA_BLOCK_PROP).equals("")) {mSystemServiceManager.startService(PersistentDataBlockService.class);}mSystemServiceManager.startService(DeviceIdleController.class);mSystemServiceManager.startService(DevicePolicyManagerService.Lifecycle.class);}if (!disableSystemUI) {traceBeginAndSlog("StartStatusBarManagerService");try {statusBar = new StatusBarManagerService(context, wm);ServiceManager.addService(Context.STATUS_BAR_SERVICE, statusBar);} catch (Throwable e) {reportWtf("starting StatusBarManagerService", e);}Trace.traceEnd(Trace.TRACE_TAG_SYSTEM_SERVER);}if (!disableNonCoreServices) {traceBeginAndSlog("StartClipboardService");try {ServiceManager.addService(Context.CLIPBOARD_SERVICE,new ClipboardService(context));} catch (Throwable e) {reportWtf("starting Clipboard Service", e);}Trace.traceEnd(Trace.TRACE_TAG_SYSTEM_SERVER);}if (!disableNetwork) {traceBeginAndSlog("StartNetworkManagementService");try {networkManagement = NetworkManagementService.create(context);ServiceManager.addService(Context.NETWORKMANAGEMENT_SERVICE, networkManagement);} catch (Throwable e) {reportWtf("starting NetworkManagement Service", e);}Trace.traceEnd(Trace.TRACE_TAG_SYSTEM_SERVER);}if (!disableNonCoreServices && !disableTextServices) {mSystemServiceManager.startService(TextServicesManagerService.Lifecycle.class);}if (!disableNetwork) {traceBeginAndSlog("StartNetworkScoreService");try {networkScore = new NetworkScoreService(context);ServiceManager.addService(Context.NETWORK_SCORE_SERVICE, networkScore);} catch (Throwable e) {reportWtf("starting Network Score Service", e);}Trace.traceEnd(Trace.TRACE_TAG_SYSTEM_SERVER);traceBeginAndSlog("StartNetworkStatsService");try {networkStats = NetworkStatsService.create(context, networkManagement);ServiceManager.addService(Context.NETWORK_STATS_SERVICE, networkStats);} catch (Throwable e) {reportWtf("starting NetworkStats Service", e);}Trace.traceEnd(Trace.TRACE_TAG_SYSTEM_SERVER);traceBeginAndSlog("StartNetworkPolicyManagerService");try {networkPolicy = new NetworkPolicyManagerService(context, mActivityManagerService,(IPowerManager)ServiceManager.getService(Context.POWER_SERVICE),networkStats, networkManagement);ServiceManager.addService(Context.NETWORK_POLICY_SERVICE, networkPolicy);} catch (Throwable e) {reportWtf("starting NetworkPolicy Service", e);}Trace.traceEnd(Trace.TRACE_TAG_SYSTEM_SERVER);if (context.getPackageManager().hasSystemFeature(PackageManager.FEATURE_WIFI_NAN)) {mSystemServiceManager.startService(WIFI_NAN_SERVICE_CLASS);} else {Slog.i(TAG, "No Wi-Fi NAN Service (NAN support Not Present)");}mSystemServiceManager.startService(WIFI_P2P_SERVICE_CLASS);mSystemServiceManager.startService(WIFI_SERVICE_CLASS);mSystemServiceManager.startService("com.android.server.wifi.scanner.WifiScanningService");if (!disableRtt) {mSystemServiceManager.startService("com.android.server.wifi.RttService");}if (mPackageManager.hasSystemFeature(PackageManager.FEATURE_ETHERNET) ||mPackageManager.hasSystemFeature(PackageManager.FEATURE_USB_HOST)) {mSystemServiceManager.startService(ETHERNET_SERVICE_CLASS);}traceBeginAndSlog("StartConnectivityService");try {connectivity = new ConnectivityService(context, networkManagement, networkStats, networkPolicy);ServiceManager.addService(Context.CONNECTIVITY_SERVICE, connectivity);networkStats.bindConnectivityManager(connectivity);networkPolicy.bindConnectivityManager(connectivity);} catch (Throwable e) {reportWtf("starting Connectivity Service", e);}Trace.traceEnd(Trace.TRACE_TAG_SYSTEM_SERVER);traceBeginAndSlog("StartNsdService");try {serviceDiscovery = NsdService.create(context);ServiceManager.addService(Context.NSD_SERVICE, serviceDiscovery);} catch (Throwable e) {reportWtf("starting Service Discovery Service", e);}Trace.traceEnd(Trace.TRACE_TAG_SYSTEM_SERVER);}if (!disableNonCoreServices) {traceBeginAndSlog("StartUpdateLockService");try {ServiceManager.addService(Context.UPDATE_LOCK_SERVICE,new UpdateLockService(context));} catch (Throwable e) {reportWtf("starting UpdateLockService", e);}Trace.traceEnd(Trace.TRACE_TAG_SYSTEM_SERVER);}if (!disableNonCoreServices) {mSystemServiceManager.startService(RecoverySystemService.class);}if (mountService != null && !mOnlyCore) {Trace.traceBegin(Trace.TRACE_TAG_SYSTEM_SERVER, "WaitForAsecScan");try {mountService.waitForAsecScan();} catch (RemoteException ignored) {}Trace.traceEnd(Trace.TRACE_TAG_SYSTEM_SERVER);}mSystemServiceManager.startService(NotificationManagerService.class);notification = INotificationManager.Stub.asInterface(ServiceManager.getService(Context.NOTIFICATION_SERVICE));networkPolicy.bindNotificationManager(notification);mSystemServiceManager.startService(DeviceStorageMonitorService.class);if (!disableLocation) {traceBeginAndSlog("StartLocationManagerService");try {location = new LocationManagerService(context);ServiceManager.addService(Context.LOCATION_SERVICE, location);} catch (Throwable e) {reportWtf("starting Location Manager", e);}Trace.traceEnd(Trace.TRACE_TAG_SYSTEM_SERVER);traceBeginAndSlog("StartCountryDetectorService");try {countryDetector = new CountryDetectorService(context);ServiceManager.addService(Context.COUNTRY_DETECTOR, countryDetector);} catch (Throwable e) {reportWtf("starting Country Detector", e);}Trace.traceEnd(Trace.TRACE_TAG_SYSTEM_SERVER);}if (!disableNonCoreServices && !disableSearchManager) {traceBeginAndSlog("StartSearchManagerService");try {mSystemServiceManager.startService(SEARCH_MANAGER_SERVICE_CLASS);} catch (Throwable e) {reportWtf("starting Search Service", e);}Trace.traceEnd(Trace.TRACE_TAG_SYSTEM_SERVER);}mSystemServiceManager.startService(DropBoxManagerService.class);if (!disableNonCoreServices && context.getResources().getBoolean(R.bool.config_enableWallpaperService)) {traceBeginAndSlog("StartWallpaperManagerService");mSystemServiceManager.startService(WALLPAPER_SERVICE_CLASS);Trace.traceEnd(Trace.TRACE_TAG_SYSTEM_SERVER);}traceBeginAndSlog("StartAudioService");mSystemServiceManager.startService(AudioService.Lifecycle.class);Trace.traceEnd(Trace.TRACE_TAG_SYSTEM_SERVER);if (!disableNonCoreServices) {mSystemServiceManager.startService(DockObserver.class);if (context.getPackageManager().hasSystemFeature(PackageManager.FEATURE_WATCH)) {mSystemServiceManager.startService(THERMAL_OBSERVER_CLASS);}}traceBeginAndSlog("StartWiredAccessoryManager");try {inputManager.setWiredAccessoryCallbacks(new WiredAccessoryManager(context, inputManager));} catch (Throwable e) {reportWtf("starting WiredAccessoryManager", e);}Trace.traceEnd(Trace.TRACE_TAG_SYSTEM_SERVER);if (!disableNonCoreServices) {if (mPackageManager.hasSystemFeature(PackageManager.FEATURE_MIDI)) {mSystemServiceManager.startService(MIDI_SERVICE_CLASS);}if (mPackageManager.hasSystemFeature(PackageManager.FEATURE_USB_HOST)|| mPackageManager.hasSystemFeature(PackageManager.FEATURE_USB_ACCESSORY)) {Trace.traceBegin(Trace.TRACE_TAG_SYSTEM_SERVER, "StartUsbService");mSystemServiceManager.startService(USB_SERVICE_CLASS);Trace.traceEnd(Trace.TRACE_TAG_SYSTEM_SERVER);}if (!disableSerial) {traceBeginAndSlog("StartSerialService");try {serial = new SerialService(context);ServiceManager.addService(Context.SERIAL_SERVICE, serial);} catch (Throwable e) {Slog.e(TAG, "Failure starting SerialService", e);}Trace.traceEnd(Trace.TRACE_TAG_SYSTEM_SERVER);}Trace.traceBegin(Trace.TRACE_TAG_SYSTEM_SERVER,"StartHardwarePropertiesManagerService");try {hardwarePropertiesService = new HardwarePropertiesManagerService(context);ServiceManager.addService(Context.HARDWARE_PROPERTIES_SERVICE,hardwarePropertiesService);} catch (Throwable e) {Slog.e(TAG, "Failure starting HardwarePropertiesManagerService", e);}Trace.traceEnd(Trace.TRACE_TAG_SYSTEM_SERVER);}mSystemServiceManager.startService(TwilightService.class);mSystemServiceManager.startService(JobSchedulerService.class);mSystemServiceManager.startService(SoundTriggerService.class);if (!disableNonCoreServices) {if (mPackageManager.hasSystemFeature(PackageManager.FEATURE_BACKUP)) {mSystemServiceManager.startService(BACKUP_MANAGER_SERVICE_CLASS);}if (mPackageManager.hasSystemFeature(PackageManager.FEATURE_APP_WIDGETS)|| context.getResources().getBoolean(R.bool.config_enableAppWidgetService)) {mSystemServiceManager.startService(APPWIDGET_SERVICE_CLASS);}if (mPackageManager.hasSystemFeature(PackageManager.FEATURE_VOICE_RECOGNIZERS)) {mSystemServiceManager.startService(VOICE_RECOGNITION_MANAGER_SERVICE_CLASS);}if (GestureLauncherService.isGestureLauncherEnabled(context.getResources())) {Slog.i(TAG, "Gesture Launcher Service");mSystemServiceManager.startService(GestureLauncherService.class);}mSystemServiceManager.startService(SensorNotificationService.class);mSystemServiceManager.startService(ContextHubSystemService.class);}traceBeginAndSlog("StartDiskStatsService");try {ServiceManager.addService("diskstats", new DiskStatsService(context));} catch (Throwable e) {reportWtf("starting DiskStats Service", e);}Trace.traceEnd(Trace.TRACE_TAG_SYSTEM_SERVER);if (!disableSamplingProfiler) {traceBeginAndSlog("StartSamplingProfilerService");try {ServiceManager.addService("samplingprofiler",new SamplingProfilerService(context));} catch (Throwable e) {reportWtf("starting SamplingProfiler Service", e);}Trace.traceEnd(Trace.TRACE_TAG_SYSTEM_SERVER);}if (!disableNetwork && !disableNetworkTime) {traceBeginAndSlog("StartNetworkTimeUpdateService");try {networkTimeUpdater = new NetworkTimeUpdateService(context);ServiceManager.addService("network_time_update_service", networkTimeUpdater);} catch (Throwable e) {reportWtf("starting NetworkTimeUpdate service", e);}Trace.traceEnd(Trace.TRACE_TAG_SYSTEM_SERVER);}traceBeginAndSlog("StartCommonTimeManagementService");try {commonTimeMgmtService = new CommonTimeManagementService(context);ServiceManager.addService("commontime_management", commonTimeMgmtService);} catch (Throwable e) {reportWtf("starting CommonTimeManagementService service", e);}Trace.traceEnd(Trace.TRACE_TAG_SYSTEM_SERVER);if (!disableNetwork) {traceBeginAndSlog("CertBlacklister");try {CertBlacklister blacklister = new CertBlacklister(context);} catch (Throwable e) {reportWtf("starting CertBlacklister", e);}Trace.traceEnd(Trace.TRACE_TAG_SYSTEM_SERVER);}if (!disableNonCoreServices) {mSystemServiceManager.startService(DreamManagerService.class);}if (!disableNonCoreServices && ZygoteInit.PRELOAD_RESOURCES) {traceBeginAndSlog("StartAssetAtlasService");try {atlas = new AssetAtlasService(context);ServiceManager.addService(AssetAtlasService.ASSET_ATLAS_SERVICE, atlas);} catch (Throwable e) {reportWtf("starting AssetAtlasService", e);}Trace.traceEnd(Trace.TRACE_TAG_SYSTEM_SERVER);}if (!disableNonCoreServices) {ServiceManager.addService(GraphicsStatsService.GRAPHICS_STATS_SERVICE,new GraphicsStatsService(context));}if (mPackageManager.hasSystemFeature(PackageManager.FEATURE_PRINTING)) {mSystemServiceManager.startService(PRINT_MANAGER_SERVICE_CLASS);}mSystemServiceManager.startService(RestrictionsManagerService.class);mSystemServiceManager.startService(MediaSessionService.class);if (mPackageManager.hasSystemFeature(PackageManager.FEATURE_HDMI_CEC)) {mSystemServiceManager.startService(HdmiControlService.class);}if (mPackageManager.hasSystemFeature(PackageManager.FEATURE_LIVE_TV)) {mSystemServiceManager.startService(TvInputManagerService.class);}if (mPackageManager.hasSystemFeature(PackageManager.FEATURE_PICTURE_IN_PICTURE)) {mSystemServiceManager.startService(MediaResourceMonitorService.class);}if (mPackageManager.hasSystemFeature(PackageManager.FEATURE_LEANBACK)) {mSystemServiceManager.startService(TvRemoteService.class);}if (!disableNonCoreServices) {traceBeginAndSlog("StartMediaRouterService");try {mediaRouter = new MediaRouterService(context);ServiceManager.addService(Context.MEDIA_ROUTER_SERVICE, mediaRouter);} catch (Throwable e) {reportWtf("starting MediaRouterService", e);}Trace.traceEnd(Trace.TRACE_TAG_SYSTEM_SERVER);if (!disableTrustManager) {mSystemServiceManager.startService(TrustManagerService.class);}if (mPackageManager.hasSystemFeature(PackageManager.FEATURE_FINGERPRINT)) {mSystemServiceManager.startService(FingerprintService.class);}traceBeginAndSlog("StartBackgroundDexOptService");try {BackgroundDexOptService.schedule(context);} catch (Throwable e) {reportWtf("starting BackgroundDexOptService", e);}Trace.traceEnd(Trace.TRACE_TAG_SYSTEM_SERVER);}mSystemServiceManager.startService(ShortcutService.Lifecycle.class);mSystemServiceManager.startService(LauncherAppsService.class);}if (!disableNonCoreServices && !disableMediaProjection) {mSystemServiceManager.startService(MediaProjectionManagerService.class);}if (context.getPackageManager().hasSystemFeature(PackageManager.FEATURE_WATCH)) {mSystemServiceManager.startService(WEAR_BLUETOOTH_SERVICE_CLASS);}final boolean safeMode = wm.detectSafeMode();if (safeMode) {mActivityManagerService.enterSafeMode();VMRuntime.getRuntime().disableJitCompilation();} else {VMRuntime.getRuntime().startJitCompilation();}mmsService = mSystemServiceManager.startService(MmsServiceBroker.class);Trace.traceBegin(Trace.TRACE_TAG_SYSTEM_SERVER, "MakeVibratorServiceReady");try {vibrator.systemReady();} catch (Throwable e) {reportWtf("making Vibrator Service ready", e);}Trace.traceEnd(Trace.TRACE_TAG_SYSTEM_SERVER);Trace.traceBegin(Trace.TRACE_TAG_SYSTEM_SERVER, "MakeLockSettingsServiceReady");if (lockSettings != null) {try {lockSettings.systemReady();} catch (Throwable e) {reportWtf("making Lock Settings Service ready", e);}}Trace.traceEnd(Trace.TRACE_TAG_SYSTEM_SERVER);mSystemServiceManager.startBootPhase(SystemService.PHASE_LOCK_SETTINGS_READY);mSystemServiceManager.startBootPhase(SystemService.PHASE_SYSTEM_SERVICES_READY);Trace.traceBegin(Trace.TRACE_TAG_SYSTEM_SERVER, "MakeWindowManagerServiceReady");try {wm.systemReady();} catch (Throwable e) {reportWtf("making Window Manager Service ready", e);}Trace.traceEnd(Trace.TRACE_TAG_SYSTEM_SERVER);if (safeMode) {mActivityManagerService.showSafeModeOverlay();}Configuration config = wm.computeNewConfiguration();DisplayMetrics metrics = new DisplayMetrics();WindowManager w = (WindowManager)context.getSystemService(Context.WINDOW_SERVICE);w.getDefaultDisplay().getMetrics(metrics);context.getResources().updateConfiguration(config, metrics);final Theme systemTheme = context.getTheme();if (systemTheme.getChangingConfigurations() != 0) {systemTheme.rebase();}Trace.traceBegin(Trace.TRACE_TAG_SYSTEM_SERVER, "MakePowerManagerServiceReady");try {mPowerManagerService.systemReady(mActivityManagerService.getAppOpsService());Trace.traceEnd(Trace.TRACE_TAG_SYSTEM_SERVER);} catch (Throwable e) {reportWtf("making Power Manager Service ready", e);}Trace.traceEnd(Trace.TRACE_TAG_SYSTEM_SERVER);Trace.traceBegin(Trace.TRACE_TAG_SYSTEM_SERVER, "MakePackageManagerServiceReady");try {mPackageManagerService.systemReady();} catch (Throwable e) {reportWtf("making Package Manager Service ready", e);}Trace.traceEnd(Trace.TRACE_TAG_SYSTEM_SERVER);Trace.traceBegin(Trace.TRACE_TAG_SYSTEM_SERVER, "MakeDisplayManagerServiceReady");try {mDisplayManagerService.systemReady(safeMode, mOnlyCore);} catch (Throwable e) {reportWtf("making Display Manager Service ready", e);}Trace.traceEnd(Trace.TRACE_TAG_SYSTEM_SERVER);final NetworkManagementService networkManagementF = networkManagement;final NetworkStatsService networkStatsF = networkStats;final NetworkPolicyManagerService networkPolicyF = networkPolicy;final ConnectivityService connectivityF = connectivity;final NetworkScoreService networkScoreF = networkScore;final LocationManagerService locationF = location;final CountryDetectorService countryDetectorF = countryDetector;final NetworkTimeUpdateService networkTimeUpdaterF = networkTimeUpdater;final CommonTimeManagementService commonTimeMgmtServiceF = commonTimeMgmtService;final AssetAtlasService atlasF = atlas;final InputManagerService inputManagerF = inputManager;final TelephonyRegistry telephonyRegistryF = telephonyRegistry;final MediaRouterService mediaRouterF = mediaRouter;final MmsServiceBroker mmsServiceF = mmsService;mActivityManagerService.systemReady(new Runnable() {public void run() {Slog.i(TAG, "Making services ready");mSystemServiceManager.startBootPhase(SystemService.PHASE_ACTIVITY_MANAGER_READY);Trace.traceBegin(Trace.TRACE_TAG_SYSTEM_SERVER, "PhaseActivityManagerReady");Trace.traceBegin(Trace.TRACE_TAG_SYSTEM_SERVER, "StartObservingNativeCrashes");try {mActivityManagerService.startObservingNativeCrashes();} catch (Throwable e) {reportWtf("observing native crashes", e);}Trace.traceEnd(Trace.TRACE_TAG_SYSTEM_SERVER);if (!mOnlyCore) {Slog.i(TAG, "WebViewFactory preparation");Trace.traceBegin(Trace.TRACE_TAG_SYSTEM_SERVER, "WebViewFactoryPreparation");mWebViewUpdateService.prepareWebViewInSystemServer();Trace.traceEnd(Trace.TRACE_TAG_SYSTEM_SERVER);}Trace.traceBegin(Trace.TRACE_TAG_SYSTEM_SERVER, "StartSystemUI");try {startSystemUi(context);} catch (Throwable e) {reportWtf("starting System UI", e);}Trace.traceEnd(Trace.TRACE_TAG_SYSTEM_SERVER);Trace.traceBegin(Trace.TRACE_TAG_SYSTEM_SERVER, "MakeNetworkScoreReady");try {if (networkScoreF != null) networkScoreF.systemReady();} catch (Throwable e) {reportWtf("making Network Score Service ready", e);}Trace.traceEnd(Trace.TRACE_TAG_SYSTEM_SERVER);Trace.traceBegin(Trace.TRACE_TAG_SYSTEM_SERVER, "MakeNetworkManagementServiceReady");try {if (networkManagementF != null) networkManagementF.systemReady();} catch (Throwable e) {reportWtf("making Network Managment Service ready", e);}Trace.traceEnd(Trace.TRACE_TAG_SYSTEM_SERVER);Trace.traceBegin(Trace.TRACE_TAG_SYSTEM_SERVER, "MakeNetworkStatsServiceReady");try {if (networkStatsF != null) networkStatsF.systemReady();} catch (Throwable e) {reportWtf("making Network Stats Service ready", e);}Trace.traceEnd(Trace.TRACE_TAG_SYSTEM_SERVER);Trace.traceBegin(Trace.TRACE_TAG_SYSTEM_SERVER, "MakeNetworkPolicyServiceReady");try {if (networkPolicyF != null) networkPolicyF.systemReady();} catch (Throwable e) {reportWtf("making Network Policy Service ready", e);}Trace.traceEnd(Trace.TRACE_TAG_SYSTEM_SERVER);Trace.traceBegin(Trace.TRACE_TAG_SYSTEM_SERVER, "MakeConnectivityServiceReady");try {if (connectivityF != null) connectivityF.systemReady();} catch (Throwable e) {reportWtf("making Connectivity Service ready", e);}Trace.traceEnd(Trace.TRACE_TAG_SYSTEM_SERVER);Watchdog.getInstance().start();Trace.traceEnd(Trace.TRACE_TAG_SYSTEM_SERVER);Trace.traceBegin(Trace.TRACE_TAG_SYSTEM_SERVER, "PhaseThirdPartyAppsCanStart");mSystemServiceManager.startBootPhase(SystemService.PHASE_THIRD_PARTY_APPS_CAN_START);try {if (locationF != null) locationF.systemRunning();} catch (Throwable e) {reportWtf("Notifying Location Service running", e);}try {if (countryDetectorF != null) countryDetectorF.systemRunning();} catch (Throwable e) {reportWtf("Notifying CountryDetectorService running", e);}try {if (networkTimeUpdaterF != null) networkTimeUpdaterF.systemRunning();} catch (Throwable e) {reportWtf("Notifying NetworkTimeService running", e);}try {if (commonTimeMgmtServiceF != null) {commonTimeMgmtServiceF.systemRunning();}} catch (Throwable e) {reportWtf("Notifying CommonTimeManagementService running", e);}try {if (atlasF != null) atlasF.systemRunning();} catch (Throwable e) {reportWtf("Notifying AssetAtlasService running", e);}try {if (inputManagerF != null) inputManagerF.systemRunning();} catch (Throwable e) {reportWtf("Notifying InputManagerService running", e);}try {if (telephonyRegistryF != null) telephonyRegistryF.systemRunning();} catch (Throwable e) {reportWtf("Notifying TelephonyRegistry running", e);}try {if (mediaRouterF != null) mediaRouterF.systemRunning();} catch (Throwable e) {reportWtf("Notifying MediaRouterService running", e);}try {if (mmsServiceF != null) mmsServiceF.systemRunning();} catch (Throwable e) {reportWtf("Notifying MmsService running", e);}try {if (networkScoreF != null) networkScoreF.systemRunning();} catch (Throwable e) {reportWtf("Notifying NetworkScoreService running", e);}Trace.traceEnd(Trace.TRACE_TAG_SYSTEM_SERVER);}});}startOtherServices()方法很长,看看就好。
ActivityManagerService的创建和初始化
ActivityManagerService(AMS)是android系统中一个非常重要的服务,它主要管理四大组件和进程内存的调度,它在SystemServer里的创建和启动,主要调用了一下几个方法:
- 12mActivityManagerService = mSystemServiceManager.startService(ActivityManagerService.Lifecycle.class).getService();
- 1mActivityManagerService.setSystemProcess();
- 1mActivityManagerService.systemReady();
变量mSystemServiceManager是一个SystemServiceManager类型的对象,首先调用它的startService()方法创建AMS对象,接着调用这个AMS对象的setSystemProcess()方法来初始化AMS中的一些重要工作,最后调用systemReady()方法来判断AM是否启动和初始化成功。在android系统中,很多的核心服务都会提供systemReady()方法来判断它相应的服务是否启动和初始化成功,因为有些核心服务如果没有启动或者初始化失败,会严重影响系统的使用,如AMS,WMS等核心服务。而有些服务没有提供这个方法,比如MountService,因为MountService主要管理Sdcard这部分,如果这个服务没有启动或者初始化失败,只会影响sdcard,对系统的影响不是很大。
首先来看一下startService()方法创建AMS对象。
12345678910111213141516171819202122232425262728293031323334353637383940414243public <T extends SystemService> T startService(Class<T> serviceClass) {try {// 首先获得name为ActivityManagerService.Lifecyclefinal String name = serviceClass.getName();Slog.i(TAG, "Starting " + name);Trace.traceBegin(Trace.TRACE_TAG_SYSTEM_SERVER, "StartService " + name);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);// 通过构造方法的反射创建了一个实例,这里是Lifecycle对象service = constructor.newInstance(mContext);} catch (InstantiationException ex) {throw new RuntimeException("Failed to create service " + name+ ": service could not be instantiated", ex);} catch (IllegalAccessException ex) {throw new RuntimeException("Failed to create service " + name+ ": service must have a public constructor with a Context argument", ex);} catch (NoSuchMethodException ex) {throw new RuntimeException("Failed to create service " + name+ ": service must have a public constructor with a Context argument", ex);} catch (InvocationTargetException ex) {throw new RuntimeException("Failed to create service " + name+ ": service constructor threw an exception", ex);}mServices.add(service);try {service.onStart();} catch (RuntimeException ex) {throw new RuntimeException("Failed to start service " + name+ ": onStart threw an exception", ex);}return service;} finally {Trace.traceEnd(Trace.TRACE_TAG_SYSTEM_SERVER);}}SystemServiceManager类的startService()方法创建了一个Lifecycle实例,然后返回,而在SystemServer类里通过这个返回的实例调用getService()方法就获得AMS对象。Lifecycle是AMS的内部类,在创建这个实例的时候,会调用它的构造方法。
1234567891011121314151617public static final class Lifecycle extends SystemService {private final ActivityManagerService mService;public Lifecycle(Context context) {super(context);mService = new ActivityManagerService(context);}public void onStart() {mService.start();}public ActivityManagerService getService() {return mService;}}Lifecycle的构造方法创建了一个AMS实例对象,而它的getService()方法会返回构造方法里创建的这个AMS实例对象。
回到前面,接下来调用ActivityManagerService的setSystemProcess()方法。
12345678910111213141516171819202122232425262728293031323334353637public void setSystemProcess() {try {// 添加AMS到ServiceManager中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));ServiceManager.addService("dbinfo", new DbBinder(this));if (MONITOR_CPU_USAGE) {ServiceManager.addService("cpuinfo", new CpuBinder(this));}ServiceManager.addService("permission", new PermissionController(this));ServiceManager.addService("processinfo", new ProcessInfoService(this));ApplicationInfo info = mContext.getPackageManager().getApplicationInfo("android", STOCK_PM_FLAGS | MATCH_SYSTEM_ONLY);mSystemThread.installSystemApplicationInfo(info, getClass().getClassLoader());synchronized (this) {ProcessRecord app = newProcessRecordLocked(info, info.processName, false, 0);app.persistent = true;app.pid = MY_PID;app.maxAdj = ProcessList.SYSTEM_ADJ;app.makeActive(mSystemThread.getApplicationThread(), mProcessStats);synchronized (mPidsSelfLocked) {mPidsSelfLocked.put(app.pid, app);}// 调整进程的调度优先级updateLruProcessLocked(app, false, null);// 调整OOM_Adj值updateOomAdjLocked();}} catch (PackageManager.NameNotFoundException e) {throw new RuntimeException("Unable to find android system package", e);}}最后,继续调用ActivityManagerService的systemReady()方法。
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158public void systemReady(final Runnable goingCallback) {synchronized(this) {if (mSystemReady) {if (goingCallback != null) {goingCallback.run();}return;}mLocalDeviceIdleController= LocalServices.getService(DeviceIdleController.LocalService.class);mUserController.onSystemReady();mRecentTasks.onSystemReadyLocked();mAppOpsService.systemReady();mSystemReady = true;}// 从mPidsSelfLocked中找到那些优先于AMS启动的进程,即manifest里声明persistent为true的那些进程ArrayList<ProcessRecord> procsToKill = null;synchronized(mPidsSelfLocked) {for (int i=mPidsSelfLocked.size()-1; i>=0; i--) {ProcessRecord proc = mPidsSelfLocked.valueAt(i);if (!isAllowedWhileBooting(proc.info)){if (procsToKill == null) {procsToKill = new ArrayList<ProcessRecord>();}procsToKill.add(proc);}}}// 找到这些进程之后,通过removeProcessLocked()方法把它关闭synchronized(this) {if (procsToKill != null) {for (int i=procsToKill.size()-1; i>=0; i--) {ProcessRecord proc = procsToKill.get(i);Slog.i(TAG, "Removing system update proc: " + proc);removeProcessLocked(proc, true, false, "system update done");}}mProcessesReady = true;}Slog.i(TAG, "System now ready");EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_AMS_READY,SystemClock.uptimeMillis());synchronized(this) {if (mFactoryTest == FactoryTest.FACTORY_TEST_LOW_LEVEL) {ResolveInfo ri = mContext.getPackageManager().resolveActivity(new Intent(Intent.ACTION_FACTORY_TEST),STOCK_PM_FLAGS);CharSequence errorMsg = null;if (ri != null) {ActivityInfo ai = ri.activityInfo;ApplicationInfo app = ai.applicationInfo;if ((app.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {mTopAction = Intent.ACTION_FACTORY_TEST;mTopData = null;mTopComponent = new ComponentName(app.packageName,ai.name);} else {errorMsg = mContext.getResources().getText(com.android.internal.R.string.factorytest_not_system);}} else {errorMsg = mContext.getResources().getText(com.android.internal.R.string.factorytest_no_action);}if (errorMsg != null) {mTopAction = null;mTopData = null;mTopComponent = null;Message msg = Message.obtain();msg.what = SHOW_FACTORY_ERROR_UI_MSG;msg.getData().putCharSequence("msg", errorMsg);mUiHandler.sendMessage(msg);}}}// 查询settings数据库,因为AMS会用到一些settings数据库里的数据retrieveSettings();final int currentUserId;synchronized (this) {currentUserId = mUserController.getCurrentUserIdLocked();readGrantedUriPermissionsLocked();}if (goingCallback != null) goingCallback.run();mBatteryStatsService.noteEvent(BatteryStats.HistoryItem.EVENT_USER_RUNNING_START,Integer.toString(currentUserId), currentUserId);mBatteryStatsService.noteEvent(BatteryStats.HistoryItem.EVENT_USER_FOREGROUND_START,Integer.toString(currentUserId), currentUserId);mSystemServiceManager.startUser(currentUserId);synchronized (this) {startPersistentApps(PackageManager.MATCH_DIRECT_BOOT_AWARE);mBooting = true;if (UserManager.isSplitSystemUser()) {ComponentName cName = new ComponentName(mContext, SystemUserHomeActivity.class);try {AppGlobals.getPackageManager().setComponentEnabledSetting(cName,PackageManager.COMPONENT_ENABLED_STATE_ENABLED, 0,UserHandle.USER_SYSTEM);} catch (RemoteException e) {throw e.rethrowAsRuntimeException();}}// 启动LauncherstartHomeActivityLocked(currentUserId, "systemReady");try {if (AppGlobals.getPackageManager().hasSystemUidErrors()) {Slog.e(TAG, "UIDs on the system are inconsistent, you need to wipe your"+ " data partition or your device will be unstable.");mUiHandler.obtainMessage(SHOW_UID_ERROR_UI_MSG).sendToTarget();}} catch (RemoteException e) {}if (!Build.isBuildConsistent()) {Slog.e(TAG, "Build fingerprint is not consistent, warning user");mUiHandler.obtainMessage(SHOW_FINGERPRINT_ERROR_UI_MSG).sendToTarget();}long ident = Binder.clearCallingIdentity();try {Intent intent = new Intent(Intent.ACTION_USER_STARTED);intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY| Intent.FLAG_RECEIVER_FOREGROUND);intent.putExtra(Intent.EXTRA_USER_HANDLE, currentUserId);broadcastIntentLocked(null, null, intent,null, null, 0, null, null, null, AppOpsManager.OP_NONE,null, false, false, MY_PID, Process.SYSTEM_UID,currentUserId);intent = new Intent(Intent.ACTION_USER_STARTING);intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);intent.putExtra(Intent.EXTRA_USER_HANDLE, currentUserId);broadcastIntentLocked(null, null, intent,null, new IIntentReceiver.Stub() {public void performReceive(Intent intent, int resultCode, String data,Bundle extras, boolean ordered, boolean sticky, int sendingUser)throws RemoteException {}}, 0, null, null,new String[] {INTERACT_ACROSS_USERS}, AppOpsManager.OP_NONE,null, true, false, MY_PID, Process.SYSTEM_UID, UserHandle.USER_ALL);} catch (Throwable t) {Slog.wtf(TAG, "Failed sending first user broadcasts", t);} finally {Binder.restoreCallingIdentity(ident);}mStackSupervisor.resumeFocusedStackTopActivityLocked();mUserController.sendUserSwitchBroadcastsLocked(-1, currentUserId);}}至此,ActivityManagerService的创建和它的核心方法的调用分析完毕。