之前这篇,从整体展示了 android 的整个启动流程,为了搞清楚 android 启动到底在代码层面上是如何调用的,将从源代码角度去分析,另所有代码基于 android 4.0 source tree

  all story begin with the init process startup
故事从 init 进程启动开始

init 运行,代码:system/core/init ,入口:system/core/init/init.c main 函数:

 1 int main(int argc, char **argv){ 2      3      ... 4     // 初始化文件系统 5     mkdir("/dev", 0755); 6     mkdir("/proc", 0755); 7     mkdir("/sys", 0755); 8  9     mount("tmpfs", "/dev", "tmpfs", MS_NOSUID, "mode=0755");10     mkdir("/dev/pts", 0755);11     mkdir("/dev/socket", 0755);12     mount("devpts", "/dev/pts", "devpts", 0, NULL);13     mount("proc", "/proc", "proc", 0, NULL);14     mount("sysfs", "/sys", "sysfs", 0, NULL);15 16     ...
17 // 解析 /init.rc 和 /init.$hardware.rc 脚本,其中 $hardware 参数从 /proc/cpuinfo 中读取,模拟器默认是 goldfish18 INFO("reading config file\n");19 init_parse_config_file("/init.rc");20 21 /* pull the kernel commandline and ramdisk properties file in */22 import_kernel_cmdline(0, import_kernel_nv);23 /* don't expose the raw commandline to nonpriv processes */24 chmod("/proc/cmdline", 0440);25 get_hardware_name(hardware, &revision);26 snprintf(tmp, sizeof(tmp), "/init.%s.rc", hardware);27 init_parse_config_file(tmp);28 29 ...30 }

解析 init.rc 文件,主要是由 /system/core/init/init_parser.c 来完成,截取 init.rc 的部分内容如下:(具体 init.rc 文件规范,可参考:/system/core/init/readme.txt)

on early-init    start ueventd# create mountpoints    mkdir /mnt 0775 root system# setup the global environment    export PATH /sbin:/vendor/bin:/system/sbin:/system/bin:/system/xbin# Create cgroup mount points for process groups    mkdir /dev/cpuctl    mount cgroup none /dev/cpuctl cpu    chown system system /dev/cpuctl    chown system system /dev/cpuctl/tasks    chmod 0777 /dev/cpuctl/tasks    write /dev/cpuctl/cpu.shares 1024service zygote /system/bin/app_process -Xzygote /system/bin --zygote --start-system-server    class main    socket zygote stream 666    onrestart write /sys/android_power/request_state wake    onrestart write /sys/power/state on    onrestart restart media    onrestart restart netd

init.rc 使用的是 android init language 规范,它支持4种语句,Actions,Commands,Services,Options:

  • Action 定义方式:
on <trigger>                        #以 on 开头,后面是触发器名字,触发器有3种方式:
<command> #1.只是一个名字,如: on early-init; 
  <command>                #2.name=value 对,如:on property:vold.decrypt=trigger_reset_main;
<command> #3.系统自带的,如:device-added-<path>,device-removed-<path>,service-exited-<name>
<command> #在触发器下一行就是在触发器触发的时候需要执行的命令,如:start...,mkdir,...
  • Command 就是系统支持的一系列命令,如:export,hostname,mkdir,mount,等等,其中一部分是 linux 命令,还有一些是 android 添加的,如:class_start <serviceclass>: 启动服务,
    class_stop <serviceclass>:关闭服务,等等。
  • Service 定义方式:
service <name> <pathname> [ <argument> ]*   <option>   <option>   ...#如:启动 android 最重要的服务 zygote service zygote /system/bin/app_process -Xzygote /system/bin --zygote --start-system-server    class main    socket zygote stream 666    onrestart write /sys/android_power/request_state wake    onrestart write /sys/power/state on    onrestart restart media    onrestart restart netd
  • Option 是针对 Service 的选项,如:
setenv <name> <value>                           在启动服务时设置环境变量user <username>                                 运行服务之前切换用户oneshot                                         如果服务已经存在,将不再启动class <classname>                               为服务设置名字,具有相同名字的服务将一起启动或者关闭
socket <name> <type> <perm> [ <user> [ <group> ] ]      创建以<name>命名的 socket,并将该 socket 的文件描述符返回给启动的服务
onrestart <command>                        在服务重新启动的时候执行<command>

在对 init.rc 和 init.$hardware.rc 2个文件按照 android init language 规范进行解析完成以后,会将所有将要执行的命令放到一个大的 action_list 当中,然后紧跟上面解析 init 文件下面:

  // 寻找 early-init 触发器,加到 action_queue 中
action_for_each_trigger("early-init", action_add_queue_tail);
// 添加系统的一些触发器   queue_builtin_action(wait_for_coldboot_done_action,
"wait_for_coldboot_done"); queue_builtin_action(property_init_action, "property_init"); queue_builtin_action(keychord_init_action, "keychord_init"); queue_builtin_action(console_init_action, "console_init"); queue_builtin_action(set_init_properties_action, "set_init_properties"); /* execute all the boot actions to get us started */ action_for_each_trigger("init", action_add_queue_tail); /* skip mounting filesystems in charger mode */ if (strcmp(bootmode, "charger") != 0) { action_for_each_trigger("early-fs", action_add_queue_tail); action_for_each_trigger("fs", action_add_queue_tail); action_for_each_trigger("post-fs", action_add_queue_tail); action_for_each_trigger("post-fs-data", action_add_queue_tail); } queue_builtin_action(property_service_init_action, "property_service_init"); queue_builtin_action(signal_init_action, "signal_init"); queue_builtin_action(check_startup_action, "check_startup"); if (!strcmp(bootmode, "charger")) { action_for_each_trigger("charger", action_add_queue_tail); } else { action_for_each_trigger("early-boot", action_add_queue_tail); action_for_each_trigger("boot", action_add_queue_tail); } /* run all property triggers based on current state of the properties */ queue_builtin_action(queue_property_triggers_action, "queue_propety_triggers");    ...
  
  // 按顺序执行 action_queue 中的命令 for(;;) { int nr, i, timeout = -1; execute_one_command(); restart_processes(); ... }

从 action_list 中找到制定触发器,将触发器需要执行的命令添加到 action_queue 中,最后按顺序执行 action_queue 中的命令来完成初始化,初始化除了设置一些环境变量和创建文件夹以外,

更多的是关心 Service 的启动,init 文件里面的服务有2种,1种是 class core,还有1种是 class main,对 init.rc 的 service 按照 class <name> 分类如下:

class core:service ueventd /sbin/ueventdservice console /system/bin/shservice adbd /sbin/adbdservice servicemanager /system/bin/servicemanagerservice vold /system/bin/voldclass main:service netd /system/bin/netdservice debuggerd /system/bin/debuggerdservice ril-daemon /system/bin/rildservice surfaceflinger /system/bin/surfaceflingerservice zygote /system/bin/app_process -Xzygote /system/bin --zygote --start-system-serverservice drm /system/bin/drmserverservice media /system/bin/mediaserverservice bootanim /system/bin/bootanimationservice dbus /system/bin/dbus-daemon --system --noforkservice bluetoothd /system/bin/bluetoothd -nservice installd /system/bin/installdservice flash_recovery /system/etc/install-recovery.shservice racoon /system/bin/racoonservice mtpd /system/bin/mtpdservice keystore /system/bin/keystore /data/misc/keystoreservice dumpstate /system/bin/dumpstate -s

service ueventd:会读取 /ueventd.rc 和 /ueventd.$hadrware.rc 文件,解析跟 init.rc 解析类似,主要是对文件系统的权限和用户进行设置:(代码:system/core/init/ueventd.c)

#目录 权限 user group

/dev/null 0666 root root/dev/zero 0666 root root

在 class core 服务启动以后, class main 开始启动,service zygote 是标志进入 android 最重要的一个服务,服务名字 zygote,实际上启动的是 app_process,(代码:frameworks/base/cmds/app_process/app_main.cpp)

int main(int argc, const char* const argv[]){    // These are global variables in ProcessState.cpp    mArgC = argc;    mArgV = argv;    mArgLen = 0;

//读取参数,传递的参数就是 init.rc 中启动时传入的: -Xzygote /system/bin --zygote --start-system-server
for (int i=0; i<argc; i++) { mArgLen += strlen(argv[i]) + 1; } mArgLen--; AppRuntime runtime; const char* argv0 = argv[0]; //-Xzygote // Process command line arguments // ignore argv[0] argc--; //之前是 4, 现在是 3 argv++; //argv 指向 argv[1] // Everything up to '--' or first non '-' arg goes to the vm  
   // i = 0,代码:frameworks/base/core/jni/AndroidRuntime.cpp int i = runtime.addVmArguments(argc, argv); // Parse runtime arguments. Stop at first unrecognized option. bool zygote = false; bool startSystemServer = false; bool application = false; const char* parentDir = NULL; const char* niceName = NULL; const char* className = NULL; while (i < argc) { const char* arg = argv[i++]; if (!parentDir) { parentDir = arg;               //parentDir = /system/bin } else if (strcmp(arg, "--zygote") == 0) { //当 i = 2,arg = argv[1] 时,即:--zygote zygote = true;                 niceName = "zygote"; } else if (strcmp(arg, "--start-system-server") == 0) { startSystemServer = true; } else if (strcmp(arg, "--application") == 0) { application = true; } else if (strncmp(arg, "--nice-name=", 12) == 0) { niceName = arg + 12; } else { className = arg; break; } } if (niceName && *niceName) { setArgv0(argv0, niceName); set_process_name(niceName); } runtime.mParentDir = parentDir; if (zygote) {
     // zygote = true,启动 com.android.internal.os.ZygoteInit,参数:startSystemServer runtime.start(
"com.android.internal.os.ZygoteInit",startSystemServer ? "start-system-server" : ""); } else if (className) { // Remainder of args get passed to startup class main() runtime.mClassName = className; runtime.mArgC = argc - i; runtime.mArgV = argv + i; runtime.start("com.android.internal.os.RuntimeInit", application ? "application" : "tool"); } else { fprintf(stderr, "Error: no class name or --zygote supplied.\n"); app_usage(); LOG_ALWAYS_FATAL("app_process: no class name or --zygote supplied."); return 10; }}

检测传入参数,将调用 :

 runtime.start("com.android.internal.os.ZygoteInit",startSystemServer ? "start-system-server" : "");

runtime 的代码:frameworks/base/core/jni/AndroidRuntime.cpp,start 函数会启动虚拟机,执行com.android.internal.os.ZygoteInit 该类的 main 函数,并传入参数:start-system-server:

void AndroidRuntime::start(const char* className, const char* options){    LOGD("\n>>>>>> AndroidRuntime START %s <<<<<<\n",            className != NULL ? className : "(unknown)");
...
/* start the virtual machine */
//设置 dalvik 虚拟机参数,创建并启动虚拟机
JNIEnv* env; if (startVm(&mJavaVM, &env) != 0) { return; } onVmCreated(env); /* * Register android functions. */ if (startReg(env) < 0) { LOGE("Unable to register all android natives\n"); return; } ...
/* * Start VM. This thread becomes the main thread of the VM, and will * not return until the VM exits. */
//将类名 com.xxx.xxx 转换成 com/xxx/xxx char* slashClassName = toSlashClassName(className); jclass startClass = env->FindClass(slashClassName); if (startClass == NULL) { LOGE("JavaVM unable to locate class '%s'\n", slashClassName); /* keep going */ } else {
     // jni 调用 java 方法,获取对应类名的 class,然后调用静态 main 方法 jmethodID startMeth
= env->GetStaticMethodID(startClass, "main", "([Ljava/lang/String;)V"); if (startMeth == NULL) { LOGE("JavaVM unable to find main() in '%s'\n", className); /* keep going */ } else { env->CallStaticVoidMethod(startClass, startMeth, strArray); } } free(slashClassName); LOGD("Shutting down VM\n"); if (mJavaVM->DetachCurrentThread() != JNI_OK) LOGW("Warning: unable to detach main thread\n"); if (mJavaVM->DestroyJavaVM() != 0) LOGW("Warning: VM did not shut down cleanly\n");}

ZygoteInit 类 main 函数:

 public static void main(String argv[]) {        try {            // Start profiling the zygote initialization.            SamplingProfilerIntegration.start();       
//注册 socket server registerZygoteSocket(); EventLog.writeEvent(LOG_BOOT_PROGRESS_PRELOAD_START, SystemClock.uptimeMillis());

//预加载资源,有 preloadClasses() 和 preloadResources(),加载的开始和结束会被记录在 /system/etc/event-log-tags 文件中 preload(); 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("start-system-server")) {
          //在调用 Zygote 的 main 函数时,已经传入 start-system-server,调用 startSystemServer() startSystemServer(); }
else if (!argv[1].equals("")) { throw new RuntimeException(argv[0] + USAGE_STRING); } Log.i(TAG, "Accepting command socket connections"); if (ZYGOTE_FORK_MODE) { runForkMode(); } else {
         //上面通过 registerZygoteSocket() 函数调用注册的 server scocket,会启动,开始监听 Zygote 连接 runSelectLoopMode(); }         closeServerSocket(); }
catch (MethodAndArgsCaller caller) { caller.run(); } catch (RuntimeException ex) { Log.e(TAG, "Zygote died with exception", ex); closeServerSocket(); throw ex; } }

那 startSystemServer 到底又做了什么东东呢,以及最后系统如何发出ACTION_BOOT_COMPLETED 广播的呢,且听下回分解。 -):

上回说到,开始调用 ZygoteInit main 函数,main 函数:

  • registerZygoteServer:注册一个 zygote server socket,所有来自客户端的连接都通过 socket 方式连接;
  • preload:预加载系统的类库和资源,这样其他程序启动将不再加载系统资源,只需加载自己程序的资源,这样就达到系统资源在程序之间共享;
  • startSystemServer:
 private static boolean startSystemServer()            throws MethodAndArgsCaller, RuntimeException {        /* Hardcoded command line to start the system server */
     //命令行参数,包括:uid,gid,group,process_name,process class String args[] = { "--setuid=1000", "--setgid=1000", "--setgroups=1001,1002,1003,1004,1005,1006,1007,1008,1009,1010,1018,3001,3002,3003,3006,3007", "--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); ZygoteConnection.applyDebuggerSystemProperty(parsedArgs); ZygoteConnection.applyInvokeWithSystemProperty(parsedArgs); /* Request to fork the system server process */
       //从 zygote 进程派生一个新的进程,fork 可参考:http://linux.die.net/man/2/fork ,不同的是该进程结束时,也会让 zygote 进程结束
      //所以这里,会返回2次,一次返回的是 zygote 进程的 pid ,值大于0;一次返回的是子进程 pid,值等于0
// fork 返回在 zygote 进程返回的子进程 pid,非0,在子进程中返回0
pid
= Zygote.forkSystemServer( parsedArgs.uid, parsedArgs.gid, parsedArgs.gids, parsedArgs.debugFlags, null, parsedArgs.permittedCapabilities, parsedArgs.effectiveCapabilities); } catch (IllegalArgumentException ex) { throw new RuntimeException(ex); } /* For child process */
    //zygote 进程 pid 非0,直接返回,而子进程 pid = 0,对子进程进行设置 if (pid == 0) { handleSystemServerProcess(parsedArgs); } return true; }

而 handleSystemServerProcess 将启动com.android.server.SystemServer:

private static void handleSystemServerProcess(            ZygoteConnection.Arguments parsedArgs)            throws ZygoteInit.MethodAndArgsCaller {
//因为有 zygote 监听 socket,所以 system server 不监听 socket 连接,此处关闭 closeServerSocket();
// set umask to 0077 so new files and directories will default to owner-only permissions. FileUtils.setUMask(FileUtils.S_IRWXG | FileUtils.S_IRWXO);     
     //设置进程名字,即从命令行参数获取的:system_server 
if (parsedArgs.niceName != null) { Process.setArgV0(parsedArgs.niceName); } if (parsedArgs.invokeWith != null) { WrapperInit.execApplication(parsedArgs.invokeWith, parsedArgs.niceName, parsedArgs.targetSdkVersion, null, parsedArgs.remainingArgs); } else { /* * Pass the remaining arguments to SystemServer. */
       /* zygoteInit -> applicationInit:设置 sdktarget 版本 -> invokeStaticMain:得到 com.android.server.SystemServer main 方法 -> ZygoteInit.MethodAndArgsCaller
        *
ZygoteInit.MethodAndArgsCaller 方法抛出异常 MethodAndArgsCaller,跳过了在 startSystemServer 下面的代码:
* if (ZYGOTE_FORK_MODE) {
        * runForkMode();
        * } else {
        * runSelectLoopMode();
        * }
        */
       RuntimeInit.zygoteInit(parsedArgs.targetSdkVersion, parsedArgs.remainingArgs); } /* should never reach here */
     }

在对MethodAndArgsCaller 异常 catch 语句里,直接调用了com.android.server.SystemServer main 方法,而 zygote 进程因为 pid 不为0,执行 runSelectLoopMode 方法:

 private static void runSelectLoopMode() throws MethodAndArgsCaller {        ArrayList<FileDescriptor> fds = new ArrayList();        ArrayList<ZygoteConnection> peers = new ArrayList();        FileDescriptor[] fdArray = new FileDescriptor[4];        fds.add(sServerSocket.getFileDescriptor());        peers.add(null);        int loopCount = GC_LOOP_COUNT;
     //一直循环
while (true) { int index; /* * Call gc() before we block in select(). * It's work that has to be done anyway, and it's better * to avoid making every child do it. It will also * madvise() any free memory as a side-effect. * * Don't call it every time, because walking the entire * heap is a lot of overhead to free a few hundred bytes. */ if (loopCount <= 0) { gc(); loopCount = GC_LOOP_COUNT; } else { loopCount--; }       //采用非阻塞方式,等待并取出 zygote 连接 try { fdArray = fds.toArray(fdArray); index = selectReadable(fdArray); } catch (IOException ex) { throw new RuntimeException("Error in select()", ex); }
//selectReadable 返回值小于0 ,有错误发生;值等于0,有新的连接,加到 list 中;值大于0,处理当前连接
if (index < 0) { throw new RuntimeException("Error in select()"); } else if (index == 0) { ZygoteConnection newPeer = acceptCommandPeer(); peers.add(newPeer); fds.add(newPeer.getFileDesciptor()); } else { boolean done; done = peers.get(index).runOnce(); if (done) { peers.remove(index); fds.remove(index); } } } }

在 zygote 进程等待连接的同时,com.android.server.SystemServer 已经启动:

    native public static void init1(String[] args);    public static void main(String[] args) {     ...
     //加载 jni ,init1 是本地方法 System.loadLibrary(
"android_servers");
     // init1 -> frameworks/base/services/jni/com_android_server_SystemServer.cpp :: android_server_SystemServer_init1 ->
    // frameworks/base/cmds/system_server/library/system_init.cpp :: system_init init1(args); }
   // init1 将回调 init2 方法
public static final void init2() { Slog.i(TAG, "Entered the Android system server!"); Thread thr = new ServerThread(); thr.setName("android.server.ServerThread"); thr.start(); }

init1 方法最终调用的是 system_init 方法(代码:frameworks/base/cmds/system_server/library/system_init.cpp)

extern "C" status_t system_init(){    LOGI("Entered system_init()");    sp<ProcessState> proc(ProcessState::self());      sp<IServiceManager> sm = defaultServiceManager();    LOGI("ServiceManager: %p\n", sm.get());    sp<GrimReaper> grim = new GrimReaper();    sm->asBinder()->linkToDeath(grim, grim.get(), 0);  
 //初始化 SurfaceFlinger 和传感器
char propBuf[PROPERTY_VALUE_MAX]; property_get("system_init.startsurfaceflinger", propBuf, "1"); if (strcmp(propBuf, "1") == 0) { // Start the SurfaceFlinger SurfaceFlinger::instantiate(); } property_get("system_init.startsensorservice", propBuf, "1"); if (strcmp(propBuf, "1") == 0) { // Start the sensor service SensorService::instantiate(); } // And now start the Android runtime. We have to do this bit // of nastiness because the Android runtime initialization requires // some of the core system services to already be started. // All other servers should just start the Android runtime at // the beginning of their processes's main(), before calling // the init function. LOGI("System server: starting Android runtime.\n"); AndroidRuntime* runtime = AndroidRuntime::getRuntime();  
   //回调 com.android.server.SystemServer init2 方法 LOGI(
"System server: starting Android services.\n"); JNIEnv* env = runtime->getJNIEnv(); if (env == NULL) { return UNKNOWN_ERROR; } jclass clazz = env->FindClass("com/android/server/SystemServer"); if (clazz == NULL) { return UNKNOWN_ERROR; } jmethodID methodId = env->GetStaticMethodID(clazz, "init2", "()V"); if (methodId == NULL) { return UNKNOWN_ERROR; } env->CallStaticVoidMethod(clazz, methodId);  
  //启动线程池,为 binder 服务 LOGI(
"System server: entering thread pool.\n"); ProcessState::self()->startThreadPool(); IPCThreadState::self()->joinThreadPool(); LOGI("System server: exiting thread pool.\n"); return NO_ERROR;}

init2 启动 ServerThread 线程,它会启动 android 系统所有的服务:

 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);        String factoryTestStr = SystemProperties.get("ro.factorytest");        int factoryTest = "".equals(factoryTestStr) ? SystemServer.FACTORY_TEST_OFF                : Integer.parseInt(factoryTestStr);      
     //初始化服务,如:网络服务,Wifi服务,蓝牙,电源,等等,初始化完成以后,加到 ServiceManager 中,
//所以我们用 Context.getSystemService (String name) 才获取到相应的服务
LightsService lights
= null; PowerManagerService power = null; BatteryService battery = null; AlarmManagerService alarm = null; NetworkManagementService networkManagement = null; NetworkStatsService networkStats = null; NetworkPolicyManagerService networkPolicy = null; ConnectivityService connectivity = null; WifiP2pService wifiP2p = null; WifiService wifi = null; IPackageManager pm = null; Context context = null; WindowManagerService wm = null; BluetoothService bluetooth = null; BluetoothA2dpService bluetoothA2dp = null; DockObserver dock = null; UsbService usb = null; UiModeManagerService uiMode = null; RecognitionManagerService recognition = null; ThrottleService throttle = null; NetworkTimeUpdateService networkTimeUpdater = null; // Critical services... try { Slog.i(TAG, "Entropy Service"); ServiceManager.addService("entropy", new EntropyService());
Slog.i(TAG, "Package Manager"); // Only run "core" apps if we're encrypting the device.
......      
      //ActivityManagerService 是 android 系统最核心的服务之一 

//1.系统 context 的初始化,设置默认主题android.R.style.Theme_Holo
//2.设置进程名字为system_process
//3.初始化ActivityStack

context = ActivityManagerService.main(factoryTest);

//往 service manager 里面添加一些服务,如:activity,meminfo,cupinfo,permission
ActivityManagerService.setSystemProcess();

//安装系统 content provider
Slog.i(TAG, "System Content Providers");
ActivityManagerService.installSystemProviders();

//设置 windows manager

ActivityManagerService.self().setWindowManager(wm);          

            ......
// 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.
    
     //代码到这里,表明系统已经就绪,可以运行第3方代码
ActivityManagerService.self().systemReady(new Runnable() { public void run() { Slog.i(TAG, "Making services ready");         // systemui 是 3.0 以后添加的,因为没有物理键,提供虚拟键  startSystemUi(contextF);

         //诸多服务开始启动
try { if (batteryF != null) batteryF.systemReady(); } catch (Throwable e) { reportWtf("making Battery Service ready", e); } try { if (networkManagementF != null) networkManagementF.systemReady(); } catch (Throwable e) { reportWtf("making Network Managment Service ready", e); } ...... } }); // 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!"); }

而要执行ActivityManagerService.self().systemReady(new Runnable() ...) 参数里面 Runnable 的 run 方法,还必须等到ActivityManagerService systemReady:

public void systemReady(final Runnable goingCallback) {        synchronized(this) {
       //mSystemReady = false
if (mSystemReady) { if (goingCallback != null) goingCallback.run(); return; } // Check to see if there are any update receivers to run. if (!mDidUpdate) { if (mWaitingUpdate) { return; }
         //检测是否有 ACTION_PRE_BOOT_COMPLETED register,该广播在 ACTION_BOOT_COMPLETED 前发出 Intent intent
= new Intent(Intent.ACTION_PRE_BOOT_COMPLETED); List<ResolveInfo> ris = null; try { ris = AppGlobals.getPackageManager().queryIntentReceivers( intent, null, 0); } catch (RemoteException e) { } if (ris != null) { for (int i=ris.size()-1; i>=0; i--) {
              //检测广播注册是否是系统程序
if ((ris.get(i).activityInfo.applicationInfo.flags &ApplicationInfo.FLAG_SYSTEM) == 0) { ris.remove(i); } } intent.addFlags(Intent.FLAG_RECEIVER_BOOT_UPGRADE); ArrayList<ComponentName> lastDoneReceivers = readLastDonePreBootReceivers(); final ArrayList<ComponentName> doneReceivers = new ArrayList<ComponentName>(); for (int i=0; i<ris.size(); i++) { ActivityInfo ai = ris.get(i).activityInfo; ComponentName comp = new ComponentName(ai.packageName, ai.name); if (lastDoneReceivers.contains(comp)) { ris.remove(i); i--; } } for (int i=0; i<ris.size(); i++) { ActivityInfo ai = ris.get(i).activityInfo; ComponentName comp = new ComponentName(ai.packageName, ai.name); doneReceivers.add(comp); intent.setComponent(comp); IIntentReceiver finisher = null; if (i == ris.size()-1) { finisher = new IIntentReceiver.Stub() { public void performReceive(Intent intent, int resultCode, String data, Bundle extras, boolean ordered, boolean sticky) { // The raw IIntentReceiver interface is called // with the AM lock held, so redispatch to // execute our code without the lock. mHandler.post(new Runnable() { public void run() { synchronized (ActivityManagerService.this) { mDidUpdate = true; } writeLastDonePreBootReceivers(doneReceivers); showBootMessage(mContext.getText( R.string.android_upgrading_complete), false);
                          //如果有 ACTION_PRE_BOOT_COMPLETED,在处理完广播 receive 以后 ,还会再次走 systemRead(goingCallback) systemReady(goingCallback); } }); } }; } Slog.i(TAG,
"Sending system update to: " + intent.getComponent()); broadcastIntentLocked(null, null, intent, null, finisher, 0, null, null, null, true, false, MY_PID, Process.SYSTEM_UID); if (finisher != null) { mWaitingUpdate = true; } } } if (mWaitingUpdate) { return; } mDidUpdate = true; } mSystemReady = true;
       //mStartRunning 已经在 ActivityManagerService.main(int factoryTest) 设置成 true
if (!mStartRunning) { return; } }
     ......
retrieveSettings();    
  
     //开始执行 runnable 的 run 方法,执行完成以后,系统就绪
if (goingCallback != null) goingCallback.run(); synchronized (this) { if (mFactoryTest != SystemServer.FACTORY_TEST_LOW_LEVEL) { try { List apps = AppGlobals.getPackageManager(). getPersistentApplications(STOCK_PM_FLAGS); if (apps != null) { int N = apps.size(); int i; for (i=0; i<N; i++) { ApplicationInfo info = (ApplicationInfo)apps.get(i); if (info != null && !info.packageName.equals("android")) { addAppLocked(info); } } } } catch (RemoteException ex) { // pm is in same process, this will never happen. } } // Start up initial activity. mBooting = true; try { if (AppGlobals.getPackageManager().hasSystemUidErrors()) { Message msg = Message.obtain(); msg.what = SHOW_UID_ERROR_MSG; mHandler.sendMessage(msg); } } catch (RemoteException e) { }       
       //恢复 top activity,因为现在没有任何启动的 activity, 将会启动 startHomeActivityLocked,启动 HOME   mMainStack.resumeTopActivityLocked(
null); } }

HOME 启动以后,ActivityManagerService 中 finishBooting 方法会发出 Intent.ACTION_BOOT_COMPLETED 广播,调用该方法的地方有很多,resume activity 的时候或者出错的时候,

调用一次以后就不再调用。

至此 android 就完成了整个启动工作,整个流程可以用下图简洁表示:


更多相关文章

  1. Android开机启动Service或Activity或应用
  2. Xamarin Mono For Android(安卓)4.6.07004看不到新建android
  3. Android源码阅读分析:从Activity开始(一)——启动流程
  4. Activity的启动
  5. Android原生SpeechRecognizer(语音识别)
  6. Activity的四种启动模式和onNewIntent()
  7. ANDROID问题总结
  8. Android(安卓)为模拟器安装其他软件
  9. Android:Service之远程服务和AIDL的创建

随机推荐

  1. ArcGIS API for Android(安卓)案例教程 1
  2. android 利用ksoap2方式连接webservice
  3. adb shell 命令详解
  4. android TextView 容纳不下内容,让字向左
  5. android开发文档中的一个小错误
  6. Android图文详解属性动画
  7. Android(安卓)软件盘回车键修改
  8. Android(安卓)支持多屏幕机制
  9. Activity对象的onCreate方法真是Android
  10. android 简单动画之 animtion