概述

该篇基于AndroidQ,主要介绍系统启动中的 AMS(ActivityManagerService)的启动过程。
AMS对四大组件(AndroidQ将activity移到了ActivityTaskManagerService中,但也和AMS相关联)进行管理和调度。同时,AMS也对进程、电池、内存、权限等进行管理。

AMS的启动过程结束 部分,主要跟踪的代码过程,加以简单说明。代码中添加了注释,可做参考,有点长。如果只想简单了解下,可以直接看下最后的 简单总结 部分。

AMS相关目录结构

AMS代码主要在下面几个目录(AndroidQ上AMS相关部分功能移到了wm下):
frameworks/base/core/java/android/app/
frameworks/base/services/core/java/com/android/server/am/
frameworks/base/services/core/java/com/android/server/wm/

下面具体看下几个重要文件
frameworks/base/core/java/android/app/下:

  • Activity.java:所有Activity的父类。
  • ActivityManager.java:AMS的客户端,提供给用户可调用的api。
  • ActivityThread.java:应用进程的主线程类,一般即UI线程。

frameworks/base/services/core/java/com/android/server/am/下:

  • ActiveServices.java:控制service的启动、重启等。
  • ProcessRecord.java:记录每个进程的信息。

frameworks/base/services/core/java/com/android/server/wm/下:

  • ActivityRecord.java:activity对象信息的记录。
  • ActivityStack.java/ActivityStackSupervisor.java:管理activity生命周期及堆栈等。
  • TaskRecord.java:任务栈记录,管理一个任务的应用activity
  • ActivityTaskManagerService.java/ActivityTaskManagerInternal.java:管理activity的启动和调度。

文末附上了一个图片,是ActivityStack、ActivityStackSupervisor、TaskRecord、ActivityRecord、ProcessRecord之间的关系。

AMS的启动过程

系统启动、AMS起点之前

系统启动后Zygote进程第一个fork出SystemServer进程,进入到SystemServer:main()->run()->startBootstrapServices() 启动引导服务,进而完成AMS的启动。

下面是fork出SystemServer的过程,有不少地方需要进一步学习,了解下不做说明。
ZygoteInit.java:main()->forkSystemServer()->Zygote.java:forkSystemServer()->nativeForkSystemServer()->com_android_internal_os_Zygote.cpp:com_android_internal_os_Zygote_nativeForkSystemServer()->ZygoteInit.java->handleSystemServerProcess()。

直接从SystemServer的run()看:

//frameworks/base/services/java/com/android/server/SystemServer.java
private void run() {
    try {
        createSystemContext();
    }
    try {
        traceBeginAndSlog("StartServices");
        startBootstrapServices();
        startCoreServices();
        startOtherServices();
        SystemServerInitThreadPool.shutdown();
    }
}

private void createSystemContext() {
    ActivityThread activityThread = ActivityThread.systemMain();
    //初始化系统context,并设置主题
    mSystemContext = activityThread.getSystemContext();
    mSystemContext.setTheme(DEFAULT_SYSTEM_THEME);
    //初始化SystemUi context,并设置主题
    final Context systemUiContext = activityThread.getSystemUiContext();
    systemUiContext.setTheme(DEFAULT_SYSTEM_THEME);
}

createSystemContext()创建了两个上下文,系统context和SystemUi context。这两个挺重要,会传入AMS中,这里就是它们创建的地方。
接下来看下上面创建两个上下文时的systemMain(),这个也很重要。

//ActivityThread.java
@UnsupportedAppUsage
public static ActivityThread systemMain() {
    // The system process on low-memory devices do not get to use hardware
    // accelerated drawing, since this can add too much overhead to the
    // process.
    if (!ActivityManager.isHighEndGfx()) {
        ThreadedRenderer.disable(true);
    } else {
        ThreadedRenderer.enableForegroundTrimming();
    }
    ActivityThread thread = new ActivityThread();
    thread.attach(true, 0);
    return thread;
}

@UnsupportedAppUsage
ActivityThread() {
    mResourcesManager = ResourcesManager.getInstance();
}

@UnsupportedAppUsage
private void attach(boolean system, long startSeq) {
    sCurrentActivityThread = this;
    mSystemThread = system;
    if (!system) {
        .......    
    } else {
        ......
        try {
            mInstrumentation = new Instrumentation();
            mInstrumentation.basicInit(this);
            ContextImpl context = ContextImpl.createAppContext(
                    this, getSystemContext().mPackageInfo);
            mInitialApplication = context.mPackageInfo.makeApplication(true, null);
            mInitialApplication.onCreate();
        }
        ......
    }
    .......
}

ActivityThread是当前进程的主线程。SystemServer初始化时ActivityThread.systemMain()创建的是系统进程(SystemServer进程)的主线程。
构造函数是获取ResourcesManager的单例对象。
attach()这里走的是系统进程(应用启动也会走,那时system为false,走的时应用进程),这里创建了几个重要的对象Instrumentation、Context、Application。
Instrumentation:很重要的一个基类,会优先实例化,允许检测系统与应用所有交互。应用中AndroidManifest.xml的标签可以定义其实现。
Context:上下文,应用运行环境的全局信息。这里创建的是一个LoadedApk(packagename是android,即framework-res.apk),以此获取了Context对象。(具体可追踪ContextImpl.createAppContext())。
Application:保存应用的全局状态。

AMS查看起点

这里从startBootstrapServices()作为AMS启动的起点开始查看

//frameworks/base/services/java/com/android/server/SystemServer.java
private void startBootstrapServices() {
    ......
    // TODO: Might need to move after migration to WM.
    //part 0
    ActivityTaskManagerService atm = mSystemServiceManager.startService(
            ActivityTaskManagerService.Lifecycle.class).getService();
    //part 1
    mActivityManagerService = ActivityManagerService.Lifecycle.startService(
            mSystemServiceManager, atm);
    //part 2
    mActivityManagerService.setSystemServiceManager(mSystemServiceManager);
    //part 3
    mActivityManagerService.setInstaller(installer);
    // Now that the power manager has been started, let the activity manager
    // initialize power management features.
    //part 4
    mActivityManagerService.initPowerManagement();
    // Set up the Application instance for the system process and get started.
    //part 5
    mActivityManagerService.setSystemProcess();
    // Complete the watchdog setup with an ActivityManager instance and listen for reboots
    // Do this only after the ActivityManagerService is properly started as a system process
    //part 6
    watchdog.init(mSystemContext, mActivityManagerService);
}

注意上面的几个部分(part0-part6),是其中mActivityManagerService相关的,依次来具体看看,了解AMS的启动过程。

part 0:mSystemServiceManager.startService(ActivityTaskManagerService.Lifecycle.class).getService()

这句和ActivityManagerService.Lifecycle.startService()里执行过程(part 1中)是一样的,这里不详细说明,当看part 1部分就能知道。
这句创建了ActivityTaskManagerService对象,并调用了ActivityTaskManagerService中的start()方法启动服务。

ActivityTaskManagerService是Android 10新引入的变化,也是系统服务,用来管理Activity启动和调度,包括其容器(task、stacks、displays等)。这篇主要关于AMS的启动,因此ActivityTaskManagerService这里不赘述。
Android 10将原先AMS中对activity的管理和调度移到了ActivityTaskManagerService中,位置放到了wm下(见上面完整路径),因此AMS负责四大组件中另外3个(service, broadcast, contentprovider)的管理和调度。

ActivityTaskManagerService.java上的注释说明:
System service for managing activities and their containers (task, stacks, displays,... ).

part 1:ActivityManagerService.Lifecycle.startService()

//ActivityManagerService.java
public static final class Lifecycle extends SystemService {
    private final ActivityManagerService mService;
    private static ActivityTaskManagerService sAtm;

    public Lifecycle(Context context) {
        super(context);
        mService = new ActivityManagerService(context, sAtm);
    }

    public static ActivityManagerService startService(
            SystemServiceManager ssm, ActivityTaskManagerService atm) {
        sAtm = atm;
        return ssm.startService(ActivityManagerService.Lifecycle.class).getService();
    }
    
    @Override
    public void onStart() {
        mService.start();
    }
    
    public ActivityManagerService getService() {
        return mService;
    }

这里的Lifecycle是AMS的内部类。ActivityManagerService.Lifecycle.startService()最终返回的是mService,即创建的AMS对象。

接着来具体看下这个过程的实现,ActivityManagerService.Lifecycle.startService()进入SystemServiceManager类的startService(),继续看

//frameworks/base/services/core/java/com/android/server/SystemServiceManager.java
public <T extends SystemService> T startService(Class<T> serviceClass) {
    try {
        final String name = serviceClass.getName();
         // Create the service.
        if (!SystemService.class.isAssignableFrom(serviceClass)) {
            throw new RuntimeException("Failed to create " + name
                    + ": service must extend " + SystemService.class.getName());
        }
        final T service;
        try {
            Constructor<T> constructor = serviceClass.getConstructor(Context.class);
            service = constructor.newInstance(mContext);
        } ......
        startService(service);
        return service;
    } 
}

public void startService(@NonNull final SystemService service) {
    // Register it.
    mServices.add(service);
    // Start it.
    long time = SystemClock.elapsedRealtime();
    try {
        service.onStart();
    } catch (RuntimeException ex) {
        ......
    }
    warnIfTooLong(SystemClock.elapsedRealtime() - time, service, "onStart");
}

SystemServiceManager中通过反射,调用了ActivityManagerService.Lifecycle的构造方法,然后startService(service) 中最终调用了service.onStart(),即ActivityManagerService.Lifecycle.onStart()。

题外话,这里有几个稍微注意下:

  • isAssignableFrom与instanceof:
    Class1.isAssignableFrom(Class2):都是Class类型 表示类或接口,判断Class1是否是Class2的父类或父接口,或者相同。
    也可以简单看作:父类.class.isAssignableFrom(子类.class)。
    oo instanceof TypeName:oo是实例对象,TypeName是具体类名或接口名。判断oo是否是TypeName的子类或接口实现。
    也可以简单看作:子类实例 instanceof 父类类型。
  • warnIfTooLong()中,时间elapsedRealtime()是包含深度睡眠的设备启动时间,具体在Handler消息机制有提过。另外这里的warn时间是SERVICE_CALL_WARN_TIME_MS -- 50ms。

接着需要看两点:通过反射调用ActivityManagerService.Lifecycle的构造方法,主要new ActivityManagerService() 创建AMS对象,干了些什么需要了解;ActivityManagerService.Lifecycle.onStart()就是直接调用AMS的start()方法;

new ActivityManagerService()

// Note: This method is invoked on the main thread but may need to attach various
// handlers to other threads.  So take care to be explicit about the looper.
public ActivityManagerService(Context systemContext, ActivityTaskManagerService atm) {
    LockGuard.installLock(this, LockGuard.INDEX_ACTIVITY);
    mInjector = new Injector(); 
    //系统上下文,是在SystemServer进程fork出来后通过createSystemContext()创建的,即与SystemServer进程是一一致
    mContext = systemContext;

    mFactoryTest = FactoryTest.getMode();
    //系统进程的主线程 sCurrentActivityThread,这里是systemMain()中创建的ActivityThread对象。即也与SystemServer一样的。
    mSystemThread = ActivityThread.currentActivityThread();
    mUiContext = mSystemThread.getSystemUiContext();

    Slog.i(TAG, "Memory class: " + ActivityManager.staticGetMemoryClass());

    mHandlerThread = new ServiceThread(TAG,
            THREAD_PRIORITY_FOREGROUND, false /*allowIo*/);
    mHandlerThread.start();
    //处理AMS消息的handle
    mHandler = new MainHandler(mHandlerThread.getLooper());
    //UiHandler对应于Android中的Ui线程
    mUiHandler = mInjector.getUiHandler(this);

    mProcStartHandlerThread = new ServiceThread(TAG + ":procStart",
            THREAD_PRIORITY_FOREGROUND, false /* allowIo */);
    mProcStartHandlerThread.start();
    mProcStartHandler = new Handler(mProcStartHandlerThread.getLooper());

    mConstants = new ActivityManagerConstants(mContext, this, mHandler);
    final ActiveUids activeUids = new ActiveUids(this, true /* postChangesToAtm */);
    mProcessList.init(this, activeUids);
    mLowMemDetector = new LowMemDetector(this);
    mOomAdjuster = new OomAdjuster(this, mProcessList, activeUids);

    // Broadcast policy parameters
    final BroadcastConstants foreConstants = new BroadcastConstants(
            Settings.Global.BROADCAST_FG_CONSTANTS);
    foreConstants.TIMEOUT = BROADCAST_FG_TIMEOUT;//10s

    final BroadcastConstants backConstants = new BroadcastConstants(
            Settings.Global.BROADCAST_BG_CONSTANTS);
    backConstants.TIMEOUT = BROADCAST_BG_TIMEOUT;//60s
    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);
    //创建几种广播相关对象,前台广播、后台广播、offload暂不了解TODO。
    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;

    // 创建ActiveServices对象,管理 ServiceRecord
    mServices = new ActiveServices(this);
    // 创建ProviderMap对象,管理ContentProviderRecord
    mProviderMap = new ProviderMap(this);
    mPackageWatchdog = PackageWatchdog.getInstance(mUiContext);
    mAppErrors = new AppErrors(mUiContext, this, mPackageWatchdog);

    final File systemDir = SystemServiceManager.ensureSystemDir();

    // 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);

    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);

    //得到ActivityTaskManagerService的对象,调用ATM.initialize
    mActivityTaskManager = atm;
    mActivityTaskManager.initialize(mIntentFirewall, mPendingIntentController,
            DisplayThread.get().getLooper());
    mAtmInternal = LocalServices.getService(ActivityTaskManagerInternal.class);

    mProcessCpuThread = new Thread("CpuTracker") {
        ......
    };

    mHiddenApiBlacklist = new HiddenApiSettings(mHandler, mContext);

    //加入Watchdog的监控
    Watchdog.getInstance().addMonitor(this);
    Watchdog.getInstance().addThread(mHandler);

    // bind background threads to little cores
    // this is expected to fail inside of framework tests because apps can't touch cpusets directly
    // make sure we've already adjusted system_server's internal view of itself first
    updateOomAdjLocked(OomAdjuster.OOM_ADJ_REASON_NONE);
    try {
        Process.setThreadGroupAndCpuset(BackgroundThread.get().getThreadId(),
                Process.THREAD_GROUP_SYSTEM);
        Process.setThreadGroupAndCpuset(
                mOomAdjuster.mAppCompact.mCompactionThread.getThreadId(),
                Process.THREAD_GROUP_SYSTEM);
    } catch (Exception e) {
        Slog.w(TAG, "Setting background thread cpuset failed");
    }

}

AMS的构造方法,主要完成一些对象的构造及变量的初始化,可以看下上面的注释。

  • 三大组件的(service、broadcast、provider)管理和调度(activity移到了ActivityTaskManagerService中,但此处也绑定了ActivityTaskManagerService对象)。
  • 监控内存、电池、权限(可以了解下appops.xml)以及性能相关的对象或变量。mLowMemDetector、mBatteryStatsService、mProcessStats、mAppOpsService、mProcessCpuThread等。

AMS的start()

private void start() {
    //移除所有的进程组
    removeAllProcessGroups();
    //启动CPU监控线程
    mProcessCpuThread.start();

    //注册电池、权限管理相关服务
    mBatteryStatsService.publish();
    mAppOpsService.publish(mContext);
    Slog.d("AppOps", "AppOpsService published");
    LocalServices.addService(ActivityManagerInternal.class, new LocalService());
    mActivityTaskManager.onActivityManagerInternalAdded();
    mUgmInternal.onActivityManagerInternalAdded();
    mPendingIntentController.onActivityManagerInternalAdded();
    // Wait for the synchronized block started in mProcessCpuThread,
    // so that any other access to mProcessCpuTracker from main thread
    // will be blocked during mProcessCpuTracker initialization.
    try {
        mProcessCpuInitLatch.await();
    } catch (InterruptedException e) {
        Slog.wtf(TAG, "Interrupted wait during start", e);
        Thread.currentThread().interrupt();
        throw new IllegalStateException("Interrupted wait during start");
    }
}

start()主要:

  • 移除所有进程组,复位进程后,启动CPU监控线程。mProcessCpuThread在前面构造函数中创建的线程。
  • 注册电池、权限管理的相关服务
  • LocalService只能本进程使用,不可跨进程。

part 2:mActivityManagerService.setSystemServiceManager(mSystemServiceManager)

ActivityManagerService.java:
public void setSystemServiceManager(SystemServiceManager mgr) {
    mSystemServiceManager = mgr;
}

很简单,将SystemServer.java中创建的SystemServiceManager对象mSystemServiceManager 设置到了AMS中。

part 3:mActivityManagerService.setInstaller(installer)

ActivityManagerService.java:
public void setInstaller(Installer installer) {
    mInstaller = installer;
}

同样,将SystemServer.java中创建的Installer对象installer设置到AMS中。

part 4:mActivityManagerService.initPowerManagement()

ActivityManagerService.java:
public void initPowerManagement() {
    mActivityTaskManager.onInitPowerManagement();
    mBatteryStatsService.initPowerManagement();
    mLocalPowerManager = LocalServices.getService(PowerManagerInternal.class);
}

在前面创建AMS过程,mActivityTaskManager、mBatteryStatsService对象已创建 相关服务已注册。这里初始化电源管理的功能。

part 5:mActivityManagerService.setSystemProcess()

public void setSystemProcess() {
   try {
        //注册服务activity
        ServiceManager.addService(Context.ACTIVITY_SERVICE, this, /* allowIsolated= */ true,
                DUMP_FLAG_PRIORITY_CRITICAL | DUMP_FLAG_PRIORITY_NORMAL | DUMP_FLAG_PROTO);
        //注册服务procstats,进程状态
        ServiceManager.addService(ProcessStats.SERVICE_NAME, mProcessStats);
        //注册服务meminfo,内存信息
        ServiceManager.addService("meminfo", new MemBinder(this), /* allowIsolated= */ false,
                DUMP_FLAG_PRIORITY_HIGH);
        //注册服务gfxinfo,图像信息
        ServiceManager.addService("gfxinfo", new GraphicsBinder(this));
        //注册服务dbinfo,数据库信息
        ServiceManager.addService("dbinfo", new DbBinder(this));
        if (MONITOR_CPU_USAGE) {
            //注册服务cpuinfo,cpu信息
            ServiceManager.addService("cpuinfo", new CpuBinder(this),
                    /* allowIsolated= */ false, DUMP_FLAG_PRIORITY_CRITICAL);
        }
        //注册服务permission和processinfo,权限和进程信息
        ServiceManager.addService("permission", new PermissionController(this));
        ServiceManager.addService("processinfo", new ProcessInfoService(this));
        //获取“android”应用的ApplicationInfo,并装载到mSystemThread
        ApplicationInfo info = mContext.getPackageManager().getApplicationInfo(
                "android", STOCK_PM_FLAGS | MATCH_SYSTEM_ONLY);
        mSystemThread.installSystemApplicationInfo(info, getClass().getClassLoader());
        //创建ProcessRecord维护进程的相关信息
        synchronized (this) {
            ProcessRecord app = mProcessList.newProcessRecordLocked(info, info.processName,
                    false,
                    0,
                    new HostingRecord("system"));
            app.setPersistent(true);
            app.pid = MY_PID;//
            app.getWindowProcessController().setPid(MY_PID);
            app.maxAdj = ProcessList.SYSTEM_ADJ;
            app.makeActive(mSystemThread.getApplicationThread(), mProcessStats);
            mPidsSelfLocked.put(app);//
            mProcessList.updateLruProcessLocked(app, false, null);
            updateOomAdjLocked(OomAdjuster.OOM_ADJ_REASON_NONE);
        }
    } catch (PackageManager.NameNotFoundException e) {
        throw new RuntimeException(
                "Unable to find android system package", e);
    }

    // Start watching app ops after we and the package manager are up and running.
    mAppOpsService.startWatchingMode(AppOpsManager.OP_RUN_IN_BACKGROUND, null,
            new IAppOpsCallback.Stub() {
                @Override public void opChanged(int op, int uid, String packageName) {
                    if (op == AppOpsManager.OP_RUN_IN_BACKGROUND && packageName != null) {
                        if (mAppOpsService.checkOperation(op, uid, packageName)
                                != AppOpsManager.MODE_ALLOWED) {
                            runInBackgroundDisabled(uid);
                        }
                    }
                }
            });
}

这个方法 设置系统进程,AMS的setSystemProcess主要:

  • 注册一些服务:activity、procstats、meminfo、gfxinfo、dbinfo、cpuinfo、permission、processinfo
    关于服务的注册涉及binder相关内容,可以参考Binder机制
  • 起点部分,attach()过程获取Context对象时通过ContextImpl.createAppContext()创建了一个LoadedApk(packagename是android,即framework-res.apk)。
    这里获取包名为“android”的应用的ApplicationInfo对象,并将该ApplicationInfo信息安装设置到SystemThread(系统进程主线程)。即可以理解,系统也是一个特殊的应用。
  • 创建ProcessRecord维护进程的相关信息,这里MY_PID即为SystemServer进程ID。
  • 启动 检测应用运行和交互。

part 6:watchdog.init(mSystemContext, mActivityManagerService)

初始化看门狗,AMS实列作为参数设置进入。

结束

这个过程,即系统完成启动,作为结束大致看下(已算不属于AMS的启动了,是在AMS启动之后)。我们平时接触比较多的,launcher、systemui都是在这个过程完成启动的,最后发送开机广播ACTION_BOOT_COMPLETED。
下面大致看下。

最开始讲过在SystemServer的run()中,有

traceBeginAndSlog("StartServices");
startBootstrapServices();
startCoreServices();
startOtherServices();

上面讲到的都是startBootstrapServices(),AMS的启动在其中。最后,当引导服务、核心服务、其他服务都完成后,会调用AMS中的systemReady()方法。

SystemServer.java:
private void startOtherServices() {
    mActivityManagerService.installSystemProviders();
    // Now that SettingsProvider is ready, reactivate SQLiteCompatibilityWalFlags
    SQLiteCompatibilityWalFlags.reset();
    ......
    mActivityManagerService.systemReady(() -> {
        ......//goingCallback
    }, BOOT_TIMINGS_TRACE_LOG);
}

systemReady()

ActivityManagerService.java:
public void systemReady(final Runnable goingCallback, TimingsTraceLog traceLog) {
    traceLog.traceBegin("PhaseActivityManagerReady");
    synchronized(this) {
        //第一次进入为false
        if (mSystemReady) {
            ......
        }
        //关键服务等待systemReady,继续完成一些初始化或进一步的工作
        mLocalDeviceIdleController
                = LocalServices.getService(DeviceIdleController.LocalService.class);
        mActivityTaskManager.onSystemReady();
        // Make sure we have the current profile info, since it is needed for security checks.
        mUserController.onSystemReady();
        mAppOpsService.systemReady();
        mSystemReady = true;
    }
    ......
    //mPidsSelfLocked中保留了当前正在运行的所有进程信息
    ArrayList<ProcessRecord> procsToKill = null;
    synchronized(mPidsSelfLocked) {
        for (int i=mPidsSelfLocked.size()-1; i>=0; i--) {
            ProcessRecord proc = mPidsSelfLocked.valueAt(i);
            //已启动的进程,若进程没有FLAG_PERSISTENT标志,则会被加入到procsToKill中
            if (!isAllowedWhileBooting(proc.info)){
                if (procsToKill == null) {
                    procsToKill = new ArrayList<ProcessRecord>();
                }
                procsToKill.add(proc);
            }
        }
    }
    //关闭procsToKill中的所有进程
    synchronized(this) {
        if (procsToKill != null) {
            for (int i=procsToKill.size()-1; i>=0; i--) {
                ProcessRecord proc = procsToKill.get(i);
                Slog.i(TAG, "Removing system update proc: " + proc);
                mProcessList.removeProcessLocked(proc, true, false, "system update done");
            }
        }

        // Now that we have cleaned up any update processes, we
        // are ready to start launching real processes and know that
        // we won't trample on them any more.
        //到这里系统准备完毕
        mProcessesReady = true;
    }

    Slog.i(TAG, "System now ready");
    EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_AMS_READY, SystemClock.uptimeMillis());

    mAtmInternal.updateTopComponentForFactoryTest();
    mAtmInternal.getLaunchObserverRegistry().registerLaunchObserver(mActivityLaunchObserver);

    watchDeviceProvisioning(mContext);

    retrieveSettings();
    mUgmInternal.onSystemReady();

    final PowerManagerInternal pmi = LocalServices.getService(PowerManagerInternal.class);
    if (pmi != null) {
        pmi.registerLowPowerModeObserver(ServiceType.FORCE_BACKGROUND_CHECK,
                state -> updateForceBackgroundCheck(state.batterySaverEnabled));
        updateForceBackgroundCheck(
                pmi.getLowPowerState(ServiceType.FORCE_BACKGROUND_CHECK).batterySaverEnabled);
    } else {
        Slog.wtf(TAG, "PowerManagerInternal not found.");
    }
    //运行goingCallback,SystemServer调用时传入的
    if (goingCallback != null) goingCallback.run();
    // Check the current user here as a user can be started inside goingCallback.run() from
    // other system services.
    final int currentUserId = mUserController.getCurrentUserId();
    ......
    final boolean bootingSystemUser = currentUserId == UserHandle.USER_SYSTEM;

    if (bootingSystemUser) {
        mSystemServiceManager.startUser(currentUserId);
    }

    synchronized (this) {
        // Only start up encryption-aware persistent apps; once user is
        // unlocked we'll come back around and start unaware apps
        startPersistentApps(PackageManager.MATCH_DIRECT_BOOT_AWARE);//FLX

        // Start up initial activity.
        mBooting = true;
        // Enable home activity for system user, so that the system can always boot. We don't
        // do this when the system user is not setup since the setup wizard should be the one
        // to handle home activity in this case.
        if (UserManager.isSplitSystemUser() &&
                Settings.Secure.getInt(mContext.getContentResolver(),
                     Settings.Secure.USER_SETUP_COMPLETE, 0) != 0) {
            ComponentName cName = new ComponentName(mContext, SystemUserHomeActivity.class);
            try {
                AppGlobals.getPackageManager().setComponentEnabledSetting(cName,
                        PackageManager.COMPONENT_ENABLED_STATE_ENABLED, 0,
                        UserHandle.USER_SYSTEM);
            } catch (RemoteException e) {
                throw e.rethrowAsRuntimeException();
            }
        }

        if (bootingSystemUser) {
            //启动launcher的Activity.
            mAtmInternal.startHomeOnAllDisplays(currentUserId, "systemReady");
        }

        mAtmInternal.showSystemReadyErrorDialogsIfNeeded();
        
        //发送一些广播ACTION_USER_STARTED  ACTION_USER_STARTING   
        if (bootingSystemUser) {
            ......
        traceLog.traceEnd(); // ActivityManagerStartApps
        traceLog.traceEnd(); // PhaseActivityManagerReady
    }
}


boolean isAllowedWhileBooting(ApplicationInfo ai) {
    return (ai.flags&ApplicationInfo.FLAG_PERSISTENT) != 0;
}

主要关注几步:

  • 关键服务等继续完成一些初始化或进一步工作
  • 已启动的进程,若进程没有FLAG_PERSISTENT标志,则会被kill掉
  • 运行goingCallback,即调用时传入的
  • 启动launcher的Activity,即桌面应用
  • 发送一些广播ACTION_USER_STARTED ACTION_USER_STARTING。

注:开机向导在这里可以在这里跳过,注意 watchDeviceProvisioning(mContext)Settings.Secure.USER_SETUP_COMPLETE属性。

goingCallback

//SystemServer.java:
traceBeginAndSlog("StartActivityManagerReadyPhase");
//启动阶段:550
mSystemServiceManager.startBootPhase(
        SystemService.PHASE_ACTIVITY_MANAGER_READY);
traceEnd();
traceBeginAndSlog("StartObservingNativeCrashes");
try {
    //监测Native Crash
    mActivityManagerService.startObservingNativeCrashes();
} catch (Throwable e) {
    reportWtf("observing native crashes", e);
}
traceEnd();

// No dependency on Webview preparation in system server. But this should
// be completed before allowing 3rd party
final String WEBVIEW_PREPARATION = "WebViewFactoryPreparation";
Future<?> webviewPrep = null;
if (!mOnlyCore && mWebViewUpdateService != null) {
    webviewPrep = SystemServerInitThreadPool.get().submit(() -> {
        Slog.i(TAG, WEBVIEW_PREPARATION);
        TimingsTraceLog traceLog = new TimingsTraceLog(
                SYSTEM_SERVER_TIMING_ASYNC_TAG, Trace.TRACE_TAG_SYSTEM_SERVER);
        traceLog.traceBegin(WEBVIEW_PREPARATION);
        ConcurrentUtils.waitForFutureNoInterrupt(mZygotePreload, "Zygote preload");
        mZygotePreload = null;
        //启动WebView相关
        mWebViewUpdateService.prepareWebViewInSystemServer();
        traceLog.traceEnd();
    }, WEBVIEW_PREPARATION);
}

if (mPackageManager.hasSystemFeature(PackageManager.FEATURE_AUTOMOTIVE)) {
    traceBeginAndSlog("StartCarServiceHelperService");
    mSystemServiceManager.startService(CAR_SERVICE_HELPER_SERVICE_CLASS);
    traceEnd();
}

traceBeginAndSlog("StartSystemUI");
try {
    //启动SystemUi
    startSystemUi(context, windowManagerF);//FLX
} catch (Throwable e) {
    reportWtf("starting System UI", e);
}
traceEnd();

// Wait for all packages to be prepared
mPackageManagerService.waitForAppDataPrepared();

//启动阶段:600
mSystemServiceManager.startBootPhase(
        SystemService.PHASE_THIRD_PARTY_APPS_CAN_START);
traceEnd();

这里几个注意的

  • startBootPhase,启动阶段。这里是550,600。这个表面大致启动的阶段,有助启动了解,具体看下面解释。
  • 在550阶段,启动了SystemUi。
SystemService.java:
/*
 * Boot Phases
 */
public static final int PHASE_WAIT_FOR_DEFAULT_DISPLAY = 100; // maybe should be a dependency?

/**
 * After receiving this boot phase, services can obtain lock settings data.
 */
public static final int PHASE_LOCK_SETTINGS_READY = 480;

/**
 * After receiving this boot phase, services can safely call into core system services
 * such as the PowerManager or PackageManager.
 */
public static final int PHASE_SYSTEM_SERVICES_READY = 500;

/**
 * After receiving this boot phase, services can safely call into device specific services.
 */
public static final int PHASE_DEVICE_SPECIFIC_SERVICES_READY = 520;

/**
 * After receiving this boot phase, services can broadcast Intents.
 */
public static final int PHASE_ACTIVITY_MANAGER_READY = 550;

/**
 * After receiving this boot phase, services can start/bind to third party apps.
 * Apps will be able to make Binder calls into services at this point.
 */
public static final int PHASE_THIRD_PARTY_APPS_CAN_START = 600;

/**
 * After receiving this boot phase, services can allow user interaction with the device.
 * This phase occurs when boot has completed and the home application has started.
 * System services may prefer to listen to this phase rather than registering a
 * broadcast receiver for ACTION_BOOT_COMPLETED to reduce overall latency.
 */
public static final int PHASE_BOOT_COMPLETED = 1000;

当桌面启动完成后,发送开机广播ACTION_BOOT_COMPLETED。(这里不赘述,可以从Launcher的resume阶段开始,调用AMS.finishBooting()方法发送)

简单总结

大致总结下AMS的启动。

  1. 系统启动后Zygote进程第一个fork出SystemServer进程
  2. SystemServer->run()->createSystemContext():创建了系统的ActivityThread对象,运行环境mSystemContext、systemUiContext
  3. SystemServer->run()->startBootstrapServices()->ActivityManagerService.Lifecycle.startService():AMS在引导服务启动方法中,通过构造函数new ActivityManagerService()进行了一些对象创建和初始化(除activity外3大组件的管理和调度对象创建;内存、电池、权限、性能、cpu等的监控等相关对象创建)start()启动服务(移除进程组、启动cpu线程、注册权限、电池等服务)
  4. SystemServer->run()->startBootstrapServices()->setSystemServiceManager()、setInstaller()、initPowerManagement()、setSystemProcess():AMS创建后进行了一系列相关的初始化和设置。
    setSystemProcess():将framework-res.apk的信息加入到SystemServer进程的LoadedApk中,并创建了SystemServer进程的ProcessRecord,加入到mPidsSelfLocked,由AMS统一管理
  5. SystemServer->run()->startOtherServices():AMS启动后的后续工作,主要调用systemReady()和运行调用时传入的goingCallback。
    systemReady()/goingCallback:各种服务或进程等AMS启动完成后需进一步完成的工作及系统相关初始化。 桌面应用在systemReady()方法中启动,systemui在goingCallback中完成。当桌面应用启动完成后,发送开机广播ACTION_BOOT_COMPLETED,到此为止。

最后附上一个图片,网上不少地方可以看见,几个类的关系很清晰。

AMS Android 模块 android ams原理_java

善始者实繁,克终者盖寡。 ---不足或不对的地方欢迎指正。