Android系统启动流程
一、概述
android版本:7.1.2
Android系统的启动从最早的BootLoader->启动linux内核->Android_init进程->android系统的启动过程
启动linux内核之后会启动两个进程一个是kernel_init(pid=1)进程,还有一个是kthreadd(pid=2)进程,
kernel_init最终会启动Android_init进程,
kthreadd最终会启动linux后面的一堆linux内核进程和linux用户进程
我们今天只从Android的init进程说起,这个是android的特有部分,不是linux系统的部分
讲解过程只涉及 重要代码,跳转节点的部分
三、流程
1、init进程启动
我们前面说了linux的linux_init进程会启动android下的init进程
启动文件目录:/android/system/core/init/init.cpp
我们看下main方法:
/*
部分代码省略
*
/
int main(int argc, char** argv) {
605 add_environment("PATH", _PATH_DEFPATH);
606
607 bool is_first_stage = (argc == 1) || (strcmp(argv[1], "--second-stage") != 0);
608
609 // Get the basic filesystem setup we need put together in the initramdisk
610 // on / and then we'll let the rc file figure out the rest.
//创建虚拟文件,比如/proc 这个用户可以查看系统内核信息
611 if (is_first_stage) {
612 mount("tmpfs", "/dev", "tmpfs", MS_NOSUID, "mode=0755");
613 mkdir("/dev/pts", 0755);
614 mkdir("/dev/socket", 0755);
615 mount("devpts", "/dev/pts", "devpts", 0, NULL);
616 #define MAKE_STR(x) __STRING(x)
617 mount("proc", "/proc", "proc", 0, "hidepid=2,gid=" MAKE_STR(AID_READPROC));
618 mount("sysfs", "/sys", "sysfs", 0, NULL);
619 }
620
62
625 open_devnull_stdio();
//klog初始化,这个可以通过这个查看init的日志,地址/dev/__kmsg__ 中查看
626 klog_init();
//设置等级
627 klog_set_level(KLOG_NOTICE_LEVEL);
628
629 NOTICE("init %s started!\n", is_first_stage ? "first stage" : "second stage");
630
631 if (!is_first_stage) {
632 // Indicate that booting is in progress to background fw loaders, etc.
633 close(open("/dev/.booting", O_WRONLY | O_CREAT | O_CLOEXEC, 0000));
634
635 property_init();
636
637 // If arguments are passed both on the command line and in DT,
638 // properties set in DT always have priority over the command-line ones.
639 process_kernel_dt();
640 process_kernel_cmdline();
641
642 // Propagate the kernel variables to internal variables
643 // used by init as well as the current required properties.
644 export_kernel_boot_props();
645 }
646
647 // Set up SELinux, including loading the SELinux policy if we're in the kernel domain.
648 selinux_initialize(is_first_stage);
649
650 // If we're in the kernel domain, re-exec init to transition to the init domain now
651 // that the SELinux policy has been loaded.
652 if (is_first_stage) {
653 if (restorecon("/init") == -1) {
654 ERROR("restorecon failed: %s\n", strerror(errno));
655 security_failure();
656 }
657 char* path = argv[0];
658 char* args[] = { path, const_cast<char*>("--second-stage"), nullptr };
659 if (execv(path, args) == -1) {
660 ERROR("execv(\"%s\") failed: %s\n", path, strerror(errno));
661 security_failure();
662 }
663 }
664
665 // These directories were necessarily created before initial policy load
666 // and therefore need their security context restored to the proper value.
667 // This must happen before /dev is populated by ueventd.
668 NOTICE("Running restorecon...\n");
669 restorecon("/dev");
670 restorecon("/dev/socket");
671 restorecon("/dev/__properties__");
672 restorecon("/property_contexts");
673 restorecon_recursive("/sys");
674
675 epoll_fd = epoll_create1(EPOLL_CLOEXEC);
676 if (epoll_fd == -1) {
677 ERROR("epoll_create1 failed: %s\n", strerror(errno));
678 exit(1);
679 }
680
681 signal_handler_init();
682
683 property_load_boot_defaults();
684 export_oem_lock_status();
685 start_property_service();
686
687 const BuiltinFunctionMap function_map;
688 Action::set_function_map(&function_map);
689 //解析init.rc,
690 Parser& parser = Parser::GetInstance();
691 parser.AddSectionParser("service",std::make_unique<ServiceParser>());
692 parser.AddSectionParser("on", std::make_unique<ActionParser>());
693 parser.AddSectionParser("import", std::make_unique<ImportParser>());
694 parser.ParseConfig("/init.rc");
695
696 ActionManager& am = ActionManager::GetInstance();
697
698 am.QueueEventTrigger("early-init");
699
700 // Queue an action that waits for coldboot done so we know ueventd has set up all of /dev...
701 am.QueueBuiltinAction(wait_for_coldboot_done_action, "wait_for_coldboot_done");
702 // ... so that we can start queuing up actions that require stuff from /dev.
703 am.QueueBuiltinAction(mix_hwrng_into_linux_rng_action, "mix_hwrng_into_linux_rng");
704 am.QueueBuiltinAction(set_mmap_rnd_bits_action, "set_mmap_rnd_bits");
705 am.QueueBuiltinAction(keychord_init_action, "keychord_init");
706 am.QueueBuiltinAction(console_init_action, "console_init");
707
708 // Trigger all the boot actions to get us started.
709 am.QueueEventTrigger("init");
710
711 // Repeat mix_hwrng_into_linux_rng in case /dev/hw_random or /dev/random
712 // wasn't ready immediately after wait_for_coldboot_done
713 am.QueueBuiltinAction(mix_hwrng_into_linux_rng_action, "mix_hwrng_into_linux_rng");
714
715 // Don't mount filesystems or start core system services in charger mode.
716 std::string bootmode = property_get("ro.bootmode");
717 if (bootmode == "charger") {
718 am.QueueEventTrigger("charger");
719 } else {
720 am.QueueEventTrigger("late-init");
721 }
722
723 // Run all property triggers based on current state of the properties.
724 am.QueueBuiltinAction(queue_property_triggers_action, "queue_property_triggers");
725
//作为守护进程,重启其他进程,防止其他进程死掉
726 while (true) {
727 if (!waiting_for_exec) {
728 am.ExecuteOneCommand();
729 restart_processes();
730 }
731
732 int timeout = -1;
733 if (process_needs_restart) {
734 timeout = (process_needs_restart - gettime()) * 1000;
735 if (timeout < 0)
736 timeout = 0;
737 }
738
739 if (am.HasMoreCommands()) {
740 timeout = 0;
741 }
742
743 bootchart_sample(&timeout);
744
745 epoll_event ev;
746 int nr = TEMP_FAILURE_RETRY(epoll_wait(epoll_fd, &ev, 1, timeout));
747 if (nr == -1) {
748 ERROR("epoll_wait failed: %s\n", strerror(errno));
749 } else if (nr == 1) {
750 ((void (*)()) ev.data.ptr)();
751 }
752 }
753
754 return 0;
755 }
756
init总结:
1、创建各种虚拟文件还有设置系统各种属性,比如cpu的 系统的等
2、解析init.rc脚本文件,init.rc里面是各种action、service等的描述,里面包含了各种服务和执行动作
zygote进程就是在这里定义的
3、处理完上面的事情后,自己成为守护进程,当其他进程被杀掉时候,可以重启这个进程,比如netd网络进程被杀了,init通过socket可以将它重启
我们来看下init.rc 中的zygote进程如何定义的
init.rc目录:system/core/rootdir/init.rc
import /init.environ.rc
8 import /init.usb.rc
9 import /init.${ro.hardware}.rc
10 import /init.usb.configfs.rc
11 import /init.${ro.zygote}.rc//zygote的rc文件被导入
12
13 on early-init
14 # Set init and its forked children's oom_adj.
15 write /proc/1/oom_score_adj -1000
16
17 # Disable sysrq from keyboard
18 write /proc/sys/kernel/sysrq 0
19
20 # Set the security context of /adb_keys if present.
21 restorecon /adb_keys
22
23 # Shouldn't be necessary, but sdcard won't start without it. http://b/22568628.
24 mkdir /mnt 0775 root system
25
26 # Set the security context of /postinstall if present.
27 restorecon /postinstall
28
29 start ueventd
30
31 on init
32 sysclktz 0
33
34 # Mix device-specific information into the entropy pool
35 copy /proc/cmdline /dev/urandom
36 copy /default.prop /dev/urandom
37
38 # Backward compatibility.
39 symlink /system/etc /etc
40 symlink /sys/kernel/debug /d
41
42 # Link /vendor to /system/vendor for devices without a vendor partition.
43 symlink /system/vendor /vendor
44
45 # Mount cgroup mount point for cpu accounting
46 mount cgroup none /acct cpuacct
47 mkdir /acct/uid
我们可以看到zygote.rc被导入进去了
zygote.rc:system/core/rootdir/init.{zygote}.rc
{zygote}根据系统的不同,是32位或者64位值也不同
我们就来看下64位的
tian@ubuntu:~/android/system/core/rootdir$ cat init.zygote64.rc
service zygote /system/bin/app_process64 -Xzygote /system/bin --zygote --start-system-server
class main
socket zygote stream 660 root system
onrestart write /sys/android_power/request_state wake
onrestart write /sys/power/state on
onrestart restart audioserver
onrestart restart cameraserver
onrestart restart media
onrestart restart netd
writepid /dev/cpuset/foreground/tasks
文件要点:
/system/bin/app_process64:这个是zygote编译之后的二进制文件,后面的/system/bin --zygote --start-system-server 是调用app_main.cpp的main方法的参数
server:这个是代表启动一个新的进程服务
onrestart write /sys/android_power/request_state wake onrestart write /sys/power/state on onrestart restart audioserver onrestart restart cameraserver onrestart restart media onrestart restart netd
这些是当这些服务挂了,zygote进程会重启
刚刚说到了app_process64是zygote的二进制文件,那么我们看下对应的编译它的android.mk的位置在哪里
目录:/frameworks/base/cmds/app_process/
Android.mk文件
# See b/21032018 for more details.
7 app_process_common_shared_libs := \
8 libwilhelm \
9
10 include $(CLEAR_VARS)
11
12 LOCAL_SRC_FILES:= \
13 app_main.cpp 这个就是要编译的源码文件
14
15 LOCAL_LDFLAGS := -Wl,--version-script,art/sigchainlib/version-script.txt -Wl,--export-dynamic
16
17 LOCAL_SHARED_LIBRARIES := \
18 libdl \
19 libcutils \
20 libutils \
21 liblog \
22 libbinder \
23 libnativeloader \
24 libandroid_runtime \
25 $(app_process_common_shared_libs) \
26
27 LOCAL_WHOLE_STATIC_LIBRARIES := libsigchain
28
29 LOCAL_MODULE:= app_process
30 LOCAL_MULTILIB := both
31 LOCAL_MODULE_STEM_32 := app_process32
32 LOCAL_MODULE_STEM_64 := app_process64
33
34 LOCAL_CFLAGS += -Wall -Werror -Wunused -Wunreachable-code
35
36 include $(BUILD_EXECUTABLE)
37
38 # Create a symlink from app_process to app_process32 or 64
39 # depending on the target configuration.
40 include $(BUILD_SYSTEM)/executable_prefer_symlink.mk
41
42 # Build a variant of app_process binary linked with ASan runtime.
43 # ARM-only at the moment.
44 ifeq ($(TARGET_ARCH),arm)
45
46 include $(CLEAR_VARS)
47
48 LOCAL_SRC_FILES:= \
49 app_main.cpp
50
51 LOCAL_SHARED_LIBRARIES := \
52 libcutils \
53 libutils \
54 liblog \
55 libbinder \
56 libandroid_runtime \
57 $(app_process_common_shared_libs) \
58
59 LOCAL_WHOLE_STATIC_LIBRARIES := libsigchain
60
61 LOCAL_LDFLAGS := -ldl -Wl,--version-script,art/sigchainlib/version-script.txt -Wl,--export-dynamic
62 LOCAL_CPPFLAGS := -std=c++11
63
64 LOCAL_MODULE := app_process__asan
65 LOCAL_MULTILIB := both
66 LOCAL_MODULE_STEM_32 := app_process32
67 LOCAL_MODULE_STEM_64 := app_process64 这个是编译成的二进制文件
68
69 LOCAL_SANITIZE := address
70 LOCAL_CLANG := true
71 LOCAL_MODULE_PATH := $(TARGET_OUT_EXECUTABLES)/asan
72
73 LOCAL_CFLAGS += -Wall -Werror -Wunused -Wunreachable-code
74
75 include $(BUILD_EXECUTABLE)
76
77 endif # ifeq($(TARGET_ARCH),arm)
那么我们知道了app_main.cpp就是下一个入口文件,这个文件运行在zygote进程中,所以这个是文件是zygote进程的入口文件
2、zygote进程—app_main.cpp
int main(int argc, char* const argv[])
187 {
188 /**
xxxx
代码省略
xxxx
**/
196
197 AppRuntime runtime(argv[0], computeArgBlockSize(argc, argv));
198 // Process command line arguments
199 // ignore argv[0]
200 argc--;
201 argv++;
202
203 /**
xxxx
代码省略
xxxx
**/
226 int i;
227 for (i = 0; i < argc; i++) {
228 if (argv[i][0] != '-') {
229 break;
230 }
231 if (argv[i][1] == '-' && argv[i][2] == 0) {
232 ++i; // Skip --.
233 break;
234 }
235 runtime.addOption(strdup(argv[i]));
236 }
237
238 // Parse runtime arguments. Stop at first unrecognized option.
239 bool zygote = false;
240 bool startSystemServer = false;
241 bool application = false;
242 String8 niceName;
243 String8 className;
244
245 ++i; // Skip unused "parent dir" argument.
246 while (i < argc) {
247 const char* arg = argv[i++];
248 if (strcmp(arg, "--zygote") == 0) {
249 zygote = true;
250 niceName = ZYGOTE_NICE_NAME;
251 } else if (strcmp(arg, "--start-system-server") == 0) {
252 startSystemServer = true;
253 } else if (strcmp(arg, "--application") == 0) {
254 application = true;
255 } else if (strncmp(arg, "--nice-name=", 12) == 0) {
256 niceName.setTo(arg + 12);
257 } else if (strncmp(arg, "--", 2) != 0) {
258 className.setTo(arg);
259 break;
260 } else {
261 --i;
262 break;
263 }
264 }
265
266 Vector<String8> args;
267 if (!className.isEmpty()) {
268 // We're not in zygote mode, the only argument we need to pass
269 // to RuntimeInit is the application argument.
270 //
271 // The Remainder of args get passed to startup class main(). Make
272 // copies of them before we overwrite them with the process name.
273 args.add(application ? String8("application") : String8("tool"));
274 runtime.setClassNameAndArgs(className, argc - i, argv + i);
275 } else {
276 // We're in zygote mode.
277 maybeCreateDalvikCache();
278
279 if (startSystemServer) {
280 args.add(String8("start-system-server"));
281 }
282
283 char prop[PROP_VALUE_MAX];
284 if (property_get(ABI_LIST_PROPERTY, prop, NULL) == 0) {
285 LOG_ALWAYS_FATAL("app_process: Unable to determine ABI list from property %s.",
286 ABI_LIST_PROPERTY);
287 return 11;
288 }
289
290 String8 abiFlag("--abi-list=");
291 abiFlag.append(prop);
292 args.add(abiFlag);
293
294 // In zygote mode, pass all remaining arguments to the zygote
295 // main() method.
296 for (; i < argc; ++i) {
297 args.add(String8(argv[i]));
298 }
299 }
300
301 if (!niceName.isEmpty()) {
302 runtime.setArgv0(niceName.string());
303 set_process_name(niceName.string());
304 }
305
306 if (zygote) {
//启动ZygoteInit 这个是第一个java程序,
307 runtime.start("com.android.internal.os.ZygoteInit", args, zygote);
308 } else if (className) {
309 runtime.start("com.android.internal.os.RuntimeInit", args, zygote);
310 } else {
311 fprintf(stderr, "Error: no class name or --zygote supplied.\n");
312 app_usage();
313 LOG_ALWAYS_FATAL("app_process: no class name or --zygote supplied.");
314 return 10;
315 }
316 }
app_main.cpp总结:
1、实例化一个AppRuntime,AppRuntime继承AndroidRuntime,这个是一个android的虚拟器,
2、配置虚拟机的各种参数保存到args中,比如start-system-server,–abi-list=
start-system-server这个是之前zygote.rc中配置的
3、启动虚拟机,如果是zygote模式就加载第一个java程序"com.android.internal.os.ZygoteInit"
执行ZygoteInit的main方法
ZygoteInit这个是zygote进程的的java入口类
3、zygote进程—ZygoteInit.java
目录:frameworks/base/core/java/com/android/internal/os/ZygoteInit.java
直接看main方法
public static void main(String argv[]) {
713 // Mark zygote start. This ensures that thread creation will throw
714 // an error.
715 ZygoteHooks.startZygoteNoThreadCreation();
716
717 try {
718 Trace.traceBegin(Trace.TRACE_TAG_DALVIK, "ZygoteInit");
//启动ddms
719 RuntimeInit.enableDdms();
720 // Start profiling the zygote initialization.
721 SamplingProfilerIntegration.start();
722
723 boolean startSystemServer = false;
724 String socketName = "zygote";//套接字的名字
725 String abiList = null;//abi 列表,比如armeabi,armeabi-v7a,x86
726 for (int i = 1; i < argv.length; i++) {
//这个start-system-server 参数是从前面传过来的,所以这里是true
727 if ("start-system-server".equals(argv[i])) {
728 startSystemServer = true;
729 } else if (argv[i].startsWith(ABI_LIST_ARG)) {
730 abiList = argv[i].substring(ABI_LIST_ARG.length());
731 } else if (argv[i].startsWith(SOCKET_NAME_ARG)) {
//获取socketName,这个名字就是Zygote进程中的socket名字,和其他进程通信 //用的
732 socketName = argv[i].substring(SOCKET_NAME_ARG.length());
733 } else {
734 throw new RuntimeException("Unknown command line argument: " + argv[i]);
735 }
736 }
737
738 if (abiList == null) {
739 throw new RuntimeException("No ABI list supplied.");
740 }
741 //注册socket服务,用于和其他进程通信,比如SystemServer进程的通信
742 registerZygoteSocket(socketName);
743 Trace.traceBegin(Trace.TRACE_TAG_DALVIK, "ZygotePreload");
744 EventLog.writeEvent(LOG_BOOT_PROGRESS_PRELOAD_START,
745 SystemClock.uptimeMillis());
//加载android的类,还有资源,还有opengl,这个是预加载,以后zygote开新进程后,子进 //程会复制这些,已经加载好的资源了,不用重复加载了
746 preload();
747 EventLog.writeEvent(LOG_BOOT_PROGRESS_PRELOAD_END,
748 SystemClock.uptimeMillis());
749 Trace.traceEnd(Trace.TRACE_TAG_DALVIK);
750
751 // Finish profiling the zygote initialization.
752 SamplingProfilerIntegration.writeZygoteSnapshot();
753
754 // Do an initial gc to clean up after startup
755 Trace.traceBegin(Trace.TRACE_TAG_DALVIK, "PostZygoteInitGC");
756 gcAndFinalize();
757 Trace.traceEnd(Trace.TRACE_TAG_DALVIK);
758
759 Trace.traceEnd(Trace.TRACE_TAG_DALVIK);
760
761 // Disable tracing so that forked processes do not inherit stale tracing tags from
762 // Zygote.
763 Trace.setTracingEnabled(false);
764
765 // Zygote process unmounts root storage spaces.
//卸载root存储空间
766 Zygote.nativeUnmountStorageOnInit();
767
768 ZygoteHooks.stopZygoteNoThreadCreation();
769
770 if (startSystemServer) {
//启动SystemServer
771 startSystemServer(abiList, socketName);
772 }
773
774 Log.i(TAG, "Accepting command socket connections");
//zygote 进入死循环 不断接受socket连接,然后处理
//比如启动一个新的app,要开个新进程,就需要zygote通过socket来连接,让zygote开启
775 runSelectLoop(abiList);
776
777 closeServerSocket();//当发生异常,或要关闭zytoge进程时候,需要先关闭套接字
778 } catch (MethodAndArgsCaller caller) {
779 caller.run();
780 } catch (Throwable ex) {
781 Log.e(TAG, "Zygote died with exception", ex);
782 closeServerSocket();
783 throw ex;
784 }
785 }
我们来看下如何启动SystemServer进程的
startSystemServer(abiList, socketName);
private static boolean startSystemServer(String abiList, String socketName)
637 throws MethodAndArgsCaller, RuntimeException {
//下面这些是设置SystemServer需要有的能力
638 long capabilities = posixCapabilitiesAsBits(
639 OsConstants.CAP_IPC_LOCK,
640 OsConstants.CAP_KILL,
641 OsConstants.CAP_NET_ADMIN,
642 OsConstants.CAP_NET_BIND_SERVICE,
643 OsConstants.CAP_NET_BROADCAST,
644 OsConstants.CAP_NET_RAW,
645 OsConstants.CAP_SYS_MODULE,
646 OsConstants.CAP_SYS_NICE,
647 OsConstants.CAP_SYS_PTRACE,
648 OsConstants.CAP_SYS_TIME,
649 OsConstants.CAP_SYS_TTY_CONFIG
650 );
651 /* Containers run without this capability, so avoid setting it in that case */
652 if (!SystemProperties.getBoolean(PROPERTY_RUNNING_IN_CONTAINER, false)) {
653 capabilities |= posixCapabilitiesAsBits(OsConstants.CAP_BLOCK_SUSPEND);
654 }
655 /* Hardcoded command line to start the system server */
//启动com.android.server.SystemServer 传入的参数
656 String args[] = {
657 "--setuid=1000",
658 "--setgid=1000",
659 "--setgroups=1001,1002,1003,1004,1005,1006,1007,1008,1009,1010,1018,1021,1032,3001,3002,3003,3006,3007,3009,3010",
660 "--capabilities=" + capabilities + "," + capabilities,
661 "--nice-name=system_server",
662 "--runtime-args",
663 "com.android.server.SystemServer",
664 };
665 ZygoteConnection.Arguments parsedArgs = null;
666
667 int pid;
668
669 try {
670 parsedArgs = new ZygoteConnection.Arguments(args);
671 ZygoteConnection.applyDebuggerSystemProperty(parsedArgs);
672 ZygoteConnection.applyInvokeWithSystemProperty(parsedArgs);
673
674 /* Request to fork the system server process */
//fork一个SystemServer进程,这个进程的父进程是zygote进程
//这里面会调用native层的fork方法,完成最后后的创建进程动作
675 pid = Zygote.forkSystemServer(
676 parsedArgs.uid, parsedArgs.gid,
677 parsedArgs.gids,
678 parsedArgs.debugFlags,
679 null,
680 parsedArgs.permittedCapabilities,
681 parsedArgs.effectiveCapabilities);
682 } catch (IllegalArgumentException ex) {
683 throw new RuntimeException(ex);
684 }
685
686 /* For child process */
//这个地方会执行两次,子进程走一次,父进程zygote走一次
687 if (pid == 0) {
如果pid==0 是代表子线程了,这个时候已经在systemserver进程中了
688 if (hasSecondZygote(abiList)) {
//如果abi匹配不对 会第二次孵化systemserver进程
689 waitForSecondaryZygote(socketName);
690 }
691 //处理systemserver进程,这里进行初始化后,最后会抛出MethodAndArgsCaller异常
//这个异常是zygoteinit中的main方法会捕获它,在catch里面caller.run()执行,
//run里面最终会通过反射的方式调用了com.android.server.SystemServer中的main方 //法
692 handleSystemServerProcess(parsedArgs);
693 }
694
695 return true;
696 }
我们继续看handleSystemServerProcess
private static void handleSystemServerProcess(
509 ZygoteConnection.Arguments parsedArgs)
510 throws ZygoteInit.MethodAndArgsCaller {
511 //子进程不需要zygote张的socket 所以要先关闭调,因为每个进程都有自己的socket
512 closeServerSocket();
513
514 // set umask to 0077 so new files and directories will default to owner-only permissions.
515 Os.umask(S_IRWXG | S_IRWXO);
516
517 if (parsedArgs.niceName != null) {
518 Process.setArgV0(parsedArgs.niceName);
519 }
520
521 final String systemServerClasspath = Os.getenv("SYSTEMSERVERCLASSPATH");
522 if (systemServerClasspath != null) {
523 performSystemServerDexOpt(systemServerClasspath);
524 }
525 //第一次parsedArgs.invokeWith 都是null的,所以直接走else中
526 if (parsedArgs.invokeWith != null) {
527 String[] args = parsedArgs.remainingArgs;
528 // If we have a non-null system server class path, we'll have to duplicate the
529 // existing arguments and append the classpath to it. ART will handle the classpath
530 // correctly when we exec a new process.
531 if (systemServerClasspath != null) {
532 String[] amendedArgs = new String[args.length + 2];
533 amendedArgs[0] = "-cp";
534 amendedArgs[1] = systemServerClasspath;
535 System.arraycopy(parsedArgs.remainingArgs, 0, amendedArgs, 2, parsedArgs.remainingArgs.length);
536 }
537
538 WrapperInit.execApplication(parsedArgs.invokeWith,
539 parsedArgs.niceName, parsedArgs.targetSdkVersion,
540 VMRuntime.getCurrentInstructionSet(), null, args);
541 } else {
542 ClassLoader cl = null;
543 if (systemServerClasspath != null) {
//创建一个ClassLoader 这个是PathClassLoader
544 cl = createSystemServerClassLoader(systemServerClasspath,
545 parsedArgs.targetSdkVersion);
546
547 Thread.currentThread().setContextClassLoader(cl);
548 }
549
550 /*
551 * Pass the remaining arguments to SystemServer.
552 */
//向SystemServer 传入参数和classloader
553 RuntimeInit.zygoteInit(parsedArgs.targetSdkVersion, parsedArgs.remainingArgs, cl);
554 }
555
556 /* should never reach here */
557 }
4、RuntimeInit.zygoteInit
RuntimeInit.zygoteInit代码
public static final void zygoteInit(int targetSdkVersion, String[] argv, ClassLoader classLoader)
281 throws ZygoteInit.MethodAndArgsCaller {
282 if (DEBUG) Slog.d(TAG, "RuntimeInit: Starting application from zygote");
283
284 Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, "RuntimeInit");
//将java的system.out 还有system.error 重定向到android的log中
//我们的log日志就是在这里初始化的
285 redirectLogStreams();
286 //做一些配置,比如设置SystemServer的全局异常捕获,比如ams挂了抛异常,整个系统要重启
//还有时区清空,重置Android的log
287 commonInit();
//zygote初始化
288 nativeZygoteInit();
289 applicationInit(targetSdkVersion, argv, classLoader);
290 }
applicationInit(targetSdkVersion, argv, classLoader);
private static void applicationInit(int targetSdkVersion, String[] argv, ClassLoader classLoader)
311 throws ZygoteInit.MethodAndArgsCaller {
312 // If the application calls System.exit(), terminate the process
313 // immediately without running any shutdown hooks. It is not possible to
314 // shutdown an Android application gracefully. Among other things, the
315 // Android runtime shutdown hooks close the Binder driver, which can cause
316 // leftover running threads to crash before the process actually exits.
317 nativeSetExitWithoutCleanup(true);
318
319 // We want to be fairly aggressive about heap utilization, to avoid
320 // holding on to a lot of memory that isn't needed.
//设置虚拟器的堆范围是0.75
321 VMRuntime.getRuntime().setTargetHeapUtilization(0.75f);
//设置vm的目标sdk版本
322 VMRuntime.getRuntime().setTargetSdkVersion(targetSdkVersion);
323
324 final Arguments args;
325 try {
//启动systemServer的参数
326 args = new Arguments(argv);
327 } catch (IllegalArgumentException ex) {
328 Slog.e(TAG, ex.getMessage());
329 // let the process exit
330 return;
331 }
332
333 // The end of of the RuntimeInit event (see #zygoteInit).
334 Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);
335
336 // Remaining arguments are passed to the start class's static main
//执行SystemServer的main方法,
337 invokeStaticMain(args.startClass, args.startArgs, classLoader);
338 }
invokeStaticMain(args.startClass, args.startArgs, classLoader);
private static void invokeStaticMain(String className, String[] argv, ClassLoader classLoader)
210 throws ZygoteInit.MethodAndArgsCaller {
211 Class<?> cl;
212
213 try {
//通过反射获取SystemServer的class
//这里的className是"com.android.server.SystemServer"
214 cl = Class.forName(className, true, classLoader);
215 } catch (ClassNotFoundException ex) {
216 throw new RuntimeException(
217 "Missing class when invoking static main " + className,
218 ex);
219 }
220
221 Method m;
222 try {
//获取main方法
223 m = cl.getMethod("main", new Class[] { String[].class });
224 } catch (NoSuchMethodException ex) {
225 throw new RuntimeException(
226 "Missing static main on " + className, ex);
227 } catch (SecurityException ex) {
228 throw new RuntimeException(
229 "Problem getting static main on " + className, ex);
230 }
231
232 int modifiers = m.getModifiers();
233 if (! (Modifier.isStatic(modifiers) && Modifier.isPublic(modifiers))) {
234 throw new RuntimeException(
235 "Main method is not public and static on " + className);
236 }
237
238 /*
239 * This throw gets caught in ZygoteInit.main(), which responds
240 * by invoking the exception's run() method. This arrangement
241 * clears up all the stack frames that were required in setting
242 * up the process.
243 */
//这里将method 和参数传入到MethodAndArgsCaller 异常中,
//这个异常最终在ZygoteInit的main方法中被捕获
244 throw new ZygoteInit.MethodAndArgsCaller(m, argv);
245 }
ZygoteInit中捕获这个异常
public static void main(String argv[]) {
713 /*
。。。。。。省略代码
*/
770 if (startSystemServer) {
771 startSystemServer(abiList, socketName);
772 }
773
774 Log.i(TAG, "Accepting command socket connections");
775 runSelectLoop(abiList);
776
777 closeServerSocket();
778 } catch (MethodAndArgsCaller caller) {
779 caller.run();
780 } catch (Throwable ex) {
781 Log.e(TAG, "Zygote died with exception", ex);
782 closeServerSocket();
783 throw ex;
784 }
785 }
下面是执行过程
可以看出就是执行了method,最终调用了main方法
public void run() {
888 try {
889 mMethod.invoke(null, new Object[] { mArgs });
890 } catch (IllegalAccessException ex) {
891 throw new RuntimeException(ex);
892 } catch (InvocationTargetException ex) {
893 Throwable cause = ex.getCause();
894 if (cause instanceof RuntimeException) {
895 throw (RuntimeException) cause;
896 } else if (cause instanceof Error) {
897 throw (Error) cause;
898 }
899 throw new RuntimeException(ex);
900 }
901 }
902 }
main方法中还有个runSelectLoop(abiList);
这个就是进入死循环,不断的监听其他进程发来的socket消息,然后给他们创建进程,这个和init进程差不多,最后都是成了守护进程了
总结下zygote进程的作用:
1、初始化AndroidRuntime虚拟机,设置参数,然后启动它,------------app_main.cpp
2、Android的虚拟器启动的第一个java程序是ZygoteInit.java 这个应该算是zygote进程的java入口------------app_main.cpp
3、注册Zygote进程的socket,预加载android的类,资源,opengl-----------ZygoteInit.java
4、启动SystemServer进程,最后是通过抛异常,捕获异常的方式,反射执行SystemServer的main方法-----------ZygoteInit.java
5、作为守护进程,runSelectLoop 死循环 不断接受其他进程的socket消息,然后处理,其他的有新创建进程的消息,最终都是通过这个方式启动的,最后执行caller.run
5、SystemServer.java
目录:/frameworks/base/services/java/com/android/server/SystemServer.java
前面说过了zygote最后会通过反射执行到SystemServer.java中的main方法,那我们就来看下
public static void main(String[] args) {
222 new SystemServer().run();
223 }
224
上面的main方法实例化了一个SystemServer对象 然后执行run方法
run方法
private void run() {
233 try {
234 //清空属性
252 if (!SystemProperties.get("persist.sys.language").isEmpty()) {
253 final String languageTag = Locale.getDefault().toLanguageTag();
254
255 SystemProperties.set("persist.sys.locale", languageTag);
256 SystemProperties.set("persist.sys.language", "");
257 SystemProperties.set("persist.sys.country", "");
258 SystemProperties.set("persist.sys.localevar", "");
259 }
260
272 SystemProperties.set("persist.sys.dalvik.vm.lib.2", VMRuntime.getRuntime().vmLibrary());
273
274 // Enable the sampling profiler.
275 if (SamplingProfilerIntegration.isEnabled()) {
276 SamplingProfilerIntegration.start();
277 mProfilerSnapshotTimer = new Timer();
278 mProfilerSnapshotTimer.schedule(new TimerTask() {
279 @Override
280 public void run() {
281 SamplingProfilerIntegration.writeSnapshot("system_server", null);
282 }
283 }, SNAPSHOT_INTERVAL, SNAPSHOT_INTERVAL);
284 }
285
286 // Mmmmmm... more memory!
287 VMRuntime.getRuntime().clearGrowthLimit();
288
289 // The system server has to run all of the time, so it needs to be
290 // as efficient as possible with its memory usage.
291 VMRuntime.getRuntime().setTargetHeapUtilization(0.8f);
292
293 // Some devices rely on runtime fingerprint generation, so make sure
294 // we've defined it before booting further.
295 Build.ensureFingerprintProperty();
296
297 // Within the system server, it is an error to access Environment paths without
298 // explicitly specifying a user.
299 Environment.setUserRequired(true);
300
301 // Within the system server, any incoming Bundles should be defused
302 // to avoid throwing BadParcelableException.
303 BaseBundle.setShouldDefuse(true);
304
305 // Ensure binder calls into the system always run at foreground priority.
306 BinderInternal.disableBackgroundScheduling(true);
307
308 // Increase the number of binder threads in system_server
309 BinderInternal.setMaxThreads(sMaxBinderThreads);
310
311 // Prepare the main looper thread (this thread).
312 android.os.Process.setThreadPriority(
313 android.os.Process.THREAD_PRIORITY_FOREGROUND);
314 android.os.Process.setCanSelfBackground(false);
//开启主线程的looper,这个looper是systemServer进程的主线程looper
315 Looper.prepareMainLooper();
316
317 // Initialize native services.
//加载对应的android_servers.so
318 System.loadLibrary("android_servers");
319
320 // Check whether we failed to shut down last time we tried.
321 // This call may not return.
322 performPendingShutdown();
323
324 // Initialize the system context.
//创建systemcontext
325 createSystemContext();
326
327 // Create the system service manager.
328 mSystemServiceManager = new SystemServiceManager(mSystemContext);
329 mSystemServiceManager.setRuntimeRestarted(mRuntimeRestart);
330 LocalServices.addService(SystemServiceManager.class, mSystemServiceManager);
331 } finally {
332 Trace.traceEnd(Trace.TRACE_TAG_SYSTEM_SERVER);
333 }
334
335 // Start services.
336 try {
337 Trace.traceBegin(Trace.TRACE_TAG_SYSTEM_SERVER, "StartServices");
338 startBootstrapServices();
339 startCoreServices();
340 startOtherServices();
341 } catch (Throwable ex) {
342 Slog.e("System", "******************************************");
343 Slog.e("System", "************ Failure starting system services", ex);
344 throw ex;
345 } finally {
346 Trace.traceEnd(Trace.TRACE_TAG_SYSTEM_SERVER);
347 }
348
349 // For debug builds, log event loop stalls to dropbox for analysis.
350 if (StrictMode.conditionallyEnableDebugLogging()) {
351 Slog.i(TAG, "Enabled StrictMode for system server main thread.");
352 }
353
354 // Loop forever.
355 Looper.loop();
356 throw new RuntimeException("Main thread loop unexpectedly exited");
357 }
上面这个方法主要做了以下几件事
1、startBootstrapServices(); 初始化AMS还有PMS等,最核心的服务,并开始
2、startCoreServices启动其他核心服务
3、startOtherServices 启动其他服务
我面先看下startBootstrapServices
private void startBootstrapServices() {
419
422 Installer installer = mSystemServiceManager.startService(Installer.class);
423 /*
省略代码
*/
//通过反射实例化AMS,并添加到mSystemServiceManager 中管理
425 mActivityManagerService = mSystemServiceManager.startService(
426 ActivityManagerService.Lifecycle.class).getService();
427 mActivityManagerService.setSystemServiceManager(mSystemServiceManager);
428 mActivityManagerService.setInstaller(installer);
// Start the package manager.这个是非常重要的PMS的启动
//这里启动了PMS,PMS的启动重要是做了系统本身的app,用户app的权限检查,app文件扫描,安装app,信息读取,提供给对外的查询等,
//PMS启动完成后,Launcer这个app就已经安装成功了e
463 traceBeginAndSlog("StartPackageManagerService");
464 mPackageManagerService = PackageManagerService.main(mSystemContext, installer,
465 mFactoryTestMode != FactoryTest.FACTORY_TEST_OFF, mOnlyCore);
466 mFirstBoot = mPackageManagerService.isFirstBoot();
467 mPackageManager = mSystemContext.getPackageManager();
468 Trace.traceEnd(Trace.TRACE_TAG_SYSTEM_SERVER);
429 /*
省略代码
*/
430 //设置AMS的服务到serverManager中管理
//我们通过context.getSystemService() 就是在serverManager管理,提供的
496 mActivityManagerService.setSystemProcess();
497
498 // The sensor service needs access to package manager service, app ops
499 // service, and permissions service, therefore we start it after them.
500 startSensorService();
501 }
startCoreServices
private void startCoreServices() {
507 // Tracks the battery level. Requires LightService.
508 mSystemServiceManager.startService(BatteryService.class);
509
510 // Tracks application usage stats.
511 mSystemServiceManager.startService(UsageStatsService.class);
512 mActivityManagerService.setUsageStatsManager(
513 LocalServices.getService(UsageStatsManagerInternal.class));
514
515 // Tracks whether the updatable WebView is in a ready state and watches for update installs.
516 mWebViewUpdateService = mSystemServiceManager.startService(WebViewUpdateService.class);
517 }
这个是启动BatteryService,UsageStatsService,WebViewUpdateService,这些服务
startOtherServices :
代码很长,我简单写下逻辑
第一部分:
try {
758 mSystemServiceManager.startService(LOCK_SETTINGS_SERVICE_CLASS);
759 lockSettings = ILockSettings.Stub.asInterface(
760 ServiceManager.getService("lock_settings"));
761 } catch (Throwable e) {
762 reportWtf("starting LockSettingsService service", e);
763 }
traceBeginAndSlog("StartStatusBarManagerService");
779 try {
780 statusBar = new StatusBarManagerService(context, wm);
781 ServiceManager.addService(Context.STATUS_BAR_SERVICE, statusBar);
782 } catch (Throwable e) {
783 reportWtf("starting StatusBarManagerService", e);
784 }
785 Trace.traceEnd(Trace.TRACE_TAG_SYSTEM_SERVER);
。。。。。。。。。。。。。。。。。。。
添加很多的其他服务
第二部分
调用了所有服务的systemReady方法,如果某个服务没有准备好,就报告错误
Trace.traceBegin(Trace.TRACE_TAG_SYSTEM_SERVER, "MakeVibratorServiceReady");
1226 try {
1227 vibrator.systemReady();
1228 } catch (Throwable e) {
1229 reportWtf("making Vibrator Service ready", e);
1230 }
1231 Trace.traceEnd(Trace.TRACE_TAG_SYSTEM_SERVER);
1232
1233 Trace.traceBegin(Trace.TRACE_TAG_SYSTEM_SERVER, "MakeLockSettingsServiceReady");
1234 if (lockSettings != null) {
1235 try {
1236 lockSettings.systemReady();
1237 } catch (Throwable e) {
1238 reportWtf("making Lock Settings Service ready", e);
1239 }
1240 }
1241 Trace.traceEnd(Trace.TRACE_TAG_SYSTEM_SERVER);
1242
1243 // Needed by DevicePolicyManager for initialization
1244 mSystemServiceManager.startBootPhase(SystemService.PHASE_LOCK_SETTINGS_READY);
1245
1246 mSystemServiceManager.startBootPhase(SystemService.PHASE_SYSTEM_SERVICES_READY);
1247
1248 Trace.traceBegin(Trace.TRACE_TAG_SYSTEM_SERVER, "MakeWindowManagerServiceReady");
1249 try {
1250 wm.systemReady();
1251 } catch (Throwable e) {
1252 reportWtf("making Window Manager Service ready", e);
1253 }
1254 Trace.traceEnd(Trace.TRACE_TAG_SYSTEM_SERVER);
1255
1256 if (safeMode) {
1257 mActivityManagerService.showSafeModeOverlay();
1258 }
最后核心的是AMS的systemReady方法,因为这个方法最终会引导luncher的启动
AMS的systemReady的Runnable 参数里面做了其他服务的systemReady工作
这个应该是有服务启动的先后顺序
mActivityManagerService.systemReady(new Runnable() {
1324 @Override
1325 public void run() {
1326 Slog.i(TAG, "Making services ready");
1327 mSystemServiceManager.startBootPhase(
1328 SystemService.PHASE_ACTIVITY_MANAGER_READY);
1329 Trace.traceBegin(Trace.TRACE_TAG_SYSTEM_SERVER, "PhaseActivityManagerReady");
1330
1331 Trace.traceBegin(Trace.TRACE_TAG_SYSTEM_SERVER, "StartObservingNativeCrashes");
1332 try {
1333 mActivityManagerService.startObservingNativeCrashes();
1334 } catch (Throwable e) {
1335 reportWtf("observing native crashes", e);
1336 }
1337 Trace.traceEnd(Trace.TRACE_TAG_SYSTEM_SERVER);
1338
1339 if (!mOnlyCore) {
1340 Slog.i(TAG, "WebViewFactory preparation");
1341 Trace.traceBegin(Trace.TRACE_TAG_SYSTEM_SERVER, "WebViewFactoryPreparation");
1342 mWebViewUpdateService.prepareWebViewInSystemServer();
1343 Trace.traceEnd(Trace.TRACE_TAG_SYSTEM_SERVER);
1344 }
1345
1346 Trace.traceBegin(Trace.TRACE_TAG_SYSTEM_SERVER, "StartSystemUI");
1347 try {
//发一个intent,让屏幕上弹出一个框,“程序正在启动”
1348 startSystemUi(context);
1349 } catch (Throwable e) {
1350 reportWtf("starting System UI", e);
1351 }
1352 Trace.traceEnd(Trace.TRACE_TAG_SYSTEM_SERVER);
1353 Trace.traceBegin(Trace.TRACE_TAG_SYSTEM_SERVER, "MakeNetworkScoreReady");
1354 try {
1355 if (networkScoreF != null) networkScoreF.systemReady();
1356 } catch (Throwable e) {
1357 reportWtf("making Network Score Service ready", e);
1358 }
1359 Trace.traceEnd(Trace.TRACE_TAG_SYSTEM_SERVER);
1360 Trace.traceBegin(Trace.TRACE_TAG_SYSTEM_SERVER, "MakeNetworkManagementServiceReady");
1361 try {
1362 if (networkManagementF != null) networkManagementF.systemReady();
1363 } catch (Throwable e) {
1364 reportWtf("making Network Managment Service ready", e);
1365 }
1366 Trace.traceEnd(Trace.TRACE_TAG_SYSTEM_SERVER);
1367 Trace.traceBegin(Trace.TRACE_TAG_SYSTEM_SERVER, "MakeNetworkStatsServiceReady");
1368 try {
1369 if (networkStatsF != null) networkStatsF.systemReady();
1370 } catch (Throwable e) {
1371 reportWtf("making Network Stats Service ready", e);
1372 }
1373 Trace.traceEnd(Trace.TRACE_TAG_SYSTEM_SERVER);
1374 Trace.traceBegin(Trace.TRACE_TAG_SYSTEM_SERVER, "MakeNetworkPolicyServiceReady");
1375 try {
1376 if (networkPolicyF != null) networkPolicyF.systemReady();
1377 } catch (Throwable e) {
1378 reportWtf("making Network Policy Service ready", e);
1379 }
1380 Trace.traceEnd(Trace.TRACE_TAG_SYSTEM_SERVER);
1381 Trace.traceBegin(Trace.TRACE_TAG_SYSTEM_SERVER, "MakeConnectivityServiceReady");
1382 try {
1383 if (connectivityF != null) connectivityF.systemReady();
1384 } catch (Throwable e) {
1385 reportWtf("making Connectivity Service ready", e);
1386 }
1387 Trace.traceEnd(Trace.TRACE_TAG_SYSTEM_SERVER);
1388
1389 Watchdog.getInstance().start();
1390
1391 // It is now okay to let the various system services start their
1392 // third party code...
1393 Trace.traceEnd(Trace.TRACE_TAG_SYSTEM_SERVER);
1394 Trace.traceBegin(Trace.TRACE_TAG_SYSTEM_SERVER, "PhaseThirdPartyAppsCanStart");
1395 mSystemServiceManager.startBootPhase(
1396 SystemService.PHASE_THIRD_PARTY_APPS_CAN_START);
1397
1398 try {
1399 if (locationF != null) locationF.systemRunning();
1400 } catch (Throwable e) {
1401 reportWtf("Notifying Location Service running", e);
1402 }
1403 try {
1404 if (countryDetectorF != null) countryDetectorF.systemRunning();
1405 } catch (Throwable e) {
1406 reportWtf("Notifying CountryDetectorService running", e);
1407 }
1408 try {
1409 if (networkTimeUpdaterF != null) networkTimeUpdaterF.systemRunning();
1410 } catch (Throwable e) {
1411 reportWtf("Notifying NetworkTimeService running", e);
1412 }
1413 try {
1414 if (commonTimeMgmtServiceF != null) {
1415 commonTimeMgmtServiceF.systemRunning();
1416 }
1417 } catch (Throwable e) {
1418 reportWtf("Notifying CommonTimeManagementService running", e);
1419 }
1420 try {
1421 if (atlasF != null) atlasF.systemRunning();
1422 } catch (Throwable e) {
1423 reportWtf("Notifying AssetAtlasService running", e);
1424 }
1425 try {
1426 // TODO(BT) Pass parameter to input manager
1427 if (inputManagerF != null) inputManagerF.systemRunning();
1428 } catch (Throwable e) {
1429 reportWtf("Notifying InputManagerService running", e);
1430 }
1431 try {
1432 if (telephonyRegistryF != null) telephonyRegistryF.systemRunning();
1433 } catch (Throwable e) {
1434 reportWtf("Notifying TelephonyRegistry running", e);
1435 }
1436 try {
1437 if (mediaRouterF != null) mediaRouterF.systemRunning();
1438 } catch (Throwable e) {
1439 reportWtf("Notifying MediaRouterService running", e);
1440 }
1441
1442 try {
1443 if (mmsServiceF != null) mmsServiceF.systemRunning();
1444 } catch (Throwable e) {
1445 reportWtf("Notifying MmsService running", e);
1446 }
1447
1448 try {
1449 if (networkScoreF != null) networkScoreF.systemRunning();
1450 } catch (Throwable e) {
1451 reportWtf("Notifying NetworkScoreService running", e);
1452 }
1453 Trace.traceEnd(Trace.TRACE_TAG_SYSTEM_SERVER);
1454 }
1455 });
AMS调用systemReady的runable有2个作用
1、调起其他的service的systemReady
2、startSystemUi(context);
static final void startSystemUi(Context context) {
1459 Intent intent = new Intent();
1460 intent.setComponent(new ComponentName("com.android.systemui",
1461 "com.android.systemui.SystemUIService"));
1462 intent.addFlags(Intent.FLAG_DEBUG_TRIAGED_MISSING);
1463 //Slog.d(TAG, "Starting service: " + intent);
1464 context.startServiceAsUser(intent, UserHandle.SYSTEM);
1465 }
startSystemUi 最终会启动SystemUIService
SystemUIService 这个是什么呢?
SystemUIService 是一个启动系统各种UI的服务
public class SystemUIService extends Service {
27
28 @Override
29 public void onCreate() {
30 super.onCreate();
31 ((SystemUIApplication) getApplication()).startServicesIfNeeded();
32 }
33
34 @Override
35 public IBinder onBind(Intent intent) {
36 return null;
37 }
38
39 @Override
40 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
41 SystemUI[] services = ((SystemUIApplication) getApplication()).getServices();
42 if (args == null || args.length == 0) {
43 for (SystemUI ui: services) {
44 pw.println("dumping service: " + ui.getClass().getName());
45 ui.dump(fd, pw, args);
46 }
47 } else {
48 String svc = args[0];
49 for (SystemUI ui: services) {
50 String name = ui.getClass().getName();
51 if (name.endsWith(svc)) {
52 ui.dump(fd, pw, args);
53 }
54 }
55 }
56 }
57 }
SystemUIApplication代码:
//通过反射调用UI服务
//我们可以看到这个其实是在启动系统的各种UI服务,比如音量UI,系统bar,充电的UI、键盘UI,锁屏UI
//我们定制系统的时候很多都是改这些内容
//每个android版本的变更,给用户视觉上改变最大的也是调整系统的UI
private final Class<?>[] SERVICES = new Class[] {
47 com.android.systemui.tuner.TunerService.class,
48 com.android.systemui.keyguard.KeyguardViewMediator.class,
49 com.android.systemui.recents.Recents.class,
50 com.android.systemui.volume.VolumeUI.class,
51 Divider.class,
52 com.android.systemui.statusbar.SystemBars.class,
53 com.android.systemui.usb.StorageNotification.class,
54 com.android.systemui.power.PowerUI.class,
55 com.android.systemui.media.RingtonePlayer.class,
56 com.android.systemui.keyboard.KeyboardUI.class,
57 com.android.systemui.tv.pip.PipUI.class,
58 com.android.systemui.shortcut.ShortcutKeyDispatcher.class,
59 com.android.systemui.VendorServices.class
60 };
private void startServicesIfNeeded(Class<?>[] services) {
140 if (mServicesStarted) {
141 return;
142 }
143
144 if (!mBootCompleted) {
145 // check to see if maybe it was already completed long before we began
146 // see ActivityManagerService.finishBooting()
147 if ("1".equals(SystemProperties.get("sys.boot_completed"))) {
148 mBootCompleted = true;
149 if (DEBUG) Log.v(TAG, "BOOT_COMPLETED was already sent");
150 }
151 }
152
153 Log.v(TAG, "Starting SystemUI services for user " +
154 Process.myUserHandle().getIdentifier() + ".");
155 final int N = services.length;
156 for (int i=0; i<N; i++) {
157 Class<?> cl = services[i];
158 if (DEBUG) Log.d(TAG, "loading: " + cl);
159 try {
160 Object newService = SystemUIFactory.getInstance().createInstance(cl);
161 mServices[i] = (SystemUI) ((newService == null) ? cl.newInstance() : newService);
162 } catch (IllegalAccessException ex) {
163 throw new RuntimeException(ex);
164 } catch (InstantiationException ex) {
165 throw new RuntimeException(ex);
166 }
167
168 mServices[i].mContext = this;
169 mServices[i].mComponents = mComponents;
170 if (DEBUG) Log.d(TAG, "running: " + mServices[i]);
//启动相关类的服务
171 mServices[i].start();
172
173 if (mBootCompleted) {
174 mServices[i].onBootCompleted();
175 }
176 }
177 mServicesStarted = true;
178 }
我们回到AMS中的systemReady方法 看是怎么启动luncher的
6、ActivityManagerService
systemReady
public void systemReady(final Runnable goingCallback) {
/*
省略代码
中间的逻辑不是我们重点
*/
xxxx
//这个是执行里面的run方法
if (goingCallback != null) goingCallback.run();
//调用这个执行下一步
startHomeActivityLocked(currentUserId, "systemReady");
}
startHomeActivityLocked:
boolean startHomeActivityLocked(int userId, String reason) {
3929 if (mFactoryTest == FactoryTest.FACTORY_TEST_LOW_LEVEL
3930 && mTopAction == null) {
3931 // We are running in factory test mode, but unable to find
3932 // the factory test app, so just sit around displaying the
3933 // error message and don't try to start anything.
3934 return false;
3935 }
3936 Intent intent = getHomeIntent();
//根据intent 查询到ActivityInfo信息
//这个其实是向PMS查询Category类型为HOME的Activity
3937 ActivityInfo aInfo = resolveActivityInfo(intent, STOCK_PM_FLAGS, userId);
3938 if (aInfo != null) {
//设置Component信息
3939 intent.设置Component信息(new ComponentName(aInfo.applicationInfo.packageName, aInfo.name));
3940 // Don't do this if the home app is currently being
3941 // instrumented.
3942 aInfo = new ActivityInfo(aInfo);
//设置applicationinfo信息
3943 aInfo.applicationInfo = getAppInfoForUser(aInfo.applicationInfo, userId);
3944 ProcessRecord app = getProcessRecordLocked(aInfo.processName,
3945 aInfo.applicationInfo.uid, true);
3946 if (app == null || app.instrumentationClass == null) {
3947 intent.setFlags(intent.getFlags() | Intent.FLAG_ACTIVITY_NEW_TASK);
//启动HomeActivity
3948 mActivityStarter.startHomeActivityLocked(intent, aInfo, reason);
3949 }
3950 } else {
3951 Slog.wtf(TAG, "No home screen found for " + intent, new Throwable());
3952 }
3953
3954 return true;
3955 }
getHomeIntent()
Intent getHomeIntent() {
3919 Intent intent = new Intent(mTopAction, mTopData != null ? Uri.parse(mTopData) : null);
3920 intent.setComponent(mTopComponent);
3921 intent.addFlags(Intent.FLAG_DEBUG_TRIAGED_MISSING);
3922 if (mFactoryTest != FactoryTest.FACTORY_TEST_LOW_LEVEL) {
//这个我们应该很熟悉,Intent.CATEGORY_HOME这个是我们launcher对应的activity需 要添加的Category
3923 intent.addCategory(Intent.CATEGORY_HOME);
3924 }
3925 return intent;
3926 }
继续往下看
mActivityStarter.startHomeActivityLocked:
void startHomeActivityLocked(Intent intent, ActivityInfo aInfo, String reason) {
643 mSupervisor.moveHomeStackTaskToTop(HOME_ACTIVITY_TYPE, reason);
644 startActivityLocked(null /*caller*/, intent, null /*ephemeralIntent*/,
645 null /*resolvedType*/, aInfo, null /*rInfo*/, null /*voiceSession*/,
646 null /*voiceInteractor*/, null /*resultTo*/, null /*resultWho*/,
647 0 /*requestCode*/, 0 /*callingPid*/, 0 /*callingUid*/, null /*callingPackage*/,
648 0 /*realCallingPid*/, 0 /*realCallingUid*/, 0 /*startFlags*/, null /*options*/,
649 false /*ignoreTargetSecurity*/, false /*componentSpecified*/, null /*outActivity*/,
650 null /*container*/, null /*inTask*/);
651 if (mSupervisor.inResumeTopActivity) {
652 // If we are in resume section already, home activity will be initialized, but not
653 // resumed (to avoid recursive resume) and will stay that way until something pokes it
654 // again. We need to schedule another resume.
655 mSupervisor.scheduleResumeTopActivities();
656 }
657 }
由于之前PMS已经做了把Launcher app安装的工作了,所以可以启动
这个方法最终会调起Launcher 这个app的启动Activity的onCreate方法,最后launcher 桌面就展示出来了
上面就是android系统的启动
从Init进程到Launcher的启动,这里只是罗列的跳转节点,细节忽略了,这样我们可以对整体的流程有个大的把握,需要的时候在细细研究里面的细节
|