源码跟踪之启动流程:从ZygoteInit到onCreate

Instrumentation源码阅读方法可参考:Android源码阅读技巧

SDK版本名称: Pie
API Level: 28

一、源码调用时序图

1. Activity的启动流程

说明:其中ActivityThread中执行的scheduleTransaction方法在其父类ClientTransactionHandler中,发送了ActivityThread.H.EXECUTE_TRANSACTIONActivityThread接收后执行了LaunchActivityItem#execute()

Activity的启动流程.jpg

2.ActivityManagerService的启动流程

说明:其中RunnableInit通过类名反射了main方法,封装成Runnable返回,最终在ZygoteInit#main中执行run()

ActivityManagerService的启动流程.jpg

3.ActivityThread的启动流程

说明:图中省略了ZygoteConnection获取MethodAndArgsCaller的步骤,其步骤可参加ActivityManagerService的启动流程,也是经过WrapperInit拿到的。

ActivityThread的启动流程 .jpg

二、流程总结

  1. ZygoteInit#main方法中启动一个SystemServer和一个ZygoteServer
  2. SystemServer中通过SystemServiceManager执行onStart()的方式启动了ActivityManagerService,使用ServiceManager对其进行持久化管理。
  3. ZygoteServer中启动了一个名为“zygote”的LocalSocket类型的socket服务。使用死循环去处理socket链接。
  4. 应用没有启动时,从Launcher进入应用,Activity中的startActivity()方法最终调用了ActivityManagerService#startProcessLocked
  5. 这个方法中将ActivityThread的类名参数通过socket链接到ZygoteInit中启动的ZygoteServer
  6. ZygoteServer死循环中得到参数后,通过ZygoteConnection#processOneCommand返回一个MethodAndArgsCaller类型的Runnable,在ZygoteInit#main中执行。
    (26版本会在ZygoteInit#main方法中捕获MethodAndArgsCaller类型的异常,然后捕获执行。两种写法的目的都是为了清除方法调用的堆栈信息)
  7. ActivityThread#main方法中调用其attach方法,将创建好的ApplicationThread传给ActivityManagerService#,AMS保留参数给ProcessRecord后续使用。
  8. 应用已经启动时,Activity中的startActivity()方法调用了ActivityManagerService#startActivityAsUser,执行ActivityStarter#execute
  9. 这个方法最终调用ActivityStackSupervisor#realStartActivityLocked,以ActivityThread.mAppThread为参数创建LaunchActivityItem。然后执行AcitivityThread#scheduleTransaction方法,发送ActivityThread.H.EXECUTE_TRANSACTION
  10. ActivityThread接收到消息后执行LaunchActivityItem#execute,调用ActivityThread#handleLaunchActivity,最终调用ActivityThread#performLaunchActivity
  11. performLaunchActivity()方法通过Instrumentation#newActivity得到要启动的Activity,然后调用其attach()方法。
  12. 而后,会调用Instrumentation#callActivityOnCreate,最终调用到Activity#onCreate

三、相关文章:

  • 谁调用了Android应用的main函数
  • 源码分析 — ActivityThread(一)之main()的调用 (Android应用进程的孵化)
  • 源码分析 — Activity的启动流程 (这个时序图画的很好,推荐!)**
  • Android设计模式(四)续:Activity的onCreate是怎么调用的
  • Activity 启动时序图
  • ActivityThread.main()入口调用流程

四、流程记录

  • 代码跟踪记录,只保留了关键代码,其余代码用...替代。
  • java类名可点击,将跳转到Android社区的sdk源代码文件。
  • 跟踪记录的意义在于,在需要研究流程中某个环节细节问题时,可以快速定位。
1. android.app.Activity.java
    private Instrumentation mInstrumentation;
    public void startActivity(...) {
        ...
        startActivityForResult(...);
        ...
    }
    
    public void startActivityForResult(...) {
        ...
        mInstrumentation.execStartActivity(...);
        ...
    }
    final void performCreate(...) {
        ...
        onCreate(...);
        ...
    }
2. android.app.Instrumentation.java
    public ActivityResult execStartActivity(...) {
        ...
        int result = ActivityManager.getService().startActivity(...)
        ...
    }
    public void callActivityOnCreate(...) {
        ...
        activity.performCreate(...);
        ...
    }
3. android.app.ActivityManager.java
    private static final Singleton IActivityManagerSingleton = () -> {
        final IBinder b = ServiceManager.getService(Context.ACTIVITY_SERVICE);
        ...
        return am;
    };
    
    public static IActivityManager getService() {
        return IActivityManagerSingleton.get();
    }   
4. android.os.ServiceManager.java
    public static IBinder getService(String name) {
        ...
        IBinder service = sCache.get(name);
        ...
    }
    public static void initServiceCache(Map cache) {
        ...
        sCache.putAll(cache);
    }
5. com.android.server.am.ActivityStartController.java
    ActivityStartController(ActivityManagerService service) {
        this(...,new DefaultFactory(..)));
    }

    @VisibleForTesting
    ActivityStartController(...,Factory factory) {
        ...
        mFactory = factory;
        ...
    }
    ActivityStarter obtainStarter(...) {
        return mFactory.obtain().setIntent(intent).setReason(reason);
    }
6. com.android.server.am.ActivityStarter.java
    private ActivityStack mTargetStack;
    static class DefaultFactory implements Factory {
        ...
        public ActivityStarter obtain() {
            ...
            return starter;
        }
        ...
    }
    int execute() {
        ...
        if (mRequest.mayWait) {
            return startActivityMayWait(...);
        } else {
            return startActivity(...);
        }
        ...
    }
    private int startActivityMayWait(...){
        ...
        int res = startActivity(...);
        ...
    }
    private int startActivity(...){
        ...
        result = startActivityUnchecked(...)
        ...
    }
    private int startActivityUnchecked(...){
        ...
         mTargetStack.startActivityLocked(...);
        ...
    }
7. com.android.server.am.ActivityStack.java
    protected final ActivityStackSupervisor mStackSupervisor;
    void startActivityLocked(...){
        ...
        ensureActivitiesVisibleLocked(...);
        ...
    }
    final void ensureActivitiesVisibleLocked(...){
        ...
        if (makeVisibleAndRestartIfNeeded(...)){
            ...
        }
        ...
    }
    private boolean makeVisibleAndRestartIfNeeded(...){
        ...
        mStackSupervisor.startSpecificActivityLocked(...);
        ...
    }
8. com.android.server.am.ActivityStackSupervisor.java
    final ActivityManagerService mService;
    void startSpecificActivityLocked(...){
        ...
        realStartActivityLocked(...);
        ...
        mService.startProcessLocked(...);
        ...
    }
    final boolean realStartActivityLocked(...){
        ...
        clientTransaction = ClientTransaction.obtain(app.thread,...);
        clientTransaction.addCallback(LaunchActivityItem.obtain(...));
        ...
      mService.getLifecycleManager().scheduleTransaction(clientTransaction);
         ...
    }
9. com.android.server.am.ClientLifecycleManager.java
    void scheduleTransaction(...){
        ...
        transaction.schedule();
        ...
    }
10. android.app.servertransaction.ClientTransaction.java
    private List mActivityCallbacks;
    private IApplicationThread mClient;
    public void addCallback(...) {
        ...
        mActivityCallbacks.add(activityCallback);
    }
    public void schedule() throws RemoteException {
        mClient.scheduleTransaction(this);
    }
    public static ClientTransaction obtain(IApplicationThread client, ...) {
        ...
        instance.mClient = client;
        ...
        return instance;
    }
11. com.android.internal.os.ZygoteInit.java
    public static void main(String argv[]) {
        ...
        Runnable r = forkSystemServer(...);
        ...
        r.run();
        ...
        caller = zygoteServer.runSelectLoop(abiList);
        ...
        caller.run();
    }
    private static Runnable forkSystemServer(...) {
        String args[] = {
            ...
            "com.android.server.SystemServer",
        };
        parsedArgs = new ZygoteConnection.Arguments(args);
        ...
        pid = Zygote.forkSystemServer(...);
        ...
        return handleSystemServerProcess(parsedArgs);
    }
    private static Runnable handleSystemServerProcess(...){
        ...
        WrapperInit.execApplication(...);
        ...
    }
    public static final Runnable zygoteInit(...) {
        ...
        return RuntimeInit.applicationInit(...);
    }
    static final Runnable childZygoteInit(...) {
        ...
        return RuntimeInit.findStaticMain(...);
    }
12. com.android.internal.os.WrapperInit.java
    @Override
        public static void execApplication(...) {
        ...
        command.append(" '--nice-name=").append(niceName).append("'");
        ...
        Zygote.execShell(command.toString());
    }
    
13. com.android.internal.os.Zygote.java
    public static int forkSystemServer(...) {
        VM_HOOKS.preFork();
        int pid = nativeForkSystemServer(...);
        ...
        VM_HOOKS.postForkCommon();
        return pid;
    }
    public static void execShell(String command) {
        String[] args = { "/system/bin/sh", "-c", command };
        ...
        Os.execv(args[0], args);
        ...
    }
14. com.android.server.SystemServer.java
    public static void main(String[] args) {
        new SystemServer().run();
    }
    private void run() {
        ...
        mSystemServiceManager = new SystemServiceManager(mSystemContext);
        ...
        startBootstrapServices();
        ...
        startOtherServices();
        ...
    }
    private void startBootstrapServices() {
        ...
        mActivityManagerService = mSystemServiceManager.startService(...)...;
        ...
        mPackageManagerService = PackageManagerService.main(...);
        ...
    }
    private void startOtherServices() {
        ...
        wm = WindowManagerService.main(...);
        ...
        mActivityManagerService.setWindowManager(wm);
        ...
        mActivityManagerService.systemReady(...);
        ...
    }
15. com.android.server.SystemServiceManager.java
    public void startService(...) {
        ...
        service.onStart();
        ...
    }
16. android.os.Process.java
    public static final String ZYGOTE_SOCKET = "zygote";
    public static final ZygoteProcess zygoteProcess =
            new ZygoteProcess(ZYGOTE_SOCKET, SECONDARY_ZYGOTE_SOCKET);
    public static final ProcessStartResult start(...) {
        ...
        return zygoteProcess.start(...);
    }
17. android.os.ZygoteProcess.java
    public final Process.ProcessStartResult start(...) {
        ...
        return startViaZygote(...);
        ...
    }
    private Process.ProcessStartResult startViaZygote(...){
        ...
        zygoteSendArgsAndGetResult(openZygoteSocketIfNeeded(abi),...);
        ...
    }
    private ZygoteState openZygoteSocketIfNeeded(...){
        ...
        ... = ZygoteState.connect(mSocket);
        ...
    }
    public static class ZygoteState {
        ...
        public static ZygoteState connect(LocalSocketAddress address) ... {
            ...
            zygoteSocket.connect(address);
            ...
        }
    }
18. com.android.internal.os.ZygoteConnection.java
    Runnable processOneCommand(ZygoteServer zygoteServer) {
        ...
        return handleChildProc(...);
        ...
    }
    private Runnable handleChildProc(...) {
        ...
        if (...) {
            WrapperInit.execApplication(...);
            throw new IllegalStateException(...);
        } else {
            if (!isZygote) {
                return ZygoteInit.zygoteInit(...);
            } else {
                return ZygoteInit.childZygoteInit(...);
            }
        }
        ...
    }
19. com.android.internal.os.RuntimeInit.java
    protected static Runnable applicationInit(...) {
        ...
        return findStaticMain(...);
    }
    protected static Runnable findStaticMain(...) {
        return new MethodAndArgsCaller(...);
    }
    static class MethodAndArgsCaller implements Runnable {
        ...
        public void run() {
            ...
            mMethod.invoke(null, new Object[] { mArgs });
            ...
        }
        ...
    }
20. com.android.internal.os.ZygoteServer.java
    Runnable runSelectLoop(String abiList) {
        ...
        ZygoteConnection connection = peers.get(i);
        final Runnable command = connection.processOneCommand(this);
        ...
    }
21. com.android.server.am.ActivityManagerService.java
    public final int startActivity(...) {
        return startActivityAsUser(...);
    }
    
    public final int startActivityAsUser(...) {
        return mActivityStartController.obtainStarter(...)
                ....
                .execute();

    }
    private final boolean startProcessLocked(...) {
        ...
        final String entryPoint = "android.app.ActivityThread";
        ...
        return startProcessLocked(..., entryPoint, ...);
    }
    private boolean startProcessLocked(..., String entryPoint,...){
        ...
        final ProcessStartResult startResult = startProcess(...);
        ...
    }
    private ProcessStartResult startProcess(...) {
        ...
        startResult = Process.start(entryPoint,...);
        ...
    }

22. android.app.ActivityThread.java

    public final void bindApplication(...){
        ...
        ServiceManager.initServiceCache(services);
        ...
    }
    private Activity performLaunchActivity(...) {
        ...
        mInstrumentation.callActivityOnCreate(...);
        ...
    }
    public Activity handleLaunchActivity(...){
        ...
        final Activity a = performLaunchActivity(...);
        ...
    }

你可能感兴趣的:(源码跟踪之启动流程:从ZygoteInit到onCreate)