Android系统启动过程全解析(基于android11)

先说总结:
当手机电源按下,引导芯片代码会从Boot Rom开始执行,加载引导程序BootLoader到RAM,然后执行。
BootLoader会启动idle进程(pid=0)。idle进程主要是初始化进程管理、内存管理等。
然后idle进程会启动init进程(pid=1)和kthread进程(pid=2)。init进程作为用户空间的鼻祖。
Init进程先是解析init.rc文件,然后又会通过fork,去加载zygote进程。zygote进程是java进程的鼻祖。
Zygote进程首先会初始化我们的运行时环境,也就是android runtime。因为在zygote之前都是c、c++的运行环境,没有java的运行时环境。
启动运行时环境后,就进入java了。然后zygote进程又会通过fork,加载systemServer进程。android用到的系统服务都是在SystemServer进程中,有90多个服务。像AMS、PMS。

SystemServer启动后,就会启动我们的launcher app。启动launcher app时,会发消息给zygote进程,让zygote进程去启动一个进程,启动进程后,我们的app就会启动自己。

activity是如何启动的?
调用startActivity,通过一系列方法的调用,通过binder通信,进入到systemServer进程。binder拿的systemServer进程中的AMS(10之前)/ATMS(10之后)服务。拿到服务的代理对象后,就会调用服务的startActivity,通过binder通信,进入到systemServer进程中。systemServer进程,先判断要启动的activity所需的进程是否存在,如果不存在,就通过socket通信,通知给zygote进程,创建一个新的进程,然后在新进程中通过反射启动ActivityThread.main()。执行这个方法后,由于新的进程需要被AMS/ATMS管理,所以新的进程会把它的binder对象给到AMS/ATMS中去,AMS/ATMS就会持有新的进程的binder对象,就可以去管理新的进程,从而去管理它的生命周期。如果要启动的activity所需的进程存在,那就不需要通知zygote,而是直接通过进程的binder对象去启动activity。


我们的android系统是基于linux系统的,而在linux中,所有的进程都是由init进程直接或间接fork出来的。zygote也不例外。
在android系统中,zygote是一个进程的名字。当手机开机时,linux系统内核加载完成之后,就会启动init进程。init进程fork出zygote进程。
SystemServer进程也是由zygote进程fork而来。

我们知道,每一个app都是一个单独的dalvik虚拟机,一个独立的进程。所以当系统的第一个zygote进程运行之后,在这之后启动app,相当于开启了一个新的进程。而为了实现资源的共享和更快的启动速度,android系统开启新进程的方式,是通过fork第一个zygote进程实现的。所以说,除了第一个zygote进程,其他应用所有的进程都是由zygote进程的子进程。

AndroidFramework里有两大进程:一个就是zygote进程,另一个就是SystemServer进程。

一、zygote进程

init进程启动zygote进程,fork SystemServer进程。

ZygoteInit 是 zygote 进程的启动类。在zygote开启的时候,会调用ZygoteInit.main()进行初始化。并fork中SystemServer进程。

public static void main(String[] argv) {
    ......
    try {
        ......
        // 在加载首个zygote的时候,会传入初始化参数,使得 startSystemServer = true
        boolean startSystemServer = false;
        String zygoteSocketName = "zygote";
        String abiList = null;
        boolean enableLazyPreload = false;
        for (int i = 1; i < argv.length; i++) {
            if ("start-system-server".equals(argv[i])) {
                // 首次加载,置为true
                startSystemServer = true;
            } else if ("--enable-lazy-preload".equals(argv[i])) {
                enableLazyPreload = true
            } else if (argv[i].startsWith(ABI_LIST_ARG)) {
                abiList = argv[i].substring(ABI_LIST_ARG.length());
            } else if (argv[i].startsWith(SOCKET_NAME_ARG)) {
                zygoteSocketName = argv[i].substring(SOCKET_NAME_ARG.length());
            } else {
                throw new RuntimeException("Unknown command line argument: " + argv[i]);
            }
        }
        ......
        // 开始fork我们的SystemServer进程
        if (startSystemServer) {
            // forkSystemServer方法的返回值是要么是一个MethodAndArgsCaller对象,要是是null
            // 准备参数,fork出ystemServer
            Runnable r = forkSystemServer(abiList, zygoteSocketName, zygoteServer);
                
            --> ......
                // 请求fork SystemServer 进程
                pid = Zygote.forkSystemServer(
                parsedArgs.mUid, parsedArgs.mGid,
                parsedArgs.mGids,
                parsedArgs.mRuntimeFlags, null, parsedArgs.mPermittedCapabilities,
                    parsedArgs.mEffectiveCapabilities);
                --> ......
                    // SystemServer的命令行参数,这个就是SystemServer.main()的args参数。后面会通过反射调用SystemServer.main()
                    String[] args = {
                              "--setuid=1000",
                              "--setgid=1000",
                              "--setgroups=1001,1002,1003,1004,1005,1006,1007,1008,1009,1010,1018,1021,1023,"
                                          + "1024,1032,1065,3001,3002,3003,3006,3007,3009,3010,3011",
                              "--capabilities=" + capabilities + "," + capabilities,
                              "--nice-name=system_server",
                              "--runtime-args",
                              "--target-sdk-version=" + VMRuntime.SDK_VERSION_CUR_DEVELOPMENT,
                              "com.android.server.SystemServer",
                      };
                    // 在native层fork SystemServer
                    int pid = nativeForkSystemServer(
                            uid, gid, gids, runtimeFlags, rlimits,
                            permittedCapabilities, effectiveCapabilities);
                    // 如果这是孩子,则为 0,如果这是父母,则为孩子的 pid,或者错误时为 -1。
                    return pid;
                ......
                return handleSystemServerProcess(parsedArgs);
                --> return ZygoteInit.zygoteInit(parsedArgs.mTargetSdkVersion, parsedArgs.mDisabledCompatChanges, parsedArgs.mRemainingArgs, cl);
                        // 在applicationInit中会对args数组进行解析,转换成有用的Arguments对象
                    --> return RuntimeInit.applicationInit(targetSdkVersion, disabledCompatChanges, argv, classLoader);
                            // args.startClass = com.android.server.SystemServer
                        --> return findStaticMain(args.startClass, args.startArgs, classLoader);
                            --> ......
                                Method m;
                                try {
                                // 找到SystemServer.main(argv[]) 方法
                                m = cl.getMethod("main", new Class[] { String[].class });
                                ......
                                return new MethodAndArgsCaller(m, argv);
}

            // r == null,说明在父(zygote)进程中,r != null说明在子(system_server)进程中。
            if (r != null) {
                // 执行的是MethodAndArgsCaller.run(),run方法内部其实就是通过反射执行SystemServer.main(argv[])
                r.run();
                return;
            }
            
            // 这里面是个while循环,用来接收socket消息。后面介绍启动进程会讲到。
            caller = zygoteServer.runSelectLoop(abiList);
        }
       ......
       }
   ......
}

二、SystemServer进程

1、启动SystemServer进程,完成mSystemContext和ActivityThread的创建,初始化SystemServiceManager对象。

SystemServer.main():

public static void main(String[] args) {
    new SystemServer().run();
}

private void run() {
    ......
        // 加载本地系统服务库,并进行初始化
        System.loadLibrary("android_servers");
        ......

        // 创建系统上下文
        createSystemContext();
            // 详细看一下createSystemContext()
            // 初始化系统上下文对象mSystemContext,并设置默认的主题。
            // mSystemContext实际上是一个ContextImpl对象。
        --> private void createSystemContext() {
              ActivityThread activityThread = ActivityThread.systemMain();
                  // 
              --> ActivityThread thread = new ActivityThread();
                  thread.attach(true, 0);
                  --> ContextImpl context = ContextImpl.createAppContext(this, getSystemContext().mPackageInfo);
                      // 创建了 Application对象,并调用了Application.onCreate()
                      mInitialApplication = context.mPackageInfo.makeApplication(true, null);
                      mInitialApplication.onCreate();
                  return thread;
              mSystemContext = activityThread.getSystemContext();
              mSystemContext.setTheme(DEFAULT_SYSTEM_THEME);

              final Context systemUiContext = activityThread.getSystemUiContext();
              systemUiContext.setTheme(DEFAULT_SYSTEM_THEME);
            }

        // Call per-process mainline module initialization.
        ActivityThread.initializeMainlineModules();

        // 初始化SystemServiceManager对象,下面的系统服务开启都需要调用SystemServiceManager.startService(Class),这个方法通过反射来启动对应的服务
        mSystemServiceManager = new SystemServiceManager(mSystemContext);
        ......
    // 启动服务。接下来我们详细看一下启动的服务。
    try {
        t.traceBegin("StartServices");
        startBootstrapServices(t); // 引导服务:ATMS、AMS等
        startCoreServices(t); // 系统所需的核心服务
        startOtherServices(t); // 其他服务:WMS等
    } catch (Throwable ex) {
        Slog.e("System", "******************************************");
        Slog.e("System", "************ Failure starting system services", ex);
        throw ex;
    } finally {
        t.traceEnd(); // StartServices
    }
    
  ......
}

2、启动系统服务,ActivityManagerService、PackageManagerService、 WindowManagerService等。

系统里面重要的服务都是在这个进程里面开启的,比如 ActivityManagerService、PackageManagerService、 WindowManagerService等等。在SystemServer 进程开启的时候,会调用SystemServer.main(),初始化ActivityManagerService。

// 在这里开启了几个核心的服务,因为这些服务之间相互依赖,所以都放 在了这个方法里面
private void startBootstrapServices(@NonNull TimingsTraceAndSlog t) {
    ......
    // android10之后,增减了ATMS。用来单独管理activity
    // 初始化ATMS
    ActivityTaskManagerService atm = mSystemServiceManager.startService(
            ActivityTaskManagerService.Lifecycle.class).getService();
    // 初始化AMS
    mActivityManagerService = ActivityManagerService.Lifecycle.startService(mSystemServiceManager, atm);
    mActivityManagerService.setSystemServiceManager(mSystemServiceManager);
    mActivityManagerService.setInstaller(installer);
    mWindowManagerGlobalLock = atm.getGlobalLock();
    t.traceEnd();
    ......
    // 电源管理器需要尽早启动,因为其他服务需要它。
    t.traceBegin("StartPowerManager");
    mPowerManagerService = mSystemServiceManager.startService(PowerManagerService.class);
    t.traceEnd();
    ......
    // 现在电源管理已经开启,ActivityManagerService负责电源管理功能
    t.traceBegin("InitPowerManagement");
    mActivityManagerService.initPowerManagement();
    t.traceEnd();
    ......
    // 初始化DisplayManagerService
    t.traceBegin("StartDisplayManager");
    mDisplayManagerService = mSystemServiceManager.startService(DisplayManagerService.class);
    t.traceEnd();
    ......
    // 初始化PackageManagerService
    t.traceBegin("StartPackageManagerService");
    try {
        Watchdog.getInstance().pauseWatchingCurrentThread("packagemanagermain");
        mPackageManagerService = PackageManagerService.main(mSystemContext, installer,
              domainVerificationService, mFactoryTestMode != FactoryTest.FACTORY_TEST_OFF, mOnlyCore);
    } finally {
        Watchdog.getInstance().resumeWatchingCurrentThread("packagemanagermain");
    }
    ......
}
2.1 ATMS的创建:

mSystemServiceManager.startService(ActivityTaskManagerService.Lifecycle.class).getService().

先看mSystemServiceManager.startService(ActivityTaskManagerService.Lifecycle.class):

mSystemServiceManager.startService() @SystemServer
    // 通过反射获取服务
--> final String name = serviceClass.getName(); @SystemServiceManager
    final T service;
    Constructor constructor = serviceClass.getConstructor(Context.class);
    service = constructor.newInstance(mContext);
    startService(service);
    // 返回的service是T泛型,继承自SystemService
    return service;
    --> mServices.add(service);
        // 启动服务
        service.onStart();

根据上面分析,ActivityTaskManagerService.Lifecycle继承自SystemService,mSystemServiceManager.startService(ActivityTaskManagerService.Lifecycle.class)最后是调用了ActivityTaskManagerService.Lifecycle.onStart()。

那再来看ActivityTaskManagerService.Lifecycle:

public Lifecycle(Context context) {
    super(context);
    // ActivityTaskManagerService.Lifecycle构造中初始化了mService。就是ATMS
    mService = new ActivityTaskManagerService(context);
}

public void onStart() {
    // 将 ATMS 加入到ServiceManager中
    publishBinderService(Context.ACTIVITY_TASK_SERVICE, mService);
        // 注册 Binder 服务。
    --> ServiceManager.addService(name, service, allowIsolated, dumpPriority); @SystemService
        --> getIServiceManager().addService(name, service, allowIsolated, dumpPriority); @ServiceManager
    // 调用 ATMS 的start()方法。
    mService.start();
}

public ActivityTaskManagerService getService() {
    // 将 ATMS 对象返回
    return mService;
}

接下来我们看下ActivityTaskManagerService构造方法中做了什么:

public ActivityTaskManagerService(Context context) {
        mContext = context;
        mFactoryTest = FactoryTest.getMode();
        mSystemThread = ActivityThread.currentActivityThread();
        mUiContext = mSystemThread.getSystemUiContext();
        mLifecycleManager = new ClientLifecycleManager(); // 管理生命周期
        mInternal = new LocalService();
        GL_ES_VERSION = SystemProperties.getInt("ro.opengles.version", GL_ES_VERSION_UNDEFINED);
        mWindowOrganizerController = new WindowOrganizerController(this);
        mTaskOrganizerController = mWindowOrganizerController.mTaskOrganizerController;
    }

ActivityServer进程创建了SystemServiceManager,然后SystemServiceManager来启动各种服务,并将对应的服务添加到SystemService中。

2.2 AMS的创建:

mActivityManagerService = ActivityManagerService.Lifecycle.startService(mSystemServiceManager, atm);

ActivityManagerService中同样有一个Lifecycle

public Lifecycle(Context context) {
    super(context);
    // ActivityManagerService.Lifecycle构造中初始化了mService。就是AMS
    mService = new ActivityManagerService(context, sAtm);
}
        
public static ActivityManagerService startService(
    SystemServiceManager ssm, ActivityTaskManagerService atm) {
    sAtm = atm; // atm就是 ATMS 
    // 还是由SystemServiceManager启动服务
    return ssm.startService(ActivityManagerService.Lifecycle.class).getService();
}

public ActivityManagerService getService() {
    return mService;
}

接下来我们看下ActivityManagerService构造方法中做了什么:

public ActivityManagerService(Context systemContext, ActivityTaskManagerService atm) {
        ······
        // 广播的管理
        final BroadcastConstants foreConstants = new BroadcastConstants(
                Settings.Global.BROADCAST_FG_CONSTANTS);
        foreConstants.TIMEOUT = BROADCAST_FG_TIMEOUT;

        final BroadcastConstants backConstants = new BroadcastConstants(
                Settings.Global.BROADCAST_BG_CONSTANTS);
        backConstants.TIMEOUT = BROADCAST_BG_TIMEOUT;

        final BroadcastConstants offloadConstants = new BroadcastConstants(
                Settings.Global.BROADCAST_OFFLOAD_CONSTANTS);
        offloadConstants.TIMEOUT = BROADCAST_BG_TIMEOUT;
        // by default, no "slow" policy in this queue
        offloadConstants.SLOW_TIME = Integer.MAX_VALUE;

        mEnableOffloadQueue = SystemProperties.getBoolean(
                "persist.device_config.activity_manager_native_boot.offload_queue_enabled", false);

        mFgBroadcastQueue = new BroadcastQueue(this, mHandler,
                "foreground", foreConstants, false);
        mBgBroadcastQueue = new BroadcastQueue(this, mHandler,
                "background", backConstants, true);
        mOffloadBroadcastQueue = new BroadcastQueue(this, mHandler,
                "offload", offloadConstants, true);
        // 三种广播形式
        mBroadcastQueues[0] = mFgBroadcastQueue;
        mBroadcastQueues[1] = mBgBroadcastQueue;
        mBroadcastQueues[2] = mOffloadBroadcastQueue;

        // Services的管理
        mServices = new ActiveServices(this);
        ......
        // 电量状态的管理
        // TODO: Move creation of battery stats service outside of activity manager service.
        mBatteryStatsService = new BatteryStatsService(systemContext, systemDir,
                BackgroundThread.get().getHandler());
        mBatteryStatsService.getActiveStatistics().readLocked();
        mBatteryStatsService.scheduleWriteToDisk();
        mOnBattery = DEBUG_POWER ? true
                : mBatteryStatsService.getActiveStatistics().getIsOnBattery();
        mBatteryStatsService.getActiveStatistics().setCallback(this);
        mOomAdjProfiler.batteryPowerChanged(mOnBattery);
        
        // 进程状态的管理
        mProcessStats = new ProcessStatsService(this, new File(systemDir, "procstats"));
        mAppOpsService = mInjector.getAppOpsService(new File(systemDir, "appops.xml"), mHandler);

        mUgmInternal = LocalServices.getService(UriGrantsManagerInternal.class);
        mUserController = new UserController(this);
        mPendingIntentController = new PendingIntentController(
                mHandlerThread.getLooper(), mUserController, mConstants);

        if (SystemProperties.getInt("sys.use_fifo_ui", 0) != 0) {
            mUseFifoUiScheduling = true;
        }

        mTrackingAssociations = "1".equals(SystemProperties.get("debug.track-associations"));
        mIntentFirewall = new IntentFirewall(new IntentFirewallInterface(), mHandler);

        // mActivityTaskManager就是 ATMS
        mActivityTaskManager = atm;
        // ATMS进行初始化,下面我们看下ATMS初始化中干了什么
        mActivityTaskManager.initialize(mIntentFirewall, mPendingIntentController,
                DisplayThread.get().getLooper());
        // 获取ATMInternal,后面会讲到。先有个印象
        mAtmInternal = LocalServices.getService(ActivityTaskManagerInternal.class);

        ......
        mInternal = new LocalService();
        mPendingStartActivityUids = new PendingStartActivityUids(mContext);
    }

mActivityTaskManager.initialize():

public void initialize(IntentFirewall intentFirewall, PendingIntentController intentController,
            Looper looper) {
        mH = new H(looper);
        mUiHandler = new UiHandler();
        mIntentFirewall = intentFirewall;
        final File systemDir = SystemServiceManager.ensureSystemDir();
        mAppWarnings = createAppWarnings(mUiContext, mH, mUiHandler, systemDir);
        mCompatModePackages = new CompatModePackages(this, systemDir, mH);
        mPendingIntentController = intentController;
        // 创建ActivityStackSupervisor
        mStackSupervisor = createStackSupervisor();

        mTaskChangeNotificationController =
                new TaskChangeNotificationController(mGlobalLock, mStackSupervisor, mH);
        mLockTaskController = new LockTaskController(mContext, mStackSupervisor, mH);
        // 控制activity的启动,这个后面还会讲到
        mActivityStartController = new ActivityStartController(this);
        // 最近使用的app
        setRecentTasks(new RecentTasks(this, mStackSupervisor));
        mVrController = new VrController(mGlobalLock);
        mKeyguardController = mStackSupervisor.getKeyguardController();
    }

经过上面这些步骤,我们的ActivityManagerService对象已经创建好了,并且完成了成员变量的初始化。而且在这之前,调用createSystemContext()创建上下文的时候,也已经完成了mSystemContext和ActivityThread的创建。注意,这是系统进程开启时的流程。在这之后,会开启系统的Launcher程序,完成系统界面的加载与显示。

2.3 WMS的创建和绑定
private void startOtherServices(@NonNull TimingsTraceAndSlog t) {
    t.traceBegin("startOtherServices");
    ......
    WindowManagerService wm = null;
    ......
    t.traceBegin("StartWindowManagerService");
    
    // WMS 需要准备好传感器服务
    ConcurrentUtils.waitForFutureNoInterrupt(mSensorServiceStart, START_SENSOR_SERVICE);
    mSensorServiceStart = null;
    wm = WindowManagerService.main(context, inputManager, !mFirstBoot, mOnlyCore,
            new PhoneWindowManager(), mActivityManagerService.mActivityTaskManager);
    ServiceManager.addService(Context.WINDOW_SERVICE, wm, /* allowIsolated= */ false,
            DUMP_FLAG_PRIORITY_CRITICAL | DUMP_FLAG_PROTO);
    ServiceManager.addService(Context.INPUT_SERVICE, inputManager,
            /* allowIsolated= */ false, DUMP_FLAG_PRIORITY_CRITICAL);
    t.traceEnd();

    t.traceBegin("SetWindowManagerService");
    // AMS 绑定 WMS
    mActivityManagerService.setWindowManager(wm);
    t.traceEnd();

    t.traceBegin("WindowManagerServiceOnInitReady");
    wm.onInitReady();
    t.traceEnd();  
    ......
    
    // 启动 Launcher
    mActivityManagerService.systemReady(() -> {
          ······
          // 启动 SystemUi
          startSystemUi(context, windowManagerF);
          ......
        }, t);
}

WindowManagerService.main():

public static WindowManagerService main(final Context context, final InputManagerService im,
            final boolean showBootMsgs, final boolean onlyCore, WindowManagerPolicy policy,
            ActivityTaskManagerService atm, Supplier transactionFactory,
            Supplier surfaceFactory,
            Function surfaceControlFactory) {
     DisplayThread.getHandler().runWithScissors(() ->
            // 创建WindowManagerService对象
            sInstance = new WindowManagerService(context, im, showBootMsgs, onlyCore, policy,
                  atm, transactionFactory, surfaceFactory, surfaceControlFactory), 0);
     return sInstance;
}

3、Launcher进程的启动

mActivityManagerService.systemReady()
    // mAtmInternal还记得是什么吗?在AMS的构造方法中获取的。就是ActivityTaskManagerInternal。   
    // ActivityTaskManagerInternal是个抽象类,ATMS实现了它。
    // 所以我们进入到ATMS中看resumeTopActivities()方法
--> mAtmInternal.resumeTopActivities(false /* scheduleIdle */); @ActivityManagerService
    --> mRootWindowContainer.resumeFocusedStacksTopActivities(); @ActivityTaskServiceManager
            // 这边分成两步走,但最后都是调用的 resumeHomeActivity()
        --> if (focusedStack != null) { @RootWindowContainer
              // 会执行这个...
              result |= focusedStack.resumeTopActivityUncheckedLocked(target, targetOptions);
                  // 关键方法:resumeTopActivityInnerLocked()
              --> result = resumeTopActivityInnerLocked(prev, options); @ActivityStack
                  --> return resumeNextFocusableActivityWhenStackIsEmpty(prev, options);
                      --> return mRootWindowContainer.resumeHomeActivity(prev, reason, getDisplayArea());
            } else if (targetStack == null) {
              result |= resumeHomeActivity(null /* prev */, "no-focusable-task",
                            display.getDefaultTaskDisplayArea());
            }

接下来重点看下RootWindowContainer.resumeHomeActivity(prev, reason, getDisplayArea());

RootWindowContainer.resumeHomeActivity(prev, reason, getDisplayArea());
--> return startHomeOnTaskDisplayArea(mCurrentUser, myReason, taskDisplayArea,
                false /* allowInstrumenting */, false /* fromHomeKey */);
        // mService就是 ATMS。在创建AMS的时候,初始化ATMS的方法中,new出来一个ActivityStartController,用来控制activity的启动。
        // 这里获取到ActivityStartController,去启动HomeActivity。这个方法很重要。。。。
    --> mService.getActivityStartController().startHomeActivity(homeIntent, aInfo, myReason,
                taskDisplayArea);
             // obtainStarter返回的是ActivityStarter对象,经过一系列设置,最后执行的是ActivityStarter.execute()
             // ActivityStarter.execute()非常关键!!!重点!!!跟栈的管理相关
        -->  mLastHomeActivityStartResult = obtainStarter(intent, "startHomeActivity: " + reason)
                .setOutActivity(tmpOutRecord)
                .setCallingUid(0)
                .setActivityInfo(aInfo)
                .setActivityOptions(options.toBundle())
                .execute(); @ActivityStartController
                

上面执行到 ActivityStarter.execute(),这个方法很关键。我们接下来看这个方法。

ActivityStarter.execute()
--> res = executeRequest(mRequest);
    --> ActivityRecord sourceRecord = null; // 启动方
        ActivityRecord resultRecord = null; // 将要启动的
        ......
        mLastStartActivityResult = startActivityUnchecked(r, sourceRecord, voiceSession,
                request.voiceInteractor, startFlags, true /* doResume */, checkedOptions, inTask,
                restrictedBgActivity, intentGrants);
        --> result = startActivityInner(r, sourceRecord, voiceSession, voiceInteractor,
                    startFlags, doResume, options, inTask, restrictedBgActivity, intentGrants);
            --> mRootWindowContainer.resumeFocusedStacksTopActivities(mTargetStack, mStartActivity, mOptions);
                --> result = targetStack.resumeTopActivityUncheckedLocked(target, targetOptions);@RootWindowContainer
                        // 这个方法就非常关键了。。。
                    --> result = resumeTopActivityInnerLocked(prev, options);@ActivityStack
                            // 这个相当重要。。。下面着重看。。。
                        --> mStackSupervisor.startSpecificActivity(next, true, true);

ActivityStackSupervisor.startSpecificActivity()。这个方法非常非常重要!!!要记住!!!

    void startSpecificActivity(ActivityRecord r, boolean andResume, boolean checkConfig) {
        // 判断要启动的activity的application是否已经在运行中?
        // Is this activity's application already running?
        final WindowProcessController wpc =
                mService.getProcessController(r.processName, r.info.applicationInfo.uid);

        boolean knownToBeDead = false;
        // 进程已经存在
        if (wpc != null && wpc.hasThread()) {
            try {
                // 真正的去启动Activity
                realStartActivityLocked(r, wpc, andResume, checkConfig);
                return;
            } catch (RemoteException e) {
                Slog.w(TAG, "Exception when starting activity "
                        + r.intent.getComponent().flattenToShortString(), e);
            }

            // If a dead object exception was thrown -- fall through to
            // restart the application.
            knownToBeDead = true;
        }

        r.notifyUnknownVisibilityLaunchedForKeyguardTransition();

        final boolean isTop = andResume && r.isTopRunningActivity();
        // 如果进程还不存在,就在这里去启动app的进程。。。mService是ATMS.
        mService.startProcessAsync(r, knownToBeDead, isTop, isTop ? "top-activity" : "activity");
    }
3.1 AMS创建socket去通知zygote,创建Launcher进程
ActivityTaskManagerService.startProcessAsync();
    // ActivityManagerInternal::startProcess,代表调用的是ActivityManagerService.startProcess()。
--> final Message m = PooledLambda.obtainMessage(ActivityManagerInternal::startProcess,
                    mAmInternal, activity.processName, activity.info.applicationInfo, knownToBeDead,
                    isTop, hostingType, activity.intent.getComponent()); @ActivityTaskManagerService
    --> ActivityManagerService.startProcess()
            // 只关注方法的调用,参数太多,可以不看。下面的参数都省略
        --> startProcessLocked();
             --> return mProcessList.startProcessLocked();
                --> final Process.ProcessStartResult startResult = startProcess();@ProcessList
                    --> startResult = Process.start();
                        --> return ZYGOTE_PROCESS.start();
                            --> return startViaZygote();@ZygoteProcess
                                --> ......
                                    // args配置的参数
                                    argsForZygote.add("--runtime-args");
                                    argsForZygote.add("--setuid=" + uid);
                                    argsForZygote.add("--setgid=" + gid);
                                    ......
                                    // openZygoteSocketIfNeeded(),打开Zygote的Socket
                                    return zygoteSendArgsAndGetResult(openZygoteSocketIfNeeded(abi),
                                              zygotePolicyFlags,
                                              argsForZygote);     

创建socket与zygote的socke连接

ZygoteProcess.openZygoteSocketIfNeeded(String abi) 
    // 与zygote的socke创建连接
--> attemptConnectionToPrimaryZygote();
    --> primaryZygoteState = ZygoteState.connect(mZygoteSocketAddress, mUsapPoolSocketAddress);

socket通知zygote

ZygoteProcess.zygoteSendArgsAndGetResult()
--> return attemptZygoteSendArgsAndGetResult(zygoteState, msgStr);
        // socket 操作
    --> final BufferedWriter zygoteWriter = zygoteState.mZygoteOutputWriter;
        final DataInputStream zygoteInputStream = zygoteState.mZygoteInputStream;

        zygoteWriter.write(msgStr);
        zygoteWriter.flush();
3.2 zygote收到socket通知后,创建Launcher进程

还记得上面有提过在zygote进程中有个死循环,用来接收socket消息的么?

ZygoteInit.main()
--> caller = zygoteServer.runSelectLoop(abiList);
    --> ......
        while (true) {
            ......
            // 进行等待
            pollReturnValue = Os.poll(pollFDs, pollTimeoutMs);
            ......
            // 有socket消息时,进行处理
            ZygoteConnection connection = peers.get(pollIndex);
            final Runnable command = connection.processOneCommand(this);
                // 创建pid。关注方法,参数不重要,省略
            --> pid = Zygote.forkAndSpecialize();
                // 反射调用ActivityThread.main()
            --> return handleChildProc(parsedArgs, childPipeFd, parsedArgs.mStartChildZygote);

反射调用了ActivityThread.main()

ActivityThread.main()
--> ActivityThread thread = new ActivityThread();
    thread.attach(false, startSeq);
    // 把应用的句柄发给AMS,让AMS进行统一管理。句柄就是ApplicationThread,
    --> mgr.attachApplication(mAppThread, startSeq);
        --> attachApplicationLocked(thread, callingPid, callingUid, startSeq);@ActivityManagerService
                // 关注方法,参数不重要,省略
            --> thread.bindApplication();
                ......
                didSomething = mAtmInternal.attachApplication(app.getWindowProcessController());
                --> return mRootWindowContainer.attachApplication(wpc);
                        // RootWindowContainer::startActivityForAttachedApplicationIfNeeded
                    --> final PooledFunction c = PooledLambda.obtainFunction(
                    RootWindowContainer::startActivityForAttachedApplicationIfNeeded, this,
                    PooledLambda.__(ActivityRecord.class), app, stack.topRunningActivity());
                            // 还记得前面有区分进程是否存在的地方吗?不管进程存不存在,最后启动activity都是调用的是StackSupervisor.realStartActivityLocked()
                        --> mStackSupervisor.realStartActivityLocked(r, app, top == r /*andResume*/, true /*checkConfig*/)
3.3 zygote进程启动launcher进程
ActivityStackSupervisor.realStartActivityLocked()
    // 添加callBack。关注方法,参数省略。后面会用到。。。
--> clientTransaction.addCallback(LaunchActivityItem.obtain(......);
    ......
    // ActivityTaskManagerService.getLifecycleManager() = ClientLifecycleManager
    mService.getLifecycleManager().scheduleTransaction(clientTransaction);
    --> transaction.schedule();
            // mClient是IApplicationThread的实例,也就是ActivityThread对象。
        --> mClient.scheduleTransaction(this);
                // 调用ActivityThread父类ClientTransactionHandler的scheduleTransaction()方法。
            --> ActivityThread.this.scheduleTransaction(transaction);@ActivityThread
                    // 又调用ActivityThread的sendMessage()方法,发送EXECUTE_TRANSACTION消息
                --> sendMessage(ActivityThread.H.EXECUTE_TRANSACTION, transaction);
                    --> mH.sendMessage(msg);

接收EXECUTE_TRANSACTION消息

case EXECUTE_TRANSACTION:
     final ClientTransaction transaction = (ClientTransaction) msg.obj;
     mTransactionExecutor.execute(transaction);
     --> executeCallbacks(transaction);@TransactionExecutor
             // 
          --> for (int i = 0; i < size; ++i) {
                 final ClientTransactionItem item = callbacks.get(i);
                 ......
                 // 这里的item就是上面添加的LaunchActivityItem。
                 item.execute(mTransactionHandler, token, mPendingActions);
                 --> ActivityClientRecord r = new ActivityClientRecord(token, mIntent, mIdent, mInfo, mOverrideConfig, mCompatInfo, mReferrer, mVoiceInteractor, mState, mPersistentState, mPendingResults, mPendingNewIntents, mIsForward, mProfilerInfo, client, mAssistToken, mFixedRotationAdjustments);
                     // ActivityThread.handleLaunchActivity()
                     client.handleLaunchActivity(r, pendingActions, null /* customIntent */);
                     --> final Activity a = performLaunchActivity(r, customIntent);@ActivityThread
                         --> java.lang.ClassLoader cl = appContext.getClassLoader();
                             // 反射创建activity
                             activity = mInstrumentation.newActivity(cl, component.getClassName(), r.intent);
                             ......
                             // 调用activity的oncreate方法
                             if (r.isPersistable()) {
                                 mInstrumentation.callActivityOnCreate(activity, r.state, r.persistentState);
                             } else {
                                 mInstrumentation.callActivityOnCreate(activity, r.state);
                             }
                 ......
              }
        
     ...... 
 break;

经过上面一系列调用,最终调用了mInstrumentation.callActivityOnCreate(activity, r.state)。后面的流程就和app的启动流程一样了,后面一起分析。

为什么说AMS是服务端对象呢?那就要说到android系统里的服务器和客户端的概念。
其实服务器客户端的概念不仅仅存在于web开发中,在android的框架设计中,使用的也是这一种模式。服务器端指的就是所有app共用的系统服务,比如我们这里提到的ActivityManagerService,和前面提到的PackageManagerService、WindowManagerService等等,这些基础的系统服务是被所有app共用的,当某个app想实现某个操作的时候,要告诉这些系统服务,比如你想要打开一个app,那么我们知道了包名和MainActivity类名之后就可以打开。

Intent intent = new Intent(Intent.ACTION_MAIN);
intent.addCategory(Intent.CATEGORY_LAUNCHER);
ComponentName cn = new ComponentName(packageName, className);
intent.setComponent(cn);
startActivity(intent);

但是,我们的app通过调用startActivity()并不能直接打开另一个app,这个方法会通过一系列的调用,最后还是告诉AMS说:我要打开这个app,我知道它的地址和名字,你帮我打开吧!所以是AMS来通知zygote进程来fork一个新进程,来开启我们的目标app的。这就像是浏览器想要打开一个超链接,浏览器把网址发送给服务器,然后由服务器把需要的资源文件发送给客户端。

知道了Android Framework的客户端服务器架构后,我们还需要了解一件事,就是我们的app和AMS(SystemServer进程),还有zygote进程分属于三个独立的进程,那它们之间是怎么通信的呢?
app和AMS(SystemServer进程)通过 Binder 进行IPC通信,AMS和zygote通过 Socket 进行IPC通信。

那么AMS有什么用呢?在前面我们知道了,如果想要打开一个app的话,需要AMS去通知zygote进程,除此之外,其实所有的Activity的开启、暂停、关闭都需要AMS来控制。所以我们说AMS控制系统中所有Activity的生命周期。

在andorid系统中,任何一个activity的启动都是由AMS和应用程序进程(只要是ActivityThread)相互配合来完成的。AMS服务统一调度系统中所有进程的Activity启动,而每个Activity的启动过程则由其所属的进程具体来完成。

后面专门介绍下AMS与ActivityThread是如何通力合作一起控制Activiy的生命周期。

你可能感兴趣的:(Android系统启动过程全解析(基于android11))