Android应用进程启动流程

本文基于Android8.0源码。

启动流程图

点击可以看大图

ActivityManagerServiceActivityManagerServiceProcessProcessZygoteProcessZygoteProcessZygoteStateZygoteStateLocalSocketActivityThreadActivityThreadApplicationThreadZygoteInitZygoteInitZygoteServerZygoteConnectionZygoteZygoteRuntimeInitRuntimeInitmainZygoteServerregisterServerSocketnew LocalServerSocket()runSelectLoopwhile(true)Os.poll()startProcessLockedstartstartstartViaZygote组装zygote参数openZygoteSocketIfNeededconnectLocalSocketnew LocalSocketAddressconnectconnectacceptCommandPeercreateNewConnectionZygoteConnectionZygoteStatezygoteSendArgsAndGetResult(BufferedWriter)write(arg)read socketrunOnceforkAndSpecializepidif (pid>0) handleParentProcwrite pidread pidreturn ProcessStartResultreturn ProcessStartResultif (pid==0) handleChildProczygoteInitnativeZygoteInitapplicationInitinvokeStaticMainthrows Zygote.MethodAndArgsCallermain() catch ExceptionmainLooper.prepareMainLooper()new ActivityThread()ApplicationThreadattach(IApplicationThread)attachApplicationBinder.getCallingPid()attachApplicationLockedfind ProcessRecord by pidbindApplicationLooper.loop()