第一步:启动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系统的第一个进程。该进程的相关代码在system\core\init\init.c。在main函数中,有如下代码:



 



[cpp]  view plain copy

 

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



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

 



[cpp]  view plain copy

 


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


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




[cpp]  view plain copy

 



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



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

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



     



    [cpp]  view plain copy

     

    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. "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. }



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



     



    [cpp]  view plain copy

     


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


         最后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函数中有如下代码: 



     



    [cpp]  view plain copy

     

    1. if (0 == strcmp("--zygote", arg)) {  
    2. bool startSystemServer = (i < argc) ?  
    3. "--start-system-server") == 0 : false;  
    4. "zygote");  
    5. "zygote");  
    6. "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. "App process is starting with pid=%d, class=%s.\n",  
    17.           getpid(), runtime.getClassName());  
    18.      runtime.start();  
    19.  }



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



     



    [cpp]  view plain copy

     


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




    [cpp]  view plain copy

     


    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.  }



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

          Policy.isPreloadable()定于如下:



     



    [cpp]  view plain copy

     


    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.  }


          其中EXCLUDED_CLASSES如下定义: 



    [cpp]  view plain copy

    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.  ));


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



     



    [cpp]  view plain copy

     

    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.  ));



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

           最后(还在ZygoteInit.java的main函数里)来通过startSystemServer()启动SystemServer进程。见如下代码:




     



    [cpp]  view plain copy

     


    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. 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)



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

    4. SystemService进程
         SystemService用于创建init.rc定义的服务之外的所有服务。在SystemServer.java (frameworks\base\services\java\com\android\server) 的main()的最后有如下代码:




    [cpp]  view plain copy

     



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



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



       



      [cpp]  view plain copy

       


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


             而system_init()(System_init.cpp (frameworks\base\cmds\system_server\library)文件中)服务初始化创建native层的各个服务:



       



      [cpp]  view plain copy

       



      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. }



            最后通过如下代码:  (android4.1略有区别)



      [cpp]  view plain copy

       


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


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



      [cpp]  view plain copy

       


      1. public static final void init2() {  
      2. "Entered the Android system server!");  
      3. new ServerThread();  
      4. "android.server.ServerThread");  
      5.      thr.start();  
      6.  }


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



       



      [cpp]  view plain copy

       

      1. // Critical services...  
      2. try {  
      3. "Entropy Service");  
      4. "entropy", new EntropyService());  
      5.   
      6. "Power Manager");  
      7. new PowerManagerService();  
      8.     ServiceManager.addService(Context.POWER_SERVICE, power);  
      9.   
      10. "Activity Manager");  
      11.     context = ActivityManagerService.main(factoryTest);  
      12.   
      13. "Telephony Registry");  
      14. "telephony.registry", new TelephonyRegistry(context));  
      15.   
      16.     AttributeCache.init(context);  
      17.   
      18. "Package Manager");  
      19. // Only run "core" apps if we're encrypting the device.  
      20. "vold.decrypt");  
      21. false;  
      22. if (ENCRYPTING_STATE.equals(cryptState)) {  
      23. "Detected encryption in progress - only parsing core apps");  
      24. true;  
      25. else if (ENCRYPTED_STATE.equals(cryptState)) {  
      26. "Device encrypted - only parsing core apps");  
      27. true;  
      28.     }  
      29.   
      30.     pm = PackageManagerService.main(context,  
      31.             factoryTest != SystemServer.FACTORY_TEST_OFF,  
      32.             onlyCore);  
      33. 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. "Account Manager");  
      46.         ServiceManager.addService(Context.ACCOUNT_SERVICE,  
      47. new AccountManagerService(context));  
      48. catch (Throwable e) {  
      49. "Failure starting Account Manager", e);  
      50.     }  
      51.   
      52. "Content Manager");  
      53.     ContentService.main(context,  
      54.             factoryTest == SystemServer.FACTORY_TEST_LOW_LEVEL);  
      55.   
      56. "System Content Providers");  
      57.     ActivityManagerService.installSystemProviders();  
      58.   
      59. "Lights Service");  
      60. new LightsService(context);  
      61.   
      62. "Battery Service");  
      63. new BatteryService(context, lights);  
      64. "battery", battery);  
      65.   
      66. "Vibrator Service");  
      67. "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. "Alarm Manager");  
      74. new AlarmManagerService(context);  
      75.     ServiceManager.addService(Context.ALARM_SERVICE, alarm);  
      76.   
      77. "Init Watchdog");  
      78.     Watchdog.getInstance().init(context, battery, power, alarm,  
      79.             ActivityManagerService.self());  
      80.   
      81. "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. "No Bluetooh Service (emulator)");  
      94. else if (factoryTest == SystemServer.FACTORY_TEST_LOW_LEVEL) {  
      95. "No Bluetooth Service (factory test)");  
      96. else {  
      97. "Bluetooth Service");  
      98. new BluetoothService(context);  
      99.         ServiceManager.addService(BluetoothAdapter.BLUETOOTH_SERVICE, bluetooth);  
      100.         bluetooth.initAfterRegistration();  
      101. 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. "System", "******************************************");  
      117. "System", "************ Failure starting core service", e);  
      118. }



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


       



      [cpp]  view plain copy

       


      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. "Registering null Bluetooth Service (emulator)");  
      14.      ServiceManager.addService(BluetoothAdapter.BLUETOOTH_SERVICE, null);  
      15. else if (factoryTest == SystemServer.FACTORY_TEST_LOW_LEVEL) {  
      16. "Registering null Bluetooth Service (factory test)");  
      17.      ServiceManager.addService(BluetoothAdapter.BLUETOOTH_SERVICE, null);  
      18. else {  
      19. "Bluetooth Service");  
      20. new BluetoothService(context);  
      21.      ServiceManager.addService(BluetoothAdapter.BLUETOOTH_SERVICE, bluetooth);  
      22.      bluetooth.initAfterRegistration();  
      23. 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.  }



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



      1. mMainStack.resumeTopActivityLocked(null);  



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



       



      [cpp]  view plain copy

       


      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. }


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



       



      [cpp]  view plain copy

       


      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. }



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