System Server进程启动过程源码分析

来源:互联网 发布:公司网址和域名是什么 编辑:程序博客网 时间:2024/05/29 11:00

SystemServer进程名称为System_Server,在Zygote进程启动过程源码分析一文中介绍了zygote进程通过startSystemServer函数调用将启动一个SystemServer子进程:

[java] view plaincopy
  1. private static boolean startSystemServer()  
  2.             throws MethodAndArgsCaller, RuntimeException {  
  3.         /* Hardcoded command line to start the system server */  
  4.         String args[] = {  
  5.             "--setuid=1000",  
  6.             "--setgid=1000",  
  7.             "--setgroups=1001,1002,1003,1004,1005,1006,1007,1008,1009,1010,1018,3001,3002,3003",  
  8.             "--capabilities=130104352,130104352",  
  9.             "--runtime-init",  
  10.             "--nice-name=system_server",  
  11.             "com.android.server.SystemServer",  
  12.         };  
  13.         ZygoteConnection.Arguments parsedArgs = null;  
  14.   
  15.         int pid;  
  16.   
  17.         try {  
  18.             parsedArgs = new ZygoteConnection.Arguments(args);  
  19.   
  20.             /* 
  21.              * Enable debugging of the system process if *either* the command line flags 
  22.              * indicate it should be debuggable or the ro.debuggable system property 
  23.              * is set to "1" 
  24.              */  
  25.             int debugFlags = parsedArgs.debugFlags;  
  26.             if ("1".equals(SystemProperties.get("ro.debuggable")))  
  27.                 debugFlags |= Zygote.DEBUG_ENABLE_DEBUGGER;  
  28.   
  29.             /* Request to fork the system server process */  
  30.             pid = Zygote.forkSystemServer(  
  31.                     parsedArgs.uid, parsedArgs.gid,  
  32.                     parsedArgs.gids, debugFlags, null,  
  33.                     parsedArgs.permittedCapabilities,  
  34.                     parsedArgs.effectiveCapabilities);  
  35.         } catch (IllegalArgumentException ex) {  
  36.             throw new RuntimeException(ex);  
  37.         }  
  38.   
  39.         /* For child process */  
  40.         if (pid == 0) {  
  41.             handleSystemServerProcess(parsedArgs);  
  42.         }  
  43.   
  44.         return true;  
  45.     }  
创建该进程的核心是通过调用forkSystemServer函数来完成的,这是应该native函数

[java] view plaincopy
  1. native public static int forkSystemServer(int uid, int gid,  
  2.         int[] gids, int debugFlags, int[][] rlimits,  
  3.         long permittedCapabilities, long effectiveCapabilities);  
[java] view plaincopy
  1. const DalvikNativeMethod dvm_dalvik_system_Zygote[] =   
  2. {  
  3.     { "fork",              "()I",Dalvik_dalvik_system_Zygote_fork },  
  4.     { "forkAndSpecialize""(II[II[[I)I",Dalvik_dalvik_system_Zygote_forkAndSpecialize },  
  5.     { "forkSystemServer",  "(II[II[[IJJ)I",Dalvik_dalvik_system_Zygote_forkSystemServer },  
  6.     { NULL, NULL, NULL },  
  7. };  

在dalvik_system_Zygote.c文件中实现:

[java] view plaincopy
  1. static void Dalvik_dalvik_system_Zygote_forkSystemServer(  
  2.         const u4* args, JValue* pResult)  
  3. {  
  4.     pid_t pid;  
  5.     //根据参数,fork一个子进程  
  6.     pid = forkAndSpecializeCommon(args, true);  
  7.   
  8.     /* The zygote process checks whether the child process has died or not. */  
  9.     if (pid > 0) {  
  10.         int status;  
  11.   
  12.         LOGI("System server process %d has been created", pid);  
  13.         gDvm.systemServerPid = pid; //保存System Server的进程ID  
  14.         /* There is a slight window that the system server process has crashed 
  15.          * but it went unnoticed because we haven't published its pid yet. So 
  16.          * we recheck here just to make sure that all is well. 
  17.          *检查创建的子进程是否退出 
  18.          */  
  19.         if (waitpid(pid, &status, WNOHANG) == pid) {  
  20.             LOGE("System server process %d has died. Restarting Zygote!", pid);  
  21.             /* FIXME: reboot instead of restarting android */  
  22.             /* kill(getpid(), SIGKILL); */  
  23.             //如果SystemServer进程退出,zygote将杀死自身进程  
  24.             reboot(RB_AUTOBOOT);  
  25.         }  
  26.     }  
  27.     RETURN_INT(pid);  
  28. }  

新创建的进程会执行handleSystemServerProcess函数,来完成自己的使命。

[java] view plaincopy
  1. private static void handleSystemServerProcess(  
  2.             ZygoteConnection.Arguments parsedArgs)  
  3.             throws ZygoteInit.MethodAndArgsCaller {  
  4.         //关闭从zygote继承下来的socket  
  5.         closeServerSocket();  
  6.   
  7.         /* 
  8.          *传递剩余参数给SystemServer并调用zygoteInit函数 
  9.          * "--nice-name=system_server com.android.server.SystemServer" 
  10.          */  
  11.         RuntimeInit.zygoteInit(parsedArgs.remainingArgs);  
  12.         /* should never reach here */  
  13.     }  
由于由Zygote进程创建的子进程会继承Zygote进程在前面创建的Socket文件描述符,而这里的子进程又不会用到它,因此,这里就调用closeServerSocket函数来关闭它。这个函数接着调用RuntimeInit.zygoteInit函数来进一步执行启动SystemServer组件的操作。
RuntimeInit.java  

[java] view plaincopy
  1. public static final void zygoteInit(String[] argv)  
  2.             throws ZygoteInit.MethodAndArgsCaller {  
  3.         //设置系统输出流  
  4.         System.setOut(new AndroidPrintStream(Log.INFO, "System.out"));  
  5.         System.setErr(new AndroidPrintStream(Log.WARN, "System.err"));  
  6.         //常规初始化  
  7.         commonInit();  
  8.         //执行一个Binder进程间通信机制的初始化工作,这个工作完成之后,这个进程中的Binder对象就可以方便地进行进程间通信了  
  9.         zygoteInitNative();  
  10.   
  11.         int curArg = 0;  
  12.         //argv = ["--nice-name=system_server, com.android.server.SystemServer"]  
  13.         for ( ; curArg < argv.length; curArg++) {  
  14.             String arg = argv[curArg];  
  15.   
  16.             if (arg.equals("--")) {  
  17.                 curArg++;  
  18.                 break;  
  19.             } else if (!arg.startsWith("--")) {  
  20.                 break;  
  21.             } else if (arg.startsWith("--nice-name=")) {  
  22.                 String niceName = arg.substring(arg.indexOf('=') + 1);  
  23.                 Process.setArgV0(niceName);//设置进程名称为system_server  
  24.             }  
  25.         }  
  26.   
  27.         if (curArg == argv.length) {  
  28.             Slog.e(TAG, "Missing classname argument to RuntimeInit!");  
  29.             // let the process exit  
  30.             return;  
  31.         }  
  32.   
  33.         // Remaining arguments are passed to the start class's static main  
  34.         String startClass = argv[curArg++];//startClass =“com.android.server.SystemServer”  
  35.         String[] startArgs = new String[argv.length - curArg];  
  36.   
  37.         System.arraycopy(argv, curArg, startArgs, 0, startArgs.length);  
  38.         //调用SystemServer类中的main函数  
  39.         invokeStaticMain(startClass, startArgs);  
  40.     }  

这个函数会执行两个操作:

一个是调用zygoteInitNative函数来执行一个Binder进程间通信机制的初始化工作;

一个是调用com.android.server.SystemServer类的main函数;

[java] view plaincopy
  1. public static final native void zygoteInitNative();  
[java] view plaincopy
  1. static JNINativeMethod gMethods[] =   
  2. {  
  3.     { "finishInit""()V",(void*) com_android_internal_os_RuntimeInit_finishInit },  
  4.     { "zygoteInitNative""()V",(void*) com_android_internal_os_RuntimeInit_zygoteInit },  
  5.     { "isComputerOn""()I",(void*) com_android_internal_os_RuntimeInit_isComputerOn },  
  6.     { "turnComputerOn""()V",(void*) com_android_internal_os_RuntimeInit_turnComputerOn },      
  7.     { "getQwertyKeyboard""()I",(void*) com_android_internal_os_RuntimeInit_getQwertyKeyboard },  
  8. };  
[java] view plaincopy
  1. static void com_android_internal_os_RuntimeInit_zygoteInit(JNIEnv* env, jobject clazz)  
  2. {  
  3.     gCurRuntime->onZygoteInit();  
  4. }  
由于SystemServer 是由zygote fork出来,因此它也拥有zygote进程中的gCurRuntime,也就是AppRuntime

[java] view plaincopy
  1. virtual void onZygoteInit()  
  2. {  
  3.    sp<ProcessState> proc = ProcessState::self();  
  4.    if (proc->supportsProcesses()) {  
  5.       LOGV("App process: starting thread pool.\n");  
  6.       proc->startThreadPool(); //启动一个线程,用于binder通信  
  7.    }         
  8. }  
因此通过调用zygoteInitNative函数,将建立Binder通信。

调用invokeStaticMain函数:

[java] view plaincopy
  1. private static void invokeStaticMain(String className, String[] argv)  
  2.             throws ZygoteInit.MethodAndArgsCaller {  
  3.   
  4.         // We want to be fairly aggressive about heap utilization, to avoid  
  5.         // holding on to a lot of memory that isn't needed.  
  6.         VMRuntime.getRuntime().setTargetHeapUtilization(0.75f);  
  7.   
  8.         Class<?> cl;  
  9.   
  10.         try {  
  11.             //com.android.server.SystemServer,通过反射加载SystemServer类  
  12.             cl = Class.forName(className);  
  13.         } catch (ClassNotFoundException ex) {  
  14.             throw new RuntimeException("Missing class when invoking static main " + className,ex);  
  15.         }  
  16.   
  17.         Method m;  
  18.         try {  
  19.             m = cl.getMethod("main"new Class[] { String[].class });//获取SystemServer类的main方法  
  20.         } catch (NoSuchMethodException ex) {  
  21.             throw new RuntimeException("Missing static main on " + className, ex);  
  22.         } catch (SecurityException ex) {  
  23.             throw new RuntimeException("Problem getting static main on " + className, ex);  
  24.         }  
  25.   
  26.         int modifiers = m.getModifiers();  
  27.         if (! (Modifier.isStatic(modifiers) && Modifier.isPublic(modifiers))) {  
  28.             throw new RuntimeException("Main method is not public and static on " + className);  
  29.         }  
  30.   
  31.         /* 
  32.          * This throw gets caught in ZygoteInit.main(), which responds 
  33.          * by invoking the exception's run() method. This arrangement 
  34.          * clears up all the stack frames that were required in setting 
  35.          * up the process. 抛出MethodAndArgsCaller异常,并在ZygoteInit.main()函数里铺货 
  36.          */  
  37.         throw new ZygoteInit.MethodAndArgsCaller(m, argv);  
  38.     }  
抛出的MethodAndArgsCaller异常会在ZygoteInit.java 中的main函数捕获:

[java] view plaincopy
  1. public static void main(String argv[]) {  
  2.         try {  
  3.             VMRuntime.getRuntime().setMinimumHeapSize(5 * 1024 * 1024);  
  4.   
  5.             // Start profiling the zygote initialization.  
  6.             SamplingProfilerIntegration.start();  
  7.   
  8.             registerZygoteSocket();  
  9.             EventLog.writeEvent(LOG_BOOT_PROGRESS_PRELOAD_START,  
  10.                 SystemClock.uptimeMillis());  
  11.             preloadClasses();  
  12.             //cacheRegisterMaps();  
  13.             preloadResources();  
  14.             EventLog.writeEvent(LOG_BOOT_PROGRESS_PRELOAD_END,  
  15.                 SystemClock.uptimeMillis());  
  16.   
  17.             // Finish profiling the zygote initialization.  
  18.             SamplingProfilerIntegration.writeZygoteSnapshot();  
  19.   
  20.             // Do an initial gc to clean up after startup  
  21.             gc();  
  22.   
  23.             // If requested, start system server directly from Zygote  
  24.             if (argv.length != 2) {  
  25.                 throw new RuntimeException(argv[0] + USAGE_STRING);  
  26.             }  
  27.   
  28.             if (argv[1].equals("true")) {  
  29.                 startSystemServer();  
  30.             } else if (!argv[1].equals("false")) {  
  31.                 throw new RuntimeException(argv[0] + USAGE_STRING);  
  32.             }  
  33.   
  34.             Log.i(TAG, "Accepting command socket connections");  
  35.   
  36.             if (ZYGOTE_FORK_MODE) {  
  37.                 runForkMode();  
  38.             } else {  
  39.                 runSelectLoopMode();  
  40.             }  
  41.   
  42.             closeServerSocket();  
  43.         } catch (MethodAndArgsCaller caller) {  
  44.             caller.run();  
  45.         } catch (RuntimeException ex) {  
  46.             Log.e(TAG, "Zygote died with exception", ex);  
  47.             closeServerSocket();  
  48.             throw ex;  
  49.         }  
  50.     }  
[java] view plaincopy
  1. public void run() {  
  2.     try {  
  3.        //mMethod 是SystemServer类的main方法        
  4.        mMethod.invoke(nullnew Object[] { mArgs });  
  5.     } catch (IllegalAccessException ex) {  
  6.         throw new RuntimeException(ex);  
  7.     } catch (InvocationTargetException ex) {  
  8.         Throwable cause = ex.getCause();  
  9.         if (cause instanceof RuntimeException) {  
  10.             throw (RuntimeException) cause;  
  11.         } else if (cause instanceof Error) {  
  12.             throw (Error) cause;  
  13.         }  
  14.         throw new RuntimeException(ex);  
  15.     }  
  16. }  
SystemServer.java

[java] view plaincopy
  1. public static void main(String[] args) {  
  2.         if (System.currentTimeMillis() < EARLIEST_SUPPORTED_TIME) {  
  3.             // If a device's clock is before 1970 (before 0), a lot of  
  4.             // APIs crash dealing with negative numbers, notably  
  5.             // java.io.File#setLastModified, so instead we fake it and  
  6.             // hope that time from cell towers or NTP fixes it  
  7.             // shortly.  
  8.             Slog.w(TAG, "System clock is before 1970; setting to 1970.");  
  9.             SystemClock.setCurrentTimeMillis(EARLIEST_SUPPORTED_TIME);  
  10.         }  
  11.   
  12.         if (SamplingProfilerIntegration.isEnabled()) {  
  13.             //启动性能统计  
  14.             SamplingProfilerIntegration.start();  
  15.             timer = new Timer();  
  16.             timer.schedule(new TimerTask() {  
  17.                 @Override  
  18.                 public void run() {  
  19.             //输出性能统计结果  
  20.                     SamplingProfilerIntegration.writeSnapshot("system_server");  
  21.                 }  
  22.             }, SNAPSHOT_INTERVAL, SNAPSHOT_INTERVAL);  
  23.         }  
  24.   
  25.         // The system server has to run all of the time, so it needs to be  
  26.         // as efficient as possible with its memory usage.  
  27.         VMRuntime.getRuntime().setTargetHeapUtilization(0.8f);  
  28.         //加载android_servers.so库  
  29.         System.loadLibrary("android_servers");  
  30.         init1(args);  
  31.     }  

抛出MethodAndArgsCaller异常会导致com.android.server.SystemServer类的main函数被调用。为什么采用这种方式来调用呢,读者可以自行研究!

[java] view plaincopy
  1. native public static void init1(String[] args);  
com_android_server_SystemServer.cpp

[java] view plaincopy
  1. static JNINativeMethod gMethods[] = {  
  2.     /* name, signature, funcPtr */  
  3.     { "init1""([Ljava/lang/String;)V", (void*) android_server_SystemServer_init1 },  
  4. };  

[cpp] view plaincopy
  1. extern "C" int system_init();  
  2.   
  3. static void android_server_SystemServer_init1(JNIEnv* env, jobject clazz)  
  4. {  
  5.     system_init();  
  6. }  
System_init.cpp

[java] view plaincopy
  1. extern "C" status_t system_init()  
  2. {  
  3.     LOGI("Entered system_init()");  
  4.       
  5.     sp<ProcessState> proc(ProcessState::self());  
  6.     //获取Service manager的远程调用接口  
  7.     sp<IServiceManager> sm = defaultServiceManager();  
  8.     LOGI("ServiceManager: %p\n", sm.get());  
  9.       
  10.     sp<GrimReaper> grim = new GrimReaper();  
  11.     sm->asBinder()->linkToDeath(grim, grim.get(), 0);  
  12.       
  13.     char propBuf[PROPERTY_VALUE_MAX];  
  14.     property_get("system_init.startsurfaceflinger", propBuf, "1");  
  15.     //在SystemServer中启动各种服务  
  16.     if (strcmp(propBuf, "1") == 0) {  
  17.         // Start the SurfaceFlinger  
  18.         SurfaceFlinger::instantiate();  
  19.     }  
  20.   
  21.     // Start the sensor service  
  22.     SensorService::instantiate();  
  23.   
  24.     // On the simulator, audioflinger et al don't get started the  
  25.     // same way as on the device, and we need to start them here  
  26.     if (!proc->supportsProcesses()) {  
  27.   
  28.         // Start the AudioFlinger  
  29.         AudioFlinger::instantiate();  
  30.   
  31.         // Start the media playback service  
  32.         MediaPlayerService::instantiate();  
  33.   
  34.         // Start the camera service  
  35.         CameraService::instantiate();  
  36.   
  37.         // Start the audio policy service  
  38.         AudioPolicyService::instantiate();  
  39.     }  
  40.   
  41.     // And now start the Android runtime.  We have to do this bit  
  42.     // of nastiness because the Android runtime initialization requires  
  43.     // some of the core system services to already be started.  
  44.     // All other servers should just start the Android runtime at  
  45.     // the beginning of their processes's main(), before calling  
  46.     // the init function.  
  47.     LOGI("System server: starting Android runtime.\n");  
  48.       
  49.     AndroidRuntime* runtime = AndroidRuntime::getRuntime();  
  50.   
  51.     LOGI("System server: starting Android services.\n");  
  52.     //调用SystemServer.java 类中的init2函数  
  53.     runtime->callStatic("com/android/server/SystemServer""init2");  
  54.           
  55.     // If running in our own process, just go into the thread  
  56.     // pool.  Otherwise, call the initialization finished  
  57.     // func to let this process continue its initilization.  
  58.     //将SystemServer进程的主线程加入Binder通信中  
  59.     if (proc->supportsProcesses()) {  
  60.         LOGI("System server: entering thread pool.\n");  
  61.         ProcessState::self()->startThreadPool();  
  62.         IPCThreadState::self()->joinThreadPool();  
  63.         LOGI("System server: exiting thread pool.\n");  
  64.     }  
  65.     return NO_ERROR;  
  66. }  
这里的main函数首先会执行JNI方法init1,然后init1会调用这里的init2函数,在init2函数里面,会创建一个ServerThread线程对象来执行一些系统关键服务的启动操作:

[java] view plaincopy
  1. public static final void init2() {  
  2.         Slog.i(TAG, "Entered the Android system server!");  
  3.         Thread thr = new ServerThread();  
  4.         thr.setName("android.server.ServerThread");  
  5.     //启动一个线程  
  6.         thr.start();  
  7. }  
init2只是简单创建一个线程,在该ServerThread线程中启动各种系统服务:

[java] view plaincopy
  1. @Override  
  2. public void run() {  
  3.     EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_SYSTEM_RUN,  
  4.         SystemClock.uptimeMillis());  
  5.   
  6.     Looper.prepare();  
  7.   
  8.     android.os.Process.setThreadPriority(  
  9.             android.os.Process.THREAD_PRIORITY_FOREGROUND);  
  10.   
  11.     BinderInternal.disableBackgroundScheduling(true);  
  12.     android.os.Process.setCanSelfBackground(false);  
  13.   
  14.     // Check whether we failed to shut down last time we tried.  
  15.     {  
  16.         final String shutdownAction = SystemProperties.get(  
  17.                 ShutdownThread.SHUTDOWN_ACTION_PROPERTY, "");  
  18.         if (shutdownAction != null && shutdownAction.length() > 0) {  
  19.             boolean reboot = (shutdownAction.charAt(0) == '1');  
  20.   
  21.             final String reason;  
  22.             if (shutdownAction.length() > 1) {  
  23.                 reason = shutdownAction.substring(1, shutdownAction.length());  
  24.             } else {  
  25.                 reason = null;  
  26.             }  
  27.   
  28.             ShutdownThread.rebootOrShutdown(reboot, reason);  
  29.         }  
  30.     }  
  31.   
  32.     String factoryTestStr = SystemProperties.get("ro.factorytest");  
  33.     int factoryTest = "".equals(factoryTestStr) ? SystemServer.FACTORY_TEST_OFF  
  34.             : Integer.parseInt(factoryTestStr);  
  35.   
  36.     LightsService lights = null;  
  37.     PowerManagerService power = null;  
  38.     BatteryService battery = null;  
  39.     ConnectivityService connectivity = null;  
  40.     IPackageManager pm = null;  
  41.     Context context = null;  
  42.     WindowManagerService wm = null;  
  43.     BluetoothService bluetooth = null;  
  44.     BluetoothA2dpService bluetoothA2dp = null;  
  45.     HeadsetObserver headset = null;  
  46.     DockObserver dock = null;  
  47.     UsbService usb = null;  
  48.     UiModeManagerService uiMode = null;  
  49.     RecognitionManagerService recognition = null;  
  50.     ThrottleService throttle = null;  
  51.   
  52.     // Critical services...  
  53.     try {  
  54.         Slog.i(TAG, "Entropy Service");  
  55.         ServiceManager.addService("entropy"new EntropyService());  
  56.   
  57.         Slog.i(TAG, "Power Manager");  
  58.         power = new PowerManagerService();  
  59.         ServiceManager.addService(Context.POWER_SERVICE, power);  
  60.   
  61.         Slog.i(TAG, "Activity Manager");  
  62.         context = ActivityManagerService.main(factoryTest);  
  63.   
  64.         Slog.i(TAG, "Telephony Registry");  
  65.         if (PhoneFactory.isMultiSim()) {  
  66.             TelephonyRegistry[] telephonyRegistry = new TelephonyRegistry[PhoneFactory.getPhoneCount()];  
  67.             for (int i = 0; i < PhoneFactory.getPhoneCount(); i++) {  
  68.                 telephonyRegistry[i] = new TelephonyRegistry(context, i);  
  69.                 ServiceManager.addService(PhoneFactory.getServiceName("telephony.registry", i),  
  70.                         telephonyRegistry[i]);  
  71.             }  
  72.             ServiceManager.addService("telephony.registry",  
  73.                     new CompositeTelephonyRegistry(context, telephonyRegistry));  
  74.         } else {  
  75.             ServiceManager.addService("telephony.registry",  
  76.                     new TelephonyRegistry(context, 0));  
  77.         }  
  78.   
  79.         AttributeCache.init(context);  
  80.   
  81.         Slog.i(TAG, "Package Manager");  
  82.         pm = PackageManagerService.main(context,  
  83.                 factoryTest != SystemServer.FACTORY_TEST_OFF);  
  84.   
  85.         ActivityManagerService.setSystemProcess();  
  86.   
  87.         mContentResolver = context.getContentResolver();  
  88.   
  89.         // The AccountManager must come before the ContentService  
  90.         try {  
  91.             Slog.i(TAG, "Account Manager");  
  92.             ServiceManager.addService(Context.ACCOUNT_SERVICE,  
  93.                     new AccountManagerService(context));  
  94.         } catch (Throwable e) {  
  95.             Slog.e(TAG, "Failure starting Account Manager", e);  
  96.         }  
  97.   
  98.         Slog.i(TAG, "Content Manager");  
  99.         ContentService.main(context,  
  100.                 factoryTest == SystemServer.FACTORY_TEST_LOW_LEVEL);  
  101.   
  102.         Slog.i(TAG, "System Content Providers");  
  103.         ActivityManagerService.installSystemProviders();  
  104.   
  105.         Slog.i(TAG, "Battery Service");  
  106.         battery = new BatteryService(context);  
  107.         ServiceManager.addService("battery", battery);  
  108.   
  109.         Slog.i(TAG, "Lights Service");  
  110.         lights = new LightsService(context);  
  111.   
  112.         Slog.i(TAG, "Vibrator Service");  
  113.         ServiceManager.addService("vibrator"new VibratorService(context));  
  114.   
  115.         // only initialize the power service after we have started the  
  116.         // lights service, content providers and the battery service.  
  117.         power.init(context, lights, ActivityManagerService.getDefault(), battery);  
  118.   
  119.         Slog.i(TAG, "Alarm Manager");  
  120.         AlarmManagerService alarm = new AlarmManagerService(context);  
  121.         ServiceManager.addService(Context.ALARM_SERVICE, alarm);  
  122.   
  123.         Slog.i(TAG, "Init Watchdog");  
  124.         Watchdog.getInstance().init(context, battery, power, alarm,  
  125.                 ActivityManagerService.self());  
  126.   
  127.         Slog.i(TAG, "Window Manager");  
  128.         wm = WindowManagerService.main(context, power,  
  129.                 factoryTest != SystemServer.FACTORY_TEST_LOW_LEVEL);  
  130.         ServiceManager.addService(Context.WINDOW_SERVICE, wm);  
  131.   
  132.         ((ActivityManagerService)ServiceManager.getService("activity"))  
  133.                 .setWindowManager(wm);  
  134.   
  135.         // Skip Bluetooth if we have an emulator kernel  
  136.         // TODO: Use a more reliable check to see if this product should  
  137.         // support Bluetooth - see bug 988521  
  138.         if (SystemProperties.get("ro.kernel.qemu").equals("1")) {  
  139.             Slog.i(TAG, "Registering null Bluetooth Service (emulator)");  
  140.             ServiceManager.addService(BluetoothAdapter.BLUETOOTH_SERVICE, null);  
  141.         } else if (factoryTest == SystemServer.FACTORY_TEST_LOW_LEVEL) {  
  142.             Slog.i(TAG, "Registering null Bluetooth Service (factory test)");  
  143.             ServiceManager.addService(BluetoothAdapter.BLUETOOTH_SERVICE, null);  
  144.         } else {  
  145.             Slog.i(TAG, "Bluetooth Service");  
  146.             bluetooth = new BluetoothService(context);  
  147.             ServiceManager.addService(BluetoothAdapter.BLUETOOTH_SERVICE, bluetooth);  
  148.             bluetooth.initAfterRegistration();  
  149.             bluetoothA2dp = new BluetoothA2dpService(context, bluetooth);  
  150.             ServiceManager.addService(BluetoothA2dpService.BLUETOOTH_A2DP_SERVICE,  
  151.                                       bluetoothA2dp);  
  152.   
  153.             int bluetoothOn = Settings.Secure.getInt(mContentResolver,  
  154.                 Settings.Secure.BLUETOOTH_ON, 0);  
  155.             if (bluetoothOn > 0) {  
  156.                 bluetooth.enable();  
  157.             }  
  158.         }  
  159.   
  160.     } catch (RuntimeException e) {  
  161.         Slog.e("System""Failure starting core service", e);  
  162.     }  
  163.   
  164.     DevicePolicyManagerService devicePolicy = null;  
  165.     StatusBarManagerService statusBar = null;  
  166.     InputMethodManagerService imm = null;  
  167.     AppWidgetService appWidget = null;  
  168.     NotificationManagerService notification = null;  
  169.     WallpaperManagerService wallpaper = null;  
  170.     LocationManagerService location = null;  
  171.   
  172.     if (factoryTest != SystemServer.FACTORY_TEST_LOW_LEVEL) {  
  173.         try {  
  174.             Slog.i(TAG, "Device Policy");  
  175.             devicePolicy = new DevicePolicyManagerService(context);  
  176.             ServiceManager.addService(Context.DEVICE_POLICY_SERVICE, devicePolicy);  
  177.         } catch (Throwable e) {  
  178.             Slog.e(TAG, "Failure starting DevicePolicyService", e);  
  179.         }  
  180.   
  181.         try {  
  182.             Slog.i(TAG, "Status Bar");  
  183.             statusBar = new StatusBarManagerService(context);  
  184.             ServiceManager.addService(Context.STATUS_BAR_SERVICE, statusBar);  
  185.         } catch (Throwable e) {  
  186.             Slog.e(TAG, "Failure starting StatusBarManagerService", e);  
  187.         }  
  188.   
  189.         try {  
  190.             Slog.i(TAG, "Clipboard Service");  
  191.             ServiceManager.addService(Context.CLIPBOARD_SERVICE,  
  192.                     new ClipboardService(context));  
  193.         } catch (Throwable e) {  
  194.             Slog.e(TAG, "Failure starting Clipboard Service", e);  
  195.         }  
  196.   
  197.         try {  
  198.             Slog.i(TAG, "Input Method Service");  
  199.             imm = new InputMethodManagerService(context, statusBar);  
  200.             ServiceManager.addService(Context.INPUT_METHOD_SERVICE, imm);  
  201.         } catch (Throwable e) {  
  202.             Slog.e(TAG, "Failure starting Input Manager Service", e);  
  203.         }  
  204.   
  205.         try {  
  206.             Slog.i(TAG, "NetStat Service");  
  207.             ServiceManager.addService("netstat"new NetStatService(context));  
  208.         } catch (Throwable e) {  
  209.             Slog.e(TAG, "Failure starting NetStat Service", e);  
  210.         }  
  211.   
  212.         try {  
  213.             Slog.i(TAG, "NetworkManagement Service");  
  214.             ServiceManager.addService(  
  215.                     Context.NETWORKMANAGEMENT_SERVICE,  
  216.                     NetworkManagementService.create(context));  
  217.         } catch (Throwable e) {  
  218.             Slog.e(TAG, "Failure starting NetworkManagement Service", e);  
  219.         }  
  220.   
  221.         try {  
  222.             Slog.i(TAG, "Connectivity Service");  
  223.             connectivity = ConnectivityService.getInstance(context);  
  224.             ServiceManager.addService(Context.CONNECTIVITY_SERVICE, connectivity);  
  225.         } catch (Throwable e) {  
  226.             Slog.e(TAG, "Failure starting Connectivity Service", e);  
  227.         }  
  228.   
  229.         try {  
  230.             Slog.i(TAG, "Throttle Service");  
  231.             throttle = new ThrottleService(context);  
  232.             ServiceManager.addService(  
  233.                     Context.THROTTLE_SERVICE, throttle);  
  234.         } catch (Throwable e) {  
  235.             Slog.e(TAG, "Failure starting ThrottleService", e);  
  236.         }  
  237.   
  238.         try {  
  239.           Slog.i(TAG, "Accessibility Manager");  
  240.           ServiceManager.addService(Context.ACCESSIBILITY_SERVICE,  
  241.                   new AccessibilityManagerService(context));  
  242.         } catch (Throwable e) {  
  243.           Slog.e(TAG, "Failure starting Accessibility Manager", e);  
  244.         }  
  245.   
  246.         try {  
  247.             /* 
  248.              * NotificationManagerService is dependant on MountService, 
  249.              * (for media / usb notifications) so we must start MountService first. 
  250.              */  
  251.             Slog.i(TAG, "Mount Service");  
  252.             ServiceManager.addService("mount"new MountService(context));  
  253.         } catch (Throwable e) {  
  254.             Slog.e(TAG, "Failure starting Mount Service", e);  
  255.         }  
  256.   
  257.         try {  
  258.             Slog.i(TAG, "Notification Manager");  
  259.             notification = new NotificationManagerService(context, statusBar, lights);  
  260.             ServiceManager.addService(Context.NOTIFICATION_SERVICE, notification);  
  261.         } catch (Throwable e) {  
  262.             Slog.e(TAG, "Failure starting Notification Manager", e);  
  263.         }  
  264.   
  265.         try {  
  266.             Slog.i(TAG, "Device Storage Monitor");  
  267.             ServiceManager.addService(DeviceStorageMonitorService.SERVICE,  
  268.                     new DeviceStorageMonitorService(context));  
  269.         } catch (Throwable e) {  
  270.             Slog.e(TAG, "Failure starting DeviceStorageMonitor service", e);  
  271.         }  
  272.   
  273.         try {  
  274.             Slog.i(TAG, "Location Manager");  
  275.             location = new LocationManagerService(context);  
  276.             ServiceManager.addService(Context.LOCATION_SERVICE, location);  
  277.         } catch (Throwable e) {  
  278.             Slog.e(TAG, "Failure starting Location Manager", e);  
  279.         }  
  280.   
  281.         try {  
  282.             Slog.i(TAG, "Search Service");  
  283.             ServiceManager.addService(Context.SEARCH_SERVICE,  
  284.                     new SearchManagerService(context));  
  285.         } catch (Throwable e) {  
  286.             Slog.e(TAG, "Failure starting Search Service", e);  
  287.         }  
  288.   
  289.         if (INCLUDE_DEMO) {  
  290.             Slog.i(TAG, "Installing demo data...");  
  291.             (new DemoThread(context)).start();  
  292.         }  
  293.   
  294.         try {  
  295.             Slog.i(TAG, "DropBox Service");  
  296.             ServiceManager.addService(Context.DROPBOX_SERVICE,  
  297.                     new DropBoxManagerService(context, new File("/data/system/dropbox")));  
  298.         } catch (Throwable e) {  
  299.             Slog.e(TAG, "Failure starting DropBoxManagerService", e);  
  300.         }  
  301.   
  302.         try {  
  303.             Slog.i(TAG, "Wallpaper Service");  
  304.             wallpaper = new WallpaperManagerService(context);  
  305.             ServiceManager.addService(Context.WALLPAPER_SERVICE, wallpaper);  
  306.         } catch (Throwable e) {  
  307.             Slog.e(TAG, "Failure starting Wallpaper Service", e);  
  308.         }  
  309.   
  310.         try {  
  311.             Slog.i(TAG, "Audio Service");  
  312.             ServiceManager.addService(Context.AUDIO_SERVICE, new AudioService(context));  
  313.         } catch (Throwable e) {  
  314.             Slog.e(TAG, "Failure starting Audio Service", e);  
  315.         }  
  316.   
  317.         try {  
  318.             Slog.i(TAG, "Headset Observer");  
  319.             // Listen for wired headset changes  
  320.             headset = new HeadsetObserver(context);  
  321.         } catch (Throwable e) {  
  322.             Slog.e(TAG, "Failure starting HeadsetObserver", e);  
  323.         }  
  324.   
  325.         try {  
  326.             Slog.i(TAG, "Dock Observer");  
  327.             // Listen for dock station changes  
  328.             dock = new DockObserver(context, power);  
  329.         } catch (Throwable e) {  
  330.             Slog.e(TAG, "Failure starting DockObserver", e);  
  331.         }  
  332.   
  333.         try {  
  334.             Slog.i(TAG, "USB Service");  
  335.             // Listen for USB changes  
  336.             usb = new UsbService(context);  
  337.             ServiceManager.addService(Context.USB_SERVICE, usb);  
  338.         } catch (Throwable e) {  
  339.             Slog.e(TAG, "Failure starting UsbService", e);  
  340.         }  
  341.   
  342.         try {  
  343.             Slog.i(TAG, "UI Mode Manager Service");  
  344.             // Listen for UI mode changes  
  345.             uiMode = new UiModeManagerService(context);  
  346.         } catch (Throwable e) {  
  347.             Slog.e(TAG, "Failure starting UiModeManagerService", e);  
  348.         }  
  349.   
  350.         try {  
  351.             Slog.i(TAG, "Backup Service");  
  352.             ServiceManager.addService(Context.BACKUP_SERVICE,  
  353.                     new BackupManagerService(context));  
  354.         } catch (Throwable e) {  
  355.             Slog.e(TAG, "Failure starting Backup Service", e);  
  356.         }  
  357.   
  358.         try {  
  359.             Slog.i(TAG, "AppWidget Service");  
  360.             appWidget = new AppWidgetService(context);  
  361.             ServiceManager.addService(Context.APPWIDGET_SERVICE, appWidget);  
  362.         } catch (Throwable e) {  
  363.             Slog.e(TAG, "Failure starting AppWidget Service", e);  
  364.         }  
  365.   
  366.         try {  
  367.             Slog.i(TAG, "Recognition Service");  
  368.             recognition = new RecognitionManagerService(context);  
  369.         } catch (Throwable e) {  
  370.             Slog.e(TAG, "Failure starting Recognition Service", e);  
  371.         }  
  372.           
  373.         try {  
  374.             Slog.i(TAG, "DiskStats Service");  
  375.             ServiceManager.addService("diskstats"new DiskStatsService(context));  
  376.         } catch (Throwable e) {  
  377.             Slog.e(TAG, "Failure starting DiskStats Service", e);  
  378.         }  
  379.   
  380.         try {  
  381.             Slog.i(TAG, "AnotherWatchdog Service");  
  382.             ServiceManager.addService("another_watchdog"new AnotherWatchdogService());  
  383.         } catch (Throwable e) {  
  384.             Slog.e(TAG, "Failure starting AnotherWatchdog Service", e);  
  385.         }  
  386.     }  
  387.   
  388.     // make sure the ADB_ENABLED setting value matches the secure property value  
  389.     Settings.Secure.putInt(mContentResolver, Settings.Secure.ADB_ENABLED,  
  390.             "1".equals(SystemProperties.get("persist.service.adb.enable")) ? 1 : 0);  
  391.   
  392.     // register observer to listen for settings changes  
  393.     mContentResolver.registerContentObserver(Settings.Secure.getUriFor(Settings.Secure.ADB_ENABLED),  
  394.             falsenew AdbSettingsObserver());  
  395.   
  396.     // Before things start rolling, be sure we have decided whether  
  397.     // we are in safe mode.  
  398.     final boolean safeMode = wm.detectSafeMode();  
  399.     if (safeMode) {  
  400.         try {  
  401.             ActivityManagerNative.getDefault().enterSafeMode();  
  402.             // Post the safe mode state in the Zygote class  
  403.             Zygote.systemInSafeMode = true;  
  404.             // Disable the JIT for the system_server process  
  405.             VMRuntime.getRuntime().disableJitCompilation();  
  406.         } catch (RemoteException e) {  
  407.         }  
  408.     } else {  
  409.         // Enable the JIT for the system_server process  
  410.         VMRuntime.getRuntime().startJitCompilation();  
  411.     }  
  412.   
  413.     // It is now time to start up the app processes...  
  414.   
  415.     if (devicePolicy != null) {  
  416.         devicePolicy.systemReady();  
  417.     }  
  418.   
  419.     if (notification != null) {  
  420.         notification.systemReady();  
  421.     }  
  422.   
  423.     if (statusBar != null) {  
  424.         statusBar.systemReady();  
  425.     }  
  426.     wm.systemReady();  
  427.     power.systemReady();  
  428.     try {  
  429.         pm.systemReady();  
  430.     } catch (RemoteException e) {  
  431.     }  
  432.   
  433.     // These are needed to propagate to the runnable below.  
  434.     final StatusBarManagerService statusBarF = statusBar;  
  435.     final BatteryService batteryF = battery;  
  436.     final ConnectivityService connectivityF = connectivity;  
  437.     final DockObserver dockF = dock;  
  438.     final UsbService usbF = usb;  
  439.     final ThrottleService throttleF = throttle;  
  440.     final UiModeManagerService uiModeF = uiMode;  
  441.     final AppWidgetService appWidgetF = appWidget;  
  442.     final WallpaperManagerService wallpaperF = wallpaper;  
  443.     final InputMethodManagerService immF = imm;  
  444.     final RecognitionManagerService recognitionF = recognition;  
  445.     final LocationManagerService locationF = location;  
  446.   
  447.     // We now tell the activity manager it is okay to run third party  
  448.     // code.  It will call back into us once it has gotten to the state  
  449.     // where third party code can really run (but before it has actually  
  450.     // started launching the initial applications), for us to complete our  
  451.     // initialization.  
  452.     ((ActivityManagerService)ActivityManagerNative.getDefault())  
  453.             .systemReady(new Runnable() {  
  454.         public void run() {  
  455.             Slog.i(TAG, "Making services ready");  
  456.   
  457.             if (statusBarF != null) statusBarF.systemReady2();  
  458.             if (batteryF != null) batteryF.systemReady();  
  459.             if (connectivityF != null) connectivityF.systemReady();  
  460.             if (dockF != null) dockF.systemReady();  
  461.             if (usbF != null) usbF.systemReady();  
  462.             if (uiModeF != null) uiModeF.systemReady();  
  463.             if (recognitionF != null) recognitionF.systemReady();  
  464.             Watchdog.getInstance().start();  
  465.   
  466.             // It is now okay to let the various system services start their  
  467.             // third party code...  
  468.   
  469.             if (appWidgetF != null) appWidgetF.systemReady(safeMode);  
  470.             if (wallpaperF != null) wallpaperF.systemReady();  
  471.             if (immF != null) immF.systemReady();  
  472.             if (locationF != null) locationF.systemReady();  
  473.             if (throttleF != null) throttleF.systemReady();  
  474.         }  
  475.     });  
  476.   
  477. w Thread(new WakelockMonitor(power))).start();  
  478.     // For debug builds, log event loop stalls to dropbox for analysis.  
  479.     if (StrictMode.conditionallyEnableDebugLogging()) {  
  480.         Slog.i(TAG, "Enabled StrictMode for system server main thread.");  
  481.     }  
  482.   
  483.     Looper.loop();  
  484.     Slog.d(TAG, "System ServerThread is exiting!");  
  485. }  

在run函数中启动Java中的各种Service。至此SystemServer进程启动过程分析完毕!启动过程序列图如下所示:


原创粉丝点击