栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

Android系统启动流程

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

Android系统启动流程

Android系统启动流程

文章目录
    • Android系统启动流程
      • 一、概述
      • 三、流程
        • 1、init进程启动
        • 2、zygote进程---app_main.cpp
        • 3、zygote进程---ZygoteInit.java
        • 4、RuntimeInit.zygoteInit
        • 5、SystemServer.java
        • 6、ActivityManagerService

一、概述

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方法:

196  
197      AppRuntime runtime(argv[0], computeArgBlockSize(argc, argv));
198      // Process command line arguments
199      // ignore argv[0]
200      argc--;
201      argv++;
202  
203     
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 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          
652          if (!SystemProperties.getBoolean(PROPERTY_RUNNING_IN_CONTAINER, false)) {
653              capabilities |= posixCapabilitiesAsBits(OsConstants.CAP_BLOCK_SUSPEND);
654          }
655          
			//启动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              
				//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          
			//这个地方会执行两次,子进程走一次,父进程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              
				//向SystemServer 传入参数和classloader
553              RuntimeInit.zygoteInit(parsedArgs.targetSdkVersion, parsedArgs.remainingArgs, cl);
554          }
555  
556          
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          
			//这里将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 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 , intent, null ,
645                  null , aInfo, null , null ,
646                  null , null , null ,
647                  0 , 0 , 0 , null ,
648                  0 , 0 , 0 , null ,
649                  false , false , null ,
650                  null , null );
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的启动,这里只是罗列的跳转节点,细节忽略了,这样我们可以对整体的流程有个大的把握,需要的时候在细细研究里面的细节

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/583149.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号