Android的System Server

 

System Server是Android系统的核心,他在Dalvik虚拟机启动后立即开始初始化和运行。其它的系统服务在System Server进程的环境中运行。/base/services/java/com/android/server/SystemServer.java

Java代码 复制代码  收藏代码
  1. /**  
  2.  * This method is called from Zygote to initialize the system. This will cause the native  
  3.  * services (SurfaceFlinger, AudioFlinger, etc..) to be started. After that it will call back  
  4.  * up into init2() to start the Android services.  
  5.  */  
  6. native public static void init1(String[] args);   
  7.   
  8. public static void main(String[] args) {   
  9.     if (System.currentTimeMillis() < EARLIEST_SUPPORTED_TIME) {   
  10.         // If a device's clock is before 1970 (before 0), a lot of   
  11.         // APIs crash dealing with negative numbers, notably   
  12.         // java.io.File#setLastModified, so instead we fake it and   
  13.         // hope that time from cell towers or NTP fixes it   
  14.         // shortly.   
  15.         Slog.w(TAG, "System clock is before 1970; setting to 1970.");   
  16.         SystemClock.setCurrentTimeMillis(EARLIEST_SUPPORTED_TIME);   
  17.     }   
  18.   
  19.     if (SamplingProfilerIntegration.isEnabled()) {   
  20.         SamplingProfilerIntegration.start();   
  21.         timer = new Timer();   
  22.         timer.schedule(new TimerTask() {   
  23.             @Override  
  24.             public void run() {   
  25.                 SamplingProfilerIntegration.writeSnapshot("system_server");   
  26.             }   
  27.         }, SNAPSHOT_INTERVAL, SNAPSHOT_INTERVAL);   
  28.     }   
  29.   
  30.     // The system server has to run all of the time, so it needs to be   
  31.     // as efficient as possible with its memory usage.   
  32.     VMRuntime.getRuntime().setTargetHeapUtilization(0.8f);   
  33.        
  34.     System.loadLibrary("android_servers");   
  35.     init1(args);   
  36. }   
  37.   
  38. public static final void init2() {   
  39.     Slog.i(TAG, "Entered the Android system server!");   
  40.     Thread thr = new ServerThread();   
  41.     thr.setName("android.server.ServerThread");   
  42.     thr.start();   
  43. }  
    /**
     * This method is called from Zygote to initialize the system. This will cause the native
     * services (SurfaceFlinger, AudioFlinger, etc..) to be started. After that it will call back
     * up into init2() to start the Android services.
     */
    native public static void init1(String[] args);

    public static void main(String[] args) {
        if (System.currentTimeMillis() < EARLIEST_SUPPORTED_TIME) {
            // If a device's clock is before 1970 (before 0), a lot of
            // APIs crash dealing with negative numbers, notably
            // java.io.File#setLastModified, so instead we fake it and
            // hope that time from cell towers or NTP fixes it
            // shortly.
            Slog.w(TAG, "System clock is before 1970; setting to 1970.");
            SystemClock.setCurrentTimeMillis(EARLIEST_SUPPORTED_TIME);
        }

        if (SamplingProfilerIntegration.isEnabled()) {
            SamplingProfilerIntegration.start();
            timer = new Timer();
            timer.schedule(new TimerTask() {
                @Override
                public void run() {
                    SamplingProfilerIntegration.writeSnapshot("system_server");
                }
            }, SNAPSHOT_INTERVAL, SNAPSHOT_INTERVAL);
        }

        // The system server has to run all of the time, so it needs to be
        // as efficient as possible with its memory usage.
        VMRuntime.getRuntime().setTargetHeapUtilization(0.8f);
        
        System.loadLibrary("android_servers");
        init1(args);
    }

    public static final void init2() {
        Slog.i(TAG, "Entered the Android system server!");
        Thread thr = new ServerThread();
        thr.setName("android.server.ServerThread");
        thr.start();
    }

 在main函数中,首先检查系统时间设置和SamplingProfiler。然后加载一个叫android_servers的本地库,他提供本地方法的接口(源程序在framework/base/services/jni/目录中)。然后调用本地方法设置服务。具体执行设置的代码在frameworks/base/cmds/system_server/library/system_init.cpp中。

C代码 复制代码  收藏代码
  1. extern "C" status_t system_init()   
  2. {   
  3.     LOGI("Entered system_init()");   
  4.        
  5.     sp<ProcessState> proc(ProcessState::self());   
  6.        
  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.     if (strcmp(propBuf, "1") == 0) {   
  16.         // Start the SurfaceFlinger   
  17.         SurfaceFlinger::instantiate();   
  18.     }   
  19.   
  20.     // Start the sensor service   
  21.     SensorService::instantiate();   
  22.   
  23.     // On the simulator, audioflinger et al don't get started the   
  24.     // same way as on the device, and we need to start them here   
  25.     if (!proc->supportsProcesses()) {   
  26.   
  27.         // Start the AudioFlinger   
  28.         AudioFlinger::instantiate();   
  29.   
  30.         // Start the media playback service   
  31.         MediaPlayerService::instantiate();   
  32.   
  33.         // Start the camera service   
  34.         CameraService::instantiate();   
  35.   
  36.         // Start the audio policy service   
  37.         AudioPolicyService::instantiate();   
  38.     }   
  39.   
  40.     // And now start the Android runtime.  We have to do this bit   
  41.     // of nastiness because the Android runtime initialization requires   
  42.     // some of the core system services to already be started.   
  43.     // All other servers should just start the Android runtime at   
  44.     // the beginning of their processes's main(), before calling   
  45.     // the init function.   
  46.     LOGI("System server: starting Android runtime.\n");   
  47.        
  48.     AndroidRuntime* runtime = AndroidRuntime::getRuntime();   
  49.   
  50.     LOGI("System server: starting Android services.\n");   
  51.     runtime->callStatic("com/android/server/SystemServer""init2");   
  52.            
  53.     // If running in our own process, just go into the thread   
  54.     // pool.  Otherwise, call the initialization finished   
  55.     // func to let this process continue its initilization.   
  56.     if (proc->supportsProcesses()) {   
  57.         LOGI("System server: entering thread pool.\n");   
  58.         ProcessState::self()->startThreadPool();   
  59.         IPCThreadState::self()->joinThreadPool();   
  60.         LOGI("System server: exiting thread pool.\n");   
  61.     }   
  62.     return NO_ERROR;   
  63. }  

 等初始化传感器,视频,音频等服务后,调用一个回调方法init2 (在SystemServer.java中)。在上面的代码可以看到,这个方法开启了ServerThread来初始化其它的服务。

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

        Looper.prepare();

        android.os.Process.setThreadPriority(
                android.os.Process.THREAD_PRIORITY_FOREGROUND);

        BinderInternal.disableBackgroundScheduling(true);
        android.os.Process.setCanSelfBackground(false);

        // Check whether we failed to shut down last time we tried.
        {
            final String shutdownAction = SystemProperties.get(
                    ShutdownThread.SHUTDOWN_ACTION_PROPERTY, "");
            if (shutdownAction != null && shutdownAction.length() > 0) {
                boolean reboot = (shutdownAction.charAt(0) == '1');

                final String reason;
                if (shutdownAction.length() > 1) {
                    reason = shutdownAction.substring(1, shutdownAction.length());
                } else {
                    reason = null;
                }

                ShutdownThread.rebootOrShutdown(reboot, reason);
            }
        }

        String factoryTestStr = SystemProperties.get("ro.factorytest");
        int factoryTest = "".equals(factoryTestStr) ? SystemServer.FACTORY_TEST_OFF
                : Integer.parseInt(factoryTestStr);

        LightsService lights = null;
        PowerManagerService power = null;
        BatteryService battery = null;
        ConnectivityService connectivity = null;
        IPackageManager pm = null;
        Context context = null;
        WindowManagerService wm = null;
        BluetoothService bluetooth = null;
        BluetoothA2dpService bluetoothA2dp = null;
        HeadsetObserver headset = null;
        DockObserver dock = null;
        UsbService usb = null;
        UiModeManagerService uiMode = null;
        RecognitionManagerService recognition = null;
        ThrottleService throttle = null;

        // Critical services...
        try {
            Slog.i(TAG, "Entropy Service");
            ServiceManager.addService("entropy", new EntropyService());

            Slog.i(TAG, "Power Manager");
            power = new PowerManagerService();
            ServiceManager.addService(Context.POWER_SERVICE, power);

            Slog.i(TAG, "Activity Manager");
            context = ActivityManagerService.main(factoryTest);

            Slog.i(TAG, "Telephony Registry");
            ServiceManager.addService("telephony.registry", new TelephonyRegistry(context));

            AttributeCache.init(context);

            Slog.i(TAG, "Package Manager");
            pm = PackageManagerService.main(context,
                    factoryTest != SystemServer.FACTORY_TEST_OFF);

            ActivityManagerService.setSystemProcess();

            mContentResolver = context.getContentResolver();

            // The AccountManager must come before the ContentService
            try {
                Slog.i(TAG, "Account Manager");
                ServiceManager.addService(Context.ACCOUNT_SERVICE,
                        new AccountManagerService(context));
            } catch (Throwable e) {
                Slog.e(TAG, "Failure starting Account Manager", e);
            }

            Slog.i(TAG, "Content Manager");
            ContentService.main(context,
                    factoryTest == SystemServer.FACTORY_TEST_LOW_LEVEL);

            Slog.i(TAG, "System Content Providers");
            ActivityManagerService.installSystemProviders();

            Slog.i(TAG, "Battery Service");
            battery = new BatteryService(context);
            ServiceManager.addService("battery", battery);

            Slog.i(TAG, "Lights Service");
            lights = new LightsService(context);

            Slog.i(TAG, "Vibrator Service");
            ServiceManager.addService("vibrator", new VibratorService(context));

            // only initialize the power service after we have started the
            // lights service, content providers and the battery service.
            power.init(context, lights, ActivityManagerService.getDefault(), battery);

            Slog.i(TAG, "Alarm Manager");
            AlarmManagerService alarm = new AlarmManagerService(context);
            ServiceManager.addService(Context.ALARM_SERVICE, alarm);

            Slog.i(TAG, "Init Watchdog");
            Watchdog.getInstance().init(context, battery, power, alarm,
                    ActivityManagerService.self());

            Slog.i(TAG, "Window Manager");
            wm = WindowManagerService.main(context, power,
                    factoryTest != SystemServer.FACTORY_TEST_LOW_LEVEL);
            ServiceManager.addService(Context.WINDOW_SERVICE, wm);

            ((ActivityManagerService)ServiceManager.getService("activity"))
                    .setWindowManager(wm);

            // Skip Bluetooth if we have an emulator kernel
            // TODO: Use a more reliable check to see if this product should
            // support Bluetooth - see bug 988521
            if (SystemProperties.get("ro.kernel.qemu").equals("1")) {
                Slog.i(TAG, "Registering null Bluetooth Service (emulator)");
                ServiceManager.addService(BluetoothAdapter.BLUETOOTH_SERVICE, null);
            } else if (factoryTest == SystemServer.FACTORY_TEST_LOW_LEVEL) {
                Slog.i(TAG, "Registering null Bluetooth Service (factory test)");
                ServiceManager.addService(BluetoothAdapter.BLUETOOTH_SERVICE, null);
            } else {
                Slog.i(TAG, "Bluetooth Service");
                bluetooth = new BluetoothService(context);
                ServiceManager.addService(BluetoothAdapter.BLUETOOTH_SERVICE, bluetooth);
                bluetooth.initAfterRegistration();
                bluetoothA2dp = new BluetoothA2dpService(context, bluetooth);
                ServiceManager.addService(BluetoothA2dpService.BLUETOOTH_A2DP_SERVICE,
                                          bluetoothA2dp);

                int bluetoothOn = Settings.Secure.getInt(mContentResolver,
                    Settings.Secure.BLUETOOTH_ON, 0);
                if (bluetoothOn > 0) {
                    bluetooth.enable();
                }
            }

        } catch (RuntimeException e) {
            Slog.e("System", "Failure starting core service", e);
        }

        DevicePolicyManagerService devicePolicy = null;
        StatusBarManagerService statusBar = null;
        InputMethodManagerService imm = null;
        AppWidgetService appWidget = null;
        NotificationManagerService notification = null;
        WallpaperManagerService wallpaper = null;
        LocationManagerService location = null;

        if (factoryTest != SystemServer.FACTORY_TEST_LOW_LEVEL) {
            try {
                Slog.i(TAG, "Device Policy");
                devicePolicy = new DevicePolicyManagerService(context);
                ServiceManager.addService(Context.DEVICE_POLICY_SERVICE, devicePolicy);
            } catch (Throwable e) {
                Slog.e(TAG, "Failure starting DevicePolicyService", e);
            }

            try {
                Slog.i(TAG, "Status Bar");
                statusBar = new StatusBarManagerService(context);
                ServiceManager.addService(Context.STATUS_BAR_SERVICE, statusBar);
            } catch (Throwable e) {
                Slog.e(TAG, "Failure starting StatusBarManagerService", e);
            }

            try {
                Slog.i(TAG, "Clipboard Service");
                ServiceManager.addService(Context.CLIPBOARD_SERVICE,
                        new ClipboardService(context));
            } catch (Throwable e) {
                Slog.e(TAG, "Failure starting Clipboard Service", e);
            }

            try {
                Slog.i(TAG, "Input Method Service");
                imm = new InputMethodManagerService(context, statusBar);
                ServiceManager.addService(Context.INPUT_METHOD_SERVICE, imm);
            } catch (Throwable e) {
                Slog.e(TAG, "Failure starting Input Manager Service", e);
            }

            try {
                Slog.i(TAG, "NetStat Service");
                ServiceManager.addService("netstat", new NetStatService(context));
            } catch (Throwable e) {
                Slog.e(TAG, "Failure starting NetStat Service", e);
            }

            try {
                Slog.i(TAG, "NetworkManagement Service");
                ServiceManager.addService(
                        Context.NETWORKMANAGEMENT_SERVICE,
                        NetworkManagementService.create(context));
            } catch (Throwable e) {
                Slog.e(TAG, "Failure starting NetworkManagement Service", e);
            }

            try {
                Slog.i(TAG, "Connectivity Service");
                connectivity = ConnectivityService.getInstance(context);
                ServiceManager.addService(Context.CONNECTIVITY_SERVICE, connectivity);
            } catch (Throwable e) {
                Slog.e(TAG, "Failure starting Connectivity Service", e);
            }

            try {
                Slog.i(TAG, "Throttle Service");
                throttle = new ThrottleService(context);
                ServiceManager.addService(
                        Context.THROTTLE_SERVICE, throttle);
            } catch (Throwable e) {
                Slog.e(TAG, "Failure starting ThrottleService", e);
            }

            try {
              Slog.i(TAG, "Accessibility Manager");
              ServiceManager.addService(Context.ACCESSIBILITY_SERVICE,
                      new AccessibilityManagerService(context));
            } catch (Throwable e) {
              Slog.e(TAG, "Failure starting Accessibility Manager", e);
            }

            try {
                /*
                 * NotificationManagerService is dependant on MountService,
                 * (for media / usb notifications) so we must start MountService first.
                 */
                Slog.i(TAG, "Mount Service");
                ServiceManager.addService("mount", new MountService(context));
            } catch (Throwable e) {
                Slog.e(TAG, "Failure starting Mount Service", e);
            }

            try {
                Slog.i(TAG, "Notification Manager");
                notification = new NotificationManagerService(context, statusBar, lights);
                ServiceManager.addService(Context.NOTIFICATION_SERVICE, notification);
            } catch (Throwable e) {
                Slog.e(TAG, "Failure starting Notification Manager", e);
            }

            try {
                Slog.i(TAG, "Device Storage Monitor");
                ServiceManager.addService(DeviceStorageMonitorService.SERVICE,
                        new DeviceStorageMonitorService(context));
            } catch (Throwable e) {
                Slog.e(TAG, "Failure starting DeviceStorageMonitor service", e);
            }

            try {
                Slog.i(TAG, "Location Manager");
                location = new LocationManagerService(context);
                ServiceManager.addService(Context.LOCATION_SERVICE, location);
            } catch (Throwable e) {
                Slog.e(TAG, "Failure starting Location Manager", e);
            }

            try {
                Slog.i(TAG, "Search Service");
                ServiceManager.addService(Context.SEARCH_SERVICE,
                        new SearchManagerService(context));
            } catch (Throwable e) {
                Slog.e(TAG, "Failure starting Search Service", e);
            }

            if (INCLUDE_DEMO) {
                Slog.i(TAG, "Installing demo data...");
                (new DemoThread(context)).start();
            }

            try {
                Slog.i(TAG, "DropBox Service");
                ServiceManager.addService(Context.DROPBOX_SERVICE,
                        new DropBoxManagerService(context, new File("/data/system/dropbox")));
            } catch (Throwable e) {
                Slog.e(TAG, "Failure starting DropBoxManagerService", e);
            }

            try {
                Slog.i(TAG, "Wallpaper Service");
                wallpaper = new WallpaperManagerService(context);
                ServiceManager.addService(Context.WALLPAPER_SERVICE, wallpaper);
            } catch (Throwable e) {
                Slog.e(TAG, "Failure starting Wallpaper Service", e);
            }

            try {
                Slog.i(TAG, "Audio Service");
                ServiceManager.addService(Context.AUDIO_SERVICE, new AudioService(context));
            } catch (Throwable e) {
                Slog.e(TAG, "Failure starting Audio Service", e);
            }

            try {
                Slog.i(TAG, "Headset Observer");
                // Listen for wired headset changes
                headset = new HeadsetObserver(context);
            } catch (Throwable e) {
                Slog.e(TAG, "Failure starting HeadsetObserver", e);
            }

            try {
                Slog.i(TAG, "Dock Observer");
                // Listen for dock station changes
                dock = new DockObserver(context, power);
            } catch (Throwable e) {
                Slog.e(TAG, "Failure starting DockObserver", e);
            }

            try {
                Slog.i(TAG, "USB Service");
                // Listen for USB changes
                usb = new UsbService(context);
                ServiceManager.addService(Context.USB_SERVICE, usb);
            } catch (Throwable e) {
                Slog.e(TAG, "Failure starting UsbService", e);
            }

            try {
                Slog.i(TAG, "UI Mode Manager Service");
                // Listen for UI mode changes
                uiMode = new UiModeManagerService(context);
            } catch (Throwable e) {
                Slog.e(TAG, "Failure starting UiModeManagerService", e);
            }

            try {
                Slog.i(TAG, "Backup Service");
                ServiceManager.addService(Context.BACKUP_SERVICE,
                        new BackupManagerService(context));
            } catch (Throwable e) {
                Slog.e(TAG, "Failure starting Backup Service", e);
            }

            try {
                Slog.i(TAG, "AppWidget Service");
                appWidget = new AppWidgetService(context);
                ServiceManager.addService(Context.APPWIDGET_SERVICE, appWidget);
            } catch (Throwable e) {
                Slog.e(TAG, "Failure starting AppWidget Service", e);
            }

            try {
                Slog.i(TAG, "Recognition Service");
                recognition = new RecognitionManagerService(context);
            } catch (Throwable e) {
                Slog.e(TAG, "Failure starting Recognition Service", e);
            }
            
            try {
                Slog.i(TAG, "DiskStats Service");
                ServiceManager.addService("diskstats", new DiskStatsService(context));
            } catch (Throwable e) {
                Slog.e(TAG, "Failure starting DiskStats Service", e);
            }
        }

        // make sure the ADB_ENABLED setting value matches the secure property value
        Settings.Secure.putInt(mContentResolver, Settings.Secure.ADB_ENABLED,
                "1".equals(SystemProperties.get("persist.service.adb.enable")) ? 1 : 0);

        // register observer to listen for settings changes
        mContentResolver.registerContentObserver(Settings.Secure.getUriFor(Settings.Secure.ADB_ENABLED),
                false, new AdbSettingsObserver());

        // Before things start rolling, be sure we have decided whether
        // we are in safe mode.
        final boolean safeMode = wm.detectSafeMode();
        if (safeMode) {
            try {
                ActivityManagerNative.getDefault().enterSafeMode();
                // Post the safe mode state in the Zygote class
                Zygote.systemInSafeMode = true;
                // Disable the JIT for the system_server process
                VMRuntime.getRuntime().disableJitCompilation();
            } catch (RemoteException e) {
            }
        } else {
            // Enable the JIT for the system_server process
            VMRuntime.getRuntime().startJitCompilation();
        }

        // It is now time to start up the app processes...

        if (devicePolicy != null) {
            devicePolicy.systemReady();
        }

        if (notification != null) {
            notification.systemReady();
        }

        if (statusBar != null) {
            statusBar.systemReady();
        }
        wm.systemReady();
        power.systemReady();
        try {
            pm.systemReady();
        } catch (RemoteException e) {
        }

        // These are needed to propagate to the runnable below.
        final StatusBarManagerService statusBarF = statusBar;
        final BatteryService batteryF = battery;
        final ConnectivityService connectivityF = connectivity;
        final DockObserver dockF = dock;
        final UsbService usbF = usb;
        final ThrottleService throttleF = throttle;
        final UiModeManagerService uiModeF = uiMode;
        final AppWidgetService appWidgetF = appWidget;
        final WallpaperManagerService wallpaperF = wallpaper;
        final InputMethodManagerService immF = imm;
        final RecognitionManagerService recognitionF = recognition;
        final LocationManagerService locationF = location;

        // We now tell the activity manager it is okay to run third party
        // code.  It will call back into us once it has gotten to the state
        // where third party code can really run (but before it has actually
        // started launching the initial applications), for us to complete our
        // initialization.
        ((ActivityManagerService)ActivityManagerNative.getDefault())
                .systemReady(new Runnable() {
            public void run() {
                Slog.i(TAG, "Making services ready");

                if (statusBarF != null) statusBarF.systemReady2();
                if (batteryF != null) batteryF.systemReady();
                if (connectivityF != null) connectivityF.systemReady();
                if (dockF != null) dockF.systemReady();
                if (usbF != null) usbF.systemReady();
                if (uiModeF != null) uiModeF.systemReady();
                if (recognitionF != null) recognitionF.systemReady();
                Watchdog.getInstance().start();

                // It is now okay to let the various system services start their
                // third party code...

                if (appWidgetF != null) appWidgetF.systemReady(safeMode);
                if (wallpaperF != null) wallpaperF.systemReady();
                if (immF != null) immF.systemReady();
                if (locationF != null) locationF.systemReady();
                if (throttleF != null) throttleF.systemReady();
            }
        });

        // For debug builds, log event loop stalls to dropbox for analysis.
        if (StrictMode.conditionallyEnableDebugLogging()) {
            Slog.i(TAG, "Enabled StrictMode for system server main thread.");
        }

        Looper.loop();
        Slog.d(TAG, "System ServerThread is exiting!");
    }

这里启动的没一个进程都作为一个Dalvik线程而存在于SystemServer进程里面。




 

  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值