Android系统开机启动流程

本文深入解析了Android系统的启动流程,从Linux内核启动到应用程序的启动全过程,包括init进程、ServiceManager、Zygote进程和服务的创建等关键环节。
第一步:启动linux
1.Bootloader
2.Kernel

第二步android系统启动:入口为init.rc(system\core\rootdir)
1./system/bin/service manager: Binder 守护进程;
2.Runtime;
3.Zygote :app-process/app-main;
4.Start VM;
5.Start server
6.Start android service:Register to service Manager
7.Start Launcher

第三步:应用程序启动:运行package Manager
1.Init进程

       Android系统在启动时首先会启动Linux系统,引导加载Linux Kernel并启动init进程。Init进程是一个由内核启动的用户级进程,是Android系统的第一个进程。该进程的相关代码在platform\system\core\init\init.c。在main函数中,有如下代码:

  1. open_devnull_stdio();  
  2. log_init();  
  3. INFO("reading config file\n");  
  4. init_parse_config_file("/init.rc");  
  5.   
  6. /* pull the kernel commandline and ramdisk properties file in */  
  7. import_kernel_cmdline(0);  
  8. get_hardware_name(hardware, &revision);  
  9. snprintf(tmp, sizeof(tmp), "/init.%s.rc", hardware);  
  10. init_parse_config_file(tmp);  
    open_devnull_stdio();
    log_init();
    INFO("reading config file\n");
    init_parse_config_file("/init.rc");

    /* pull the kernel commandline and ramdisk properties file in */
    import_kernel_cmdline(0);
    get_hardware_name(hardware, &revision);
    snprintf(tmp, sizeof(tmp), "/init.%s.rc", hardware);
    init_parse_config_file(tmp);

       这里会加载解析init.rc和init.hardware.rc两个初始化脚本。*.rc文件定义了在init进程中需要启动哪些进程服务和执行哪些动作。其详细说明参见platform\system\core\init\reademe.txt。init.rc见如下定义:

  1. service servicemanager /system/bin/servicemanager  
  2.     user system  
  3.     critical  
  4.     onrestart restart zygote  
  5.     onrestart restart media  
  6.   
  7. service vold /system/bin/vold  
  8.     socket vold stream 0660 root mount  
  9.     ioprio be 2  
  10.   
  11. service netd /system/bin/netd  
  12.     socket netd stream 0660 root system  
  13.     socket dnsproxyd stream 0660 root inet  
  14.   
  15. service debuggerd /system/bin/debuggerd  
  16.   
  17. service ril-daemon /system/bin/rild  
  18.     socket rild stream 660 root radio  
  19.     socket rild-debug stream 660 radio system  
  20.     user root  
  21.     group radio cache inet misc audio sdcard_rw  
  22.   
  23. service zygote /system/bin/app_process -Xzygote /system/bin --zygote --start-system-server  
  24.     socket zygote stream 666  
  25.     onrestart write /sys/android_power/request_state wake  
  26.     onrestart write /sys/power/state on  
  27.     onrestart restart media  
  28.     onrestart restart netd  
  29.   
  30. service drm /system/bin/drmserver  
  31.     user drm  
  32.     group system root inet  
service servicemanager /system/bin/servicemanager
    user system
    critical
    onrestart restart zygote
    onrestart restart media

service vold /system/bin/vold
    socket vold stream 0660 root mount
    ioprio be 2

service netd /system/bin/netd
    socket netd stream 0660 root system
    socket dnsproxyd stream 0660 root inet

service debuggerd /system/bin/debuggerd

service ril-daemon /system/bin/rild
    socket rild stream 660 root radio
    socket rild-debug stream 660 radio system
    user root
    group radio cache inet misc audio sdcard_rw

service zygote /system/bin/app_process -Xzygote /system/bin --zygote --start-system-server
    socket zygote stream 666
    onrestart write /sys/android_power/request_state wake
    onrestart write /sys/power/state on
    onrestart restart media
    onrestart restart netd

service drm /system/bin/drmserver
    user drm
    group system root inet

    具体解析过程见platform\system\core\init\Init_parser.c。解析所得服务添加到service_list中,动作添加到action_list中。
    接下来在main函数中执行动作和启动进程服务:

  1. execute_one_command();  
  2. restart_processes();  
   execute_one_command();
   restart_processes();

      通常init过程需要创建一些系统文件夹并启动USB守护进程、Android Debug Bridge守护进程、Debug守护进程、ServiceManager进程、Zygote进程等。

2. ServiceManager进程
     ServiceManager进程是所有服务的管理器。由init.rc对ServiceManager的描述service servicemanager/system/bin/servicemanager可知servicemanager进程从platform\frameworks\base\cmd\servicemanager\Service_manager.cpp启动。在main函数中有如下代码:

  1. int main(int argc, char **argv)  
  2. {  
  3.     struct binder_state *bs;  
  4.     void *svcmgr = BINDER_SERVICE_MANAGER;  
  5.   
  6.     bs = binder_open(128*1024);  
  7.   
  8.     if (binder_become_context_manager(bs)) {  
  9.         LOGE("cannot become context manager (%s)\n", strerror(errno));  
  10.         return -1;  
  11.     }  
  12.   
  13.     svcmgr_handle = svcmgr;  
  14.     binder_loop(bs, svcmgr_handler);  
  15.     return 0;  
  16. }  
int main(int argc, char **argv)
{
    struct binder_state *bs;
    void *svcmgr = BINDER_SERVICE_MANAGER;

    bs = binder_open(128*1024);

    if (binder_become_context_manager(bs)) {
        LOGE("cannot become context manager (%s)\n", strerror(errno));
        return -1;
    }

    svcmgr_handle = svcmgr;
    binder_loop(bs, svcmgr_handler);
    return 0;
}

       首先调用binder_open()打开Binder设备(/dev/binder),调用binder_become_context_manager()把当前进程设置为ServiceManager。ServiceManager本身就是一个服务。

  1. int binder_become_context_manager(struct binder_state *bs)  
  2. {  
  3.     return ioctl(bs->fd, BINDER_SET_CONTEXT_MGR, 0);  
  4. }  
int binder_become_context_manager(struct binder_state *bs)
{
    return ioctl(bs->fd, BINDER_SET_CONTEXT_MGR, 0);
}


     最后binder_loop()进入循环状态,并设置svcmgr_handler回调函数等待添加、查询、获取服务等请求。

3. Zygote进程
      Zygote进程用于产生其他进程。由init.rc对zygote的描述service zygot /system/bin/app_process可知zygote进程从platfrom\frameworks\base\cmds\app_process\App_main.cpp启动。在main函数中有如下代码:
 

  1. if (0 == strcmp("--zygote", arg)) {  
  2.      bool startSystemServer = (i < argc) ?  
  3.             strcmp(argv[i], "--start-system-server") == 0 : false;  
  4.      setArgv0(argv0, "zygote");  
  5.      set_process_name("zygote");  
  6.      runtime.start("com.android.internal.os.ZygoteInit",  
  7.          startSystemServer);  
  8.  } else {  
  9.      set_process_name(argv0);  
  10.      runtime.mClassName = arg;  
  11.   
  12.      // Remainder of args get passed to startup class main()   
  13.      runtime.mArgC = argc-i;  
  14.      runtime.mArgV = argv+i;  
  15.   
  16.      LOGV("App process is starting with pid=%d, class=%s.\n",  
  17.           getpid(), runtime.getClassName());  
  18.      runtime.start();  
  19.  }  
       if (0 == strcmp("--zygote", arg)) {
            bool startSystemServer = (i < argc) ?
                   strcmp(argv[i], "--start-system-server") == 0 : false;
            setArgv0(argv0, "zygote");
            set_process_name("zygote");
            runtime.start("com.android.internal.os.ZygoteInit",
                startSystemServer);
        } else {
            set_process_name(argv0);
            runtime.mClassName = arg;

            // Remainder of args get passed to startup class main()
            runtime.mArgC = argc-i;
            runtime.mArgV = argv+i;

            LOGV("App process is starting with pid=%d, class=%s.\n",
                 getpid(), runtime.getClassName());
            runtime.start();
        }

      首先创建AppRuntime,即AndroidRuntime,建立了一个Dalvik虚拟机。通过这个runtime传递com.android.internal.os.ZygoteInit参数,从而由Dalvik虚拟机运行ZygoteInit.java的main(),开始创建Zygote进程。在其main()中,如下所示:

  1. registerZygoteSocket();  
  2. EventLog.writeEvent(LOG_BOOT_PROGRESS_PRELOAD_START,  
  3. SystemClock.uptimeMillis());  
  4. preloadClasses();  
  5. //cacheRegisterMaps();   
  6. preloadResources();  
  7. EventLog.writeEvent(LOG_BOOT_PROGRESS_PRELOAD_END,  
  8.          SystemClock.uptimeMillis());  
  9.   
  10. // Finish profiling the zygote initialization.   
  11. SamplingProfilerIntegration.writeZygoteSnapshot();  
  12.   
  13. // Do an initial gc to clean up after startup   
  14. gc();  
  15.   
  16. // If requested, start system server directly from Zygote   
  17. if (argv.length != 2) {  
  18.    throw new RuntimeException(argv[0] + USAGE_STRING);  
  19. }  
  20.   
  21. if (argv[1].equals("true")) {  
  22.      startSystemServer();  
  23. else if (!argv[1].equals("false")) {  
  24.     throw new RuntimeException(argv[0] + USAGE_STRING);  
  25. }  
       registerZygoteSocket();
       EventLog.writeEvent(LOG_BOOT_PROGRESS_PRELOAD_START,
       SystemClock.uptimeMillis());
       preloadClasses();
       //cacheRegisterMaps();
       preloadResources();
       EventLog.writeEvent(LOG_BOOT_PROGRESS_PRELOAD_END,
                SystemClock.uptimeMillis());

       // Finish profiling the zygote initialization.
       SamplingProfilerIntegration.writeZygoteSnapshot();

       // Do an initial gc to clean up after startup
       gc();

       // If requested, start system server directly from Zygote
       if (argv.length != 2) {
          throw new RuntimeException(argv[0] + USAGE_STRING);
       }

       if (argv[1].equals("true")) {
            startSystemServer();
       } else if (!argv[1].equals("false")) {
           throw new RuntimeException(argv[0] + USAGE_STRING);
       }


      首先通过registerZygoteSocket()登记端口,接着preloadClasses()装载相关类。这里大概要装载1000多个类,具体装载类见platform\frameworks\base\preloaded-classes。这个文件有WritePreloadedClassFile类自动生成。分析该类的main函数,有如下一段筛选类的代码:

  1. // Preload classes that were loaded by at least 2 processes. Hopefully,   
  2. // the memory associated with these classes will be shared.   
  3.  for (LoadedClass loadedClass : root.loadedClasses.values()) {  
  4.      Set<String> names = loadedClass.processNames();  
  5.      if (!Policy.isPreloadable(loadedClass)) {  
  6.          continue;  
  7.      }  
  8.   
  9.      if (names.size() >= MIN_PROCESSES ||  
  10.              (loadedClass.medianTimeMicros() > MIN_LOAD_TIME_MICROS && names.size() > 1)) {  
  11.          toPreload.add(loadedClass);  
  12.      }  
  13.  }  
  14.  int initialSize = toPreload.size();  
  15.  System.out.println(initialSize  
  16.          + " classses were loaded by more than one app.");  
  17.  // Preload eligable classes from applications (not long-running   
  18.  // services).   
  19.  for (Proc proc : root.processes.values()) {  
  20.      if (proc.fromZygote() && !Policy.isService(proc.name)) {  
  21.          for (Operation operation : proc.operations) {  
  22.              LoadedClass loadedClass = operation.loadedClass;  
  23.              if (shouldPreload(loadedClass)) {  
  24.                  toPreload.add(loadedClass);  
  25.              }  
  26.          }  
  27.      }  
  28.  }  
       // Preload classes that were loaded by at least 2 processes. Hopefully,
       // the memory associated with these classes will be shared.
        for (LoadedClass loadedClass : root.loadedClasses.values()) {
            Set<String> names = loadedClass.processNames();
            if (!Policy.isPreloadable(loadedClass)) {
                continue;
            }

            if (names.size() >= MIN_PROCESSES ||
                    (loadedClass.medianTimeMicros() > MIN_LOAD_TIME_MICROS && names.size() > 1)) {
                toPreload.add(loadedClass);
            }
        }
        int initialSize = toPreload.size();
        System.out.println(initialSize
                + " classses were loaded by more than one app.");
        // Preload eligable classes from applications (not long-running
        // services).
        for (Proc proc : root.processes.values()) {
            if (proc.fromZygote() && !Policy.isService(proc.name)) {
                for (Operation operation : proc.operations) {
                    LoadedClass loadedClass = operation.loadedClass;
                    if (shouldPreload(loadedClass)) {
                        toPreload.add(loadedClass);
                    }
                }
            }
        }


      其中MIN_LOAD_TIME_MICROS等于1250,当类的装载时间大于1.25ms,则需要预装载。

      Policy.isPreloadable()定于如下:

  1. /**Reports if the given class should be preloaded. */  
  2.  public static boolean isPreloadable(LoadedClass clazz) {  
  3.      return clazz.systemClass && !EXCLUDED_CLASSES.contains(clazz.name);  
  4.  }  
   /**Reports if the given class should be preloaded. */
    public static boolean isPreloadable(LoadedClass clazz) {
        return clazz.systemClass && !EXCLUDED_CLASSES.contains(clazz.name);
    }


      其中EXCLUDED_CLASSES如下定义:

  1. /** 
  2.   * Classes which we shouldn't load from the Zygote. 
  3.   */  
  4.  private static final Set<String> EXCLUDED_CLASSES  
  5.          = new HashSet<String>(Arrays.asList(  
  6.      // Binders   
  7.      "android.app.AlarmManager",  
  8.      "android.app.SearchManager",  
  9.      "android.os.FileObserver",  
  10.      "com.android.server.PackageManagerService$AppDirObserver",  
  11.      // Threads   
  12.      "android.os.AsyncTask",  
  13.      "android.pim.ContactsAsyncHelper",  
  14.      "java.lang.ProcessManager"  
  15.  ));  
   /**
     * Classes which we shouldn't load from the Zygote.
     */
    private static final Set<String> EXCLUDED_CLASSES
            = new HashSet<String>(Arrays.asList(
        // Binders
        "android.app.AlarmManager",
        "android.app.SearchManager",
        "android.os.FileObserver",
        "com.android.server.PackageManagerService$AppDirObserver",
        // Threads
        "android.os.AsyncTask",
        "android.pim.ContactsAsyncHelper",
        "java.lang.ProcessManager"
    ));


      这几个Binders和Thread是不会被预加载的。
      另外还有一些application需要装载,要求满足条件proc.fromZygote()且不是属于常驻内存的服务。SERVICES定义如下:

 

  1. /** 
  2.   * Long running services. These are restricted in their contribution to the 
  3.   * preloader because their launch time is less critical. 
  4.   */  
  5.  // TODO: Generate this automatically from package manager.   
  6.  private static final Set<String> SERVICES = new HashSet<String>(Arrays.asList(  
  7.      "system_server",  
  8.      "com.google.process.content",  
  9.      "android.process.media",  
  10.      "com.android.bluetooth",  
  11.      "com.android.calendar",  
  12.      "com.android.inputmethod.latin",  
  13.      "com.android.phone",  
  14.      "com.google.android.apps.maps.FriendService"// pre froyo   
  15.      "com.google.android.apps.maps:FriendService"// froyo   
  16.      "com.google.android.apps.maps.LocationFriendService",  
  17.      "com.google.android.deskclock",  
  18.      "com.google.process.gapps",  
  19.      "android.tts"  
  20.  ));  
   /**
     * Long running services. These are restricted in their contribution to the
     * preloader because their launch time is less critical.
     */
    // TODO: Generate this automatically from package manager.
    private static final Set<String> SERVICES = new HashSet<String>(Arrays.asList(
        "system_server",
        "com.google.process.content",
        "android.process.media",
        "com.android.bluetooth",
        "com.android.calendar",
        "com.android.inputmethod.latin",
        "com.android.phone",
        "com.google.android.apps.maps.FriendService", // pre froyo
        "com.google.android.apps.maps:FriendService", // froyo
        "com.google.android.apps.maps.LocationFriendService",
        "com.google.android.deskclock",
        "com.google.process.gapps",
        "android.tts"
    ));


        preloaded-classes是在下载源码的时候生成,WritePreloadedClassFile类并没有被用到,但可以通过这个类了解Android系统对预加载类的默认要求,参考修改preloaded-classes文件,减少开机初始化时要预加载的类,提高开机速度。 

       最后来通过startSystemServer()启动SystemServer进程。见如下代码:

 

  1. /* Hardcoded command line to start the system server */  
  2.  String args[] = {  
  3.      "--setuid=1000",  
  4.      "--setgid=1000",  
  5.      "--setgroups=1001,1002,1003,1004,1005,1006,1007,1008,1009,1010,1018,3001,3002,3003",  
  6.      "--capabilities=130104352,130104352",  
  7.      "--runtime-init",  
  8.      "--nice-name=system_server",  
  9.      "com.android.server.SystemServer",  
  10.  };  
  11.   
  12.  ZygoteConnection.Arguments parsedArgs = null;  
  13.  int pid;  
  14.  try {  
  15.      parsedArgs = new ZygoteConnection.Arguments(args);  
  16.      /* 
  17.       * Enable debugging of the system process if *either* the command line flags 
  18.       * indicate it should be debuggable or the ro.debuggable system property 
  19.       * is set to "1" 
  20.       */  
  21.      int debugFlags = parsedArgs.debugFlags;  
  22.      if ("1".equals(SystemProperties.get("ro.debuggable")))  
  23.          debugFlags |= Zygote.DEBUG_ENABLE_DEBUGGER;  
  24.   
  25.      /* Request to fork the system server process */  
  26.      pid = Zygote.forkSystemServer(  
  27.              parsedArgs.uid, parsedArgs.gid,  
  28.              parsedArgs.gids, debugFlags, null,  
  29.              parsedArgs.permittedCapabilities,  
  30.              parsedArgs.effectiveCapabilities)  
       /* Hardcoded command line to start the system server */
        String args[] = {
            "--setuid=1000",
            "--setgid=1000",
            "--setgroups=1001,1002,1003,1004,1005,1006,1007,1008,1009,1010,1018,3001,3002,3003",
            "--capabilities=130104352,130104352",
            "--runtime-init",
            "--nice-name=system_server",
            "com.android.server.SystemServer",
        };

        ZygoteConnection.Arguments parsedArgs = null;
        int pid;
        try {
            parsedArgs = new ZygoteConnection.Arguments(args);
            /*
             * Enable debugging of the system process if *either* the command line flags
             * indicate it should be debuggable or the ro.debuggable system property
             * is set to "1"
             */
            int debugFlags = parsedArgs.debugFlags;
            if ("1".equals(SystemProperties.get("ro.debuggable")))
                debugFlags |= Zygote.DEBUG_ENABLE_DEBUGGER;

            /* Request to fork the system server process */
            pid = Zygote.forkSystemServer(
                    parsedArgs.uid, parsedArgs.gid,
                    parsedArgs.gids, debugFlags, null,
                    parsedArgs.permittedCapabilities,
                    parsedArgs.effectiveCapabilities)


      Zygote包装了Linux的fork。forkSystemServer()调用forkAndSpecialize(),最终穿过虚拟机调用platform\dalvik\vm\native\dalvik_system_Zygote.c中Dalvik_dalvik_system_Zygote_forkAndSpecialize()。由dalvik完成fork新的进程。
  main()最后会调用runSelectLoopMode(),进入while循环,由peers创建新的进程。

4. SystemService进程
     SystemService用于创建init.rc定义的服务之外的所有服务。在main()的最后有如下代码:

  1. // The system server has to run all of the time, so it needs to be   
  2. // as efficient as possible with its memory usage.   
  3. VMRuntime.getRuntime().setTargetHeapUtilization(0.8f);  
  4.   
  5. System.loadLibrary("android_servers");  
  6. init1(args);  
        // 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);

       Init1()是在native空间实现的,用于启动native空间的服务,其实现在com_android_server_SystemServer.cpp中的android_server_SystemServer_init1():

  1. static void android_server_SystemServer_init1(JNIEnv* env, jobject clazz)  
  2. {  
  3.     system_init();  
  4. }  
static void android_server_SystemServer_init1(JNIEnv* env, jobject clazz)
{
    system_init();
}

       而system_init()服务初始化创建native层的各个服务:

  1. // Start the sensor service   
  2. SensorService::instantiate();  
  3.   
  4. // On the simulator, audioflinger et al don't get started the   
  5. // same way as on the device, and we need to start them here   
  6. if (!proc->supportsProcesses()) {  
  7.   // Start the AudioFlinger   
  8.   AudioFlinger::instantiate();  
  9.   
  10.   // Start the media playback service   
  11.   MediaPlayerService::instantiate();  
  12.   
  13.   // Start the camera service   
  14.   CameraService::instantiate();  
  15.   
  16.   // Start the audio policy service   
  17.   AudioPolicyService::instantiate();  
  18. }  
    // Start the sensor service
    SensorService::instantiate();

    // On the simulator, audioflinger et al don't get started the
    // same way as on the device, and we need to start them here
    if (!proc->supportsProcesses()) {
      // Start the AudioFlinger
      AudioFlinger::instantiate();

      // Start the media playback service
      MediaPlayerService::instantiate();

      // Start the camera service
      CameraService::instantiate();

      // Start the audio policy service
      AudioPolicyService::instantiate();
    }

      最后通过如下代码:

  1. LOGI("System server: starting Android services.\n");  
  2. runtime->callStatic("com/android/server/SystemServer""init2");  
   LOGI("System server: starting Android services.\n");
   runtime->callStatic("com/android/server/SystemServer", "init2");

      回到SystemServer.java,调用init2():

  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.      thr.start();  
  6.  }  
   public static final void init2() {
        Slog.i(TAG, "Entered the Android system server!");
        Thread thr = new ServerThread();
        thr.setName("android.server.ServerThread");
        thr.start();
    }

      Init2启动一个线程,专门用来启动java空间的所有服务。如下代码所示启动部分服务:

  1. // Critical services...   
  2. try {  
  3.     Slog.i(TAG, "Entropy Service");  
  4.     ServiceManager.addService("entropy"new EntropyService());  
  5.   
  6.     Slog.i(TAG, "Power Manager");  
  7.     power = new PowerManagerService();  
  8.     ServiceManager.addService(Context.POWER_SERVICE, power);  
  9.   
  10.     Slog.i(TAG, "Activity Manager");  
  11.     context = ActivityManagerService.main(factoryTest);  
  12.   
  13.     Slog.i(TAG, "Telephony Registry");  
  14.     ServiceManager.addService("telephony.registry"new TelephonyRegistry(context));  
  15.   
  16.     AttributeCache.init(context);  
  17.   
  18.     Slog.i(TAG, "Package Manager");  
  19.     // Only run "core" apps if we're encrypting the device.   
  20.     String cryptState = SystemProperties.get("vold.decrypt");  
  21.     boolean onlyCore = false;  
  22.     if (ENCRYPTING_STATE.equals(cryptState)) {  
  23.         Slog.w(TAG, "Detected encryption in progress - only parsing core apps");  
  24.         onlyCore = true;  
  25.     } else if (ENCRYPTED_STATE.equals(cryptState)) {  
  26.         Slog.w(TAG, "Device encrypted - only parsing core apps");  
  27.         onlyCore = true;  
  28.     }  
  29.   
  30.     pm = PackageManagerService.main(context,  
  31.             factoryTest != SystemServer.FACTORY_TEST_OFF,  
  32.             onlyCore);  
  33.     boolean firstBoot = false;  
  34.     try {  
  35.         firstBoot = pm.isFirstBoot();  
  36.     } catch (RemoteException e) {  
  37.     }  
  38.   
  39.     ActivityManagerService.setSystemProcess();  
  40.   
  41.     mContentResolver = context.getContentResolver();  
  42.   
  43.     // The AccountManager must come before the ContentService   
  44.     try {  
  45.         Slog.i(TAG, "Account Manager");  
  46.         ServiceManager.addService(Context.ACCOUNT_SERVICE,  
  47.                 new AccountManagerService(context));  
  48.     } catch (Throwable e) {  
  49.         Slog.e(TAG, "Failure starting Account Manager", e);  
  50.     }  
  51.   
  52.     Slog.i(TAG, "Content Manager");  
  53.     ContentService.main(context,  
  54.             factoryTest == SystemServer.FACTORY_TEST_LOW_LEVEL);  
  55.   
  56.     Slog.i(TAG, "System Content Providers");  
  57.     ActivityManagerService.installSystemProviders();  
  58.   
  59.     Slog.i(TAG, "Lights Service");  
  60.     lights = new LightsService(context);  
  61.   
  62.     Slog.i(TAG, "Battery Service");  
  63.     battery = new BatteryService(context, lights);  
  64.     ServiceManager.addService("battery", battery);  
  65.   
  66.     Slog.i(TAG, "Vibrator Service");  
  67.     ServiceManager.addService("vibrator"new VibratorService(context));  
  68.   
  69.     // only initialize the power service after we have started the   
  70.     // lights service, content providers and the battery service.   
  71.     power.init(context, lights, ActivityManagerService.self(), battery);  
  72.   
  73.     Slog.i(TAG, "Alarm Manager");  
  74.     alarm = new AlarmManagerService(context);  
  75.     ServiceManager.addService(Context.ALARM_SERVICE, alarm);  
  76.   
  77.     Slog.i(TAG, "Init Watchdog");  
  78.     Watchdog.getInstance().init(context, battery, power, alarm,  
  79.             ActivityManagerService.self());  
  80.   
  81.     Slog.i(TAG, "Window Manager");  
  82.     wm = WindowManagerService.main(context, power,  
  83.             factoryTest != SystemServer.FACTORY_TEST_LOW_LEVEL,  
  84.             !firstBoot);  
  85.     ServiceManager.addService(Context.WINDOW_SERVICE, wm);  
  86.   
  87.     ActivityManagerService.self().setWindowManager(wm);  
  88.   
  89.     // Skip Bluetooth if we have an emulator kernel   
  90.     // TODO: Use a more reliable check to see if this product should   
  91.     // support Bluetooth - see bug 988521   
  92.     if (SystemProperties.get("ro.kernel.qemu").equals("1")) {  
  93.         Slog.i(TAG, "No Bluetooh Service (emulator)");  
  94.     } else if (factoryTest == SystemServer.FACTORY_TEST_LOW_LEVEL) {  
  95.         Slog.i(TAG, "No Bluetooth Service (factory test)");  
  96.     } else {  
  97.         Slog.i(TAG, "Bluetooth Service");  
  98.         bluetooth = new BluetoothService(context);  
  99.         ServiceManager.addService(BluetoothAdapter.BLUETOOTH_SERVICE, bluetooth);  
  100.         bluetooth.initAfterRegistration();  
  101.         bluetoothA2dp = new BluetoothA2dpService(context, bluetooth);  
  102.         ServiceManager.addService(BluetoothA2dpService.BLUETOOTH_A2DP_SERVICE,  
  103.                                   bluetoothA2dp);  
  104.         bluetooth.initAfterA2dpRegistration();  
  105.   
  106.         int airplaneModeOn = Settings.System.getInt(mContentResolver,  
  107.                 Settings.System.AIRPLANE_MODE_ON, 0);  
  108.         int bluetoothOn = Settings.Secure.getInt(mContentResolver,  
  109.             Settings.Secure.BLUETOOTH_ON, 0);  
  110.         if (airplaneModeOn == 0 && bluetoothOn != 0) {  
  111.             bluetooth.enable();  
  112.         }  
  113.     }  
  114.   
  115. catch (RuntimeException e) {  
  116.     Slog.e("System""******************************************");  
  117.     Slog.e("System""************ Failure starting core service", e);  
  118. }  
        // 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");
            // Only run "core" apps if we're encrypting the device.
            String cryptState = SystemProperties.get("vold.decrypt");
            boolean onlyCore = false;
            if (ENCRYPTING_STATE.equals(cryptState)) {
                Slog.w(TAG, "Detected encryption in progress - only parsing core apps");
                onlyCore = true;
            } else if (ENCRYPTED_STATE.equals(cryptState)) {
                Slog.w(TAG, "Device encrypted - only parsing core apps");
                onlyCore = true;
            }

            pm = PackageManagerService.main(context,
                    factoryTest != SystemServer.FACTORY_TEST_OFF,
                    onlyCore);
            boolean firstBoot = false;
            try {
                firstBoot = pm.isFirstBoot();
            } catch (RemoteException e) {
            }

            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, "Lights Service");
            lights = new LightsService(context);

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

            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.self(), battery);

            Slog.i(TAG, "Alarm Manager");
            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,
                    !firstBoot);
            ServiceManager.addService(Context.WINDOW_SERVICE, wm);

            ActivityManagerService.self().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, "No Bluetooh Service (emulator)");
            } else if (factoryTest == SystemServer.FACTORY_TEST_LOW_LEVEL) {
                Slog.i(TAG, "No Bluetooth Service (factory test)");
            } 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);
                bluetooth.initAfterA2dpRegistration();

                int airplaneModeOn = Settings.System.getInt(mContentResolver,
                        Settings.System.AIRPLANE_MODE_ON, 0);
                int bluetoothOn = Settings.Secure.getInt(mContentResolver,
                    Settings.Secure.BLUETOOTH_ON, 0);
                if (airplaneModeOn == 0 && bluetoothOn != 0) {
                    bluetooth.enable();
                }
            }

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


       并且把这些服务添加到ServiceManager中,以便管理和进程间通讯。
       在该线程后半部分,ActivityManagerService会等待AppWidget、WallPaper、IMM等systemReady后调用自身的systemReady()。
   

 

  1. Slog.i(TAG, "Content Manager");  
  2. ContentService.main(context,  
  3.          factoryTest == SystemServer.FACTORY_TEST_LOW_LEVEL);  
  4.   
  5. ((ActivityManagerService)ServiceManager.getService("activity"))  
  6.          .setWindowManager(wm);  
  7.   
  8.   
  9.  // Skip Bluetooth if we have an emulator kernel   
  10.  // TODO: Use a more reliable check to see if this product should   
  11.  // support Bluetooth - see bug 988521   
  12.  if (SystemProperties.get("ro.kernel.qemu").equals("1")) {  
  13.      Slog.i(TAG, "Registering null Bluetooth Service (emulator)");  
  14.      ServiceManager.addService(BluetoothAdapter.BLUETOOTH_SERVICE, null);  
  15.  } else if (factoryTest == SystemServer.FACTORY_TEST_LOW_LEVEL) {  
  16.      Slog.i(TAG, "Registering null Bluetooth Service (factory test)");  
  17.      ServiceManager.addService(BluetoothAdapter.BLUETOOTH_SERVICE, null);  
  18.  } else {  
  19.      Slog.i(TAG, "Bluetooth Service");  
  20.      bluetooth = new BluetoothService(context);  
  21.      ServiceManager.addService(BluetoothAdapter.BLUETOOTH_SERVICE, bluetooth);  
  22.      bluetooth.initAfterRegistration();  
  23.      bluetoothA2dp = new BluetoothA2dpService(context, bluetooth);  
  24.      ServiceManager.addService(BluetoothA2dpService.BLUETOOTH_A2DP_SERVICE,  
  25.                                bluetoothA2dp);  
  26.   
  27.      int bluetoothOn = Settings.Secure.getInt(mContentResolver,  
  28.          Settings.Secure.BLUETOOTH_ON, 0);  
  29.   
  30.      if (bluetoothOn > 0) {  
  31.          bluetooth.enable();  
  32.      }  
  33.  }  
           Slog.i(TAG, "Content Manager");
           ContentService.main(context,
                    factoryTest == SystemServer.FACTORY_TEST_LOW_LEVEL);

           ((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();
                }
            }

       而在ActivityManagerService的systemReady()最后会执行如下代码:

  1. mMainStack.resumeTopActivityLocked(null);  
mMainStack.resumeTopActivityLocked(null);

       由于Activity管理栈为空,因此启动Launcher。

  1. // Find the first activity that is not finishing.   
  2. ActivityRecord next = topRunningActivityLocked(null);  
  3.   
  4. // Remember how we'll process this pause/resume situation, and ensure   
  5. // that the state is reset however we wind up proceeding.   
  6. final boolean userLeaving = mUserLeaving;  
  7. mUserLeaving = false;  
  8.   
  9. if (next == null) {  
  10.     // There are no more activities!  Let's just start up the   
  11.     // Launcher...   
  12.     if (mMainStack) {  
  13.         return mService.startHomeActivityLocked();  
  14.     }  
  15. }  
        // Find the first activity that is not finishing.
        ActivityRecord next = topRunningActivityLocked(null);

        // Remember how we'll process this pause/resume situation, and ensure
        // that the state is reset however we wind up proceeding.
        final boolean userLeaving = mUserLeaving;
        mUserLeaving = false;

        if (next == null) {
            // There are no more activities!  Let's just start up the
            // Launcher...
            if (mMainStack) {
                return mService.startHomeActivityLocked();
            }
        }


        在startHomeActivityLocked()中创建一个带Category为CATEGORY_HOME的Intent,由此去启动相应Activity,即Launcher。

  1. Intent intent = new Intent(  
  2.     mTopAction,  
  3.     mTopData != null ? Uri.parse(mTopData) : null);  
  4. intent.setComponent(mTopComponent);  
  5.   
  6. if (mFactoryTest != SystemServer.FACTORY_TEST_LOW_LEVEL) {  
  7.     intent.addCategory(Intent.CATEGORY_HOME);  
  8. }  
        Intent intent = new Intent(
            mTopAction,
            mTopData != null ? Uri.parse(mTopData) : null);
        intent.setComponent(mTopComponent);

        if (mFactoryTest != SystemServer.FACTORY_TEST_LOW_LEVEL) {
            intent.addCategory(Intent.CATEGORY_HOME);
        }

       这样,Android系统便启动起来进入到待机界面。

摘自 亨利摩根的专栏

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值