Android10系统启动之AMS服务启动详解

这篇文章我们来详细学习下Android10系统启动中AMS服务启动过程

发布日期 2020-04-17

1.概述

上一节我们讲完了SystemServer的启动过程,这一节接着上一节的步骤,来讲解ActivityManagerService的启动过程。

ActivityManagerService简称AMS,具有管理Activity行为、控制activity的生命周期、派发消息事件、内存管理等功能。

2.核心源码

/frameworks/base/services/java/com/android/server/SystemServer.java
/frameworks/base/core/java/android/app/ActivityThread.java
/frameworks/base/core/java/android/app/Instrumentation.java
/frameworks/base/core/java/android/app/ContextImpl.java
/frameworks/base/core/java/android/app/LoadedApk.java
/frameworks/base/core/java/android/app/Application.java

/frameworks/base/core/java/com/android/server/LocalServices.java
/frameworks/base/services/core/java/com/android/server/ServiceThread.java

/frameworks/base/services/core/java/com/android/server/wm/ActivityTaskManagerService.java
/frameworks/base/services/core/java/com/android/server/wm/ActivityTaskManagerInternal.java
/frameworks/base/services/core/java/com/android/server/wm/RootActivityContainer.java
/frameworks/base/services/core/java/com/android/server/am/ActivityManagerService.java

3.架构

ActivityManagerService启动共分为以下4个阶段:

阶段1:为SystemSerer进程创建Android运行环境。AMS运行与SystemServer进程中,它的许多工作依赖于该运行环境

createSystemContext() -> new ActvityThread()-->attach ->getSystemContext ->createSystemContext

阶段2:启动AMS,主要进行一些初始化工作

new ActivityManagerService()

start()

阶段3:将SystemServer进程纳入到AMS的进程管理体系中

setSystemProcess() //将framework-res.apk的信息加入到SystemServer进程的LoadedApk中;构建SystemServer进程的ProcessRecord,保存到AMS中,以便AMS进程统一管理

installSystemProvider() //安装SystemServer进程中的SettingsProvider.apk

阶段4:AMS启动完成,通知服务或应用完成后续的工作,或直接启动一些进程

AMS.systemReady() //许多服务或应用进程必须等待AMS完成启动工作后,才能启动或进行一些后续工作;AMS就是在systemReady中,通知或者启动这些等待的服务和应用进程,例如启动桌面等。

ActivityManagerService时序图如下

4. ActivityManagerService启动流程-源码分析

4.1 SystemServer启动

Zygote进行启动后,第一个Fork出SystemServer进程,SystemServer的启动流程可以参考我之前的文章,这里只分析与AMS相关的启动流程:

  1. 初始化 SystemContext
  2. 创建SystemServiceManager 对象,用来启动后面的服务
  3. 启动系统服务,共分为三种系统服务:系统引导服务(Boot Service)、核心服务(Core Service)和其他服务(Other Service)
  4. 在引导服务(Boot Service)中启动ATM、AMS服务
  5. 在其他服务(Other Service)中完成AMS的最后工作systemReady

源码:

[SystemServer.java]

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

private void run() {
    ...
    //1.初始化 System Context
    createSystemContext(); //参考[4.2]

    //2.创建 SystemServiceManager 对象,用来启动后面的服务
    mSystemServiceManager = new SystemServiceManager(mSystemContext); 
    //参考[4.3]
    mSystemServiceManager.setStartInfo(mRuntimeRestart,
            mRuntimeStartElapsedTime, mRuntimeStartUptime);
    LocalServices.addService(SystemServiceManager.class, mSystemServiceManager);
    ...
    
    //3.启动服务
    startBootstrapServices();  //启动引导服务,参考[4.1.1]
    startCoreServices();       //启动核心服务
    startOtherServices();      //启动其他服务,参考[4.1.2]
    ...
}

4.1.1 [SystemServer.java] startBootstrapServices()

说明:启动引导服务,在其中启动了ATM和AMS服务,通过AMS安装Installer、初始化Power,设置系统进程等。

源码:

private void startBootstrapServices() {
    ...
    //启动ActivityTaskManagerService服务,简称ATM,Android10新引入功能,用来管理Activity的启动、调度等功能
    //参考[4.4]
    atm = mSystemServiceManager.startService(
            ActivityTaskManagerService.Lifecycle.class).getService();

    //参考[4.5]
    //启动服务 ActivityManagerService,简称AMS
    mActivityManagerService = ActivityManagerService.Lifecycle.startService(
            mSystemServiceManager, atm);

    //安装Installer
    mActivityManagerService.setSystemServiceManager(mSystemServiceManager);
    mActivityManagerService.setInstaller(installer);
    
    //初始化PowerManager
    mActivityManagerService.initPowerManagement();
    
    //设置系统进程,参考4.6
    mActivityManagerService.setSystemProcess();
    
}

4.1.2 [SystemServer.java] startOtherServices

说明:启动其他服务,AMS启动后,完成后续桌面启动等操作

源码:

private void startOtherServices() {
    ...
    //安装SettingsProvider.apk
    mActivityManagerService.installSystemProviders();
    mActivityManagerService.setWindowManager(wm);

    //AMS启动完成,完成后续的工作,例如启动桌面等
    //参考[4.7]
    mActivityManagerService.systemReady(() -> {
        ...
    }, BOOT_TIMINGS_TRACE_LOG);
    ...
}

4.2 System Context初始化

说明: 在SystemServer的run函数中,在启动AMS之前,调用了createSystemContext函,主要用来是初始化 System Context和SystemUi Context,并设置主题

当SystemServer 调用createSystemContext()完毕后,完成以下两个内容:

  1. 得到了一个ActivityThread对象,它代表当前进程 (此时为系统进程) 的主线程;
  2. 得到了一个Context对象,对于SystemServer而言,它包含的Application运行环境与framework-res.apk有关。

源码:

[SystemServer.java]

private void createSystemContext() {
    ActivityThread activityThread = ActivityThread.systemMain();  //参考[4.2.1]
    
    //获取system context
    mSystemContext = activityThread.getSystemContext();
    //设置系统主题
    mSystemContext.setTheme(DEFAULT_SYSTEM_THEME);

    //获取systemui context
    final Context systemUiContext = activityThread.getSystemUiContext();
    //设置systemUI 主题
    systemUiContext.setTheme(DEFAULT_SYSTEM_THEME);
}

4.2.1 [ActivityThread.java] systemMain()

说明:systemMain函数主要作用是: 创建ActivityThread对象,然后调用该对象的attach函数。

源码:

[ActivityThread.java]

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对象
    ActivityThread thread = new ActivityThread(); //参考[4.2.2]
    thread.attach(true, 0); 参考[4.2.3]
    return thread;
}

4.2.2 ActivityThread 对象创建

说明:ActivityThread是Android Framework中一个非常重要的类,它代表一个应用进程的主线程,其职责就是调度及执行在该线程中运行的四大组件。

注意到此处的ActivityThread创建于SystemServer进程中。

由于SystemServer中也运行着一些系统APK,例如framework-res.apk、SettingsProvider.apk等,因此也可以认为SystemServer是一个特殊的应用进程。

AMS负责管理和调度进程,因此AMS需要通过Binder机制和应用进程通信。

为此,Android提供了一个IApplicationThread接口,该接口定义了AMS和应用进程之间的交互函数。

ActivityThread的构造函数比较简单,获取ResourcesManager的单例对象,比较关键的是它的成员变量:

源码:

public final class ActivityThread extends ClientTransactionHandler {

    ...
    //定义了AMS与应用通信的接口,拿到ApplicationThread的对象
    final ApplicationThread mAppThread = new ApplicationThread();

    //拥有自己的looper,说明ActivityThread确实可以代表事件处理线程
    final Looper mLooper = Looper.myLooper();

    //H继承Handler,ActivityThread中大量事件处理依赖此Handler
    final H mH = new H();

    //用于保存该进程的ActivityRecord
    final ArrayMap<IBinder, ActivityClientRecord> mActivities = new ArrayMap<>();

    //用于保存进程中的Service
    final ArrayMap<IBinder, Service> mServices = new ArrayMap<>();

    用于保存进程中的Application
    final ArrayList<Application> mAllApplications
        = new ArrayList<Application>();
    //构造函数
    @UnsupportedAppUsage
    ActivityThread() {
        mResourcesManager = ResourcesManager.getInstance();
    }
}

4.2.3 [ActivityThread.java] attach

说明:对于系统进程而言,ActivityThread的attach函数最重要的工作就是创建了Instrumentation、Application和Context

调用:attach(true, 0),传入的system为0

源码:

private void attach(boolean system, long startSeq) {
    mSystemThread = system;
    //传入的system为0
    if (!system) {
        //应用进程的处理流程
        ...
    } else {
        //系统进程的处理流程,该情况只在SystemServer中处理
        //创建ActivityThread中的重要成员:Instrumentation、 Application 和 Context
        mInstrumentation = new Instrumentation();
        mInstrumentation.basicInit(this);
        
        //创建系统的Context,参考[4.2.4]
        ContextImpl context = ContextImpl.createAppContext(
                this, getSystemContext().mPackageInfo);
        
        //调用LoadedApk的makeApplication函数
        mInitialApplication = context.mPackageInfo.makeApplication(true, null);
        mInitialApplication.onCreate();
    }
    
}

Instrumentation

Instrumentation是Android中的一个工具类,当该类被启用时,它将优先于应用中其它的类被初始化。

此时,系统先创建它,再通过它创建其它组件。

mInstrumentation = new Instrumentation();
mInstrumentation.basicInit(this);

Context

Context是Android中的一个抽象类,用于维护应用运行环境的全局信息。

通过Context可以访问应用的资源和类,甚至进行系统级的操作,例如启动Activity、发送广播等。

ActivityThread的attach函数中,通过下面的代码创建出系统应用对应的Context:

ContextImpl context = ContextImpl.createAppContext(this, getSystemContext().mPackageInfo);

Application:

Android中Application类用于保存应用的全局状态。

在ActivityThread中,针对系统进程,通过下面的代码创建了初始的Application:

mInitialApplication = context.mPackageInfo.makeApplication(true, null);
mInitialApplication.onCreate();

4.2.4 [ContextImpl.java] getSystemContext()

说明:创建并返回System Context

源码:

public ContextImpl getSystemContext() {
    synchronized (this) {
        if (mSystemContext == null) {
            //调用ContextImpl的静态函数createSystemContext
            mSystemContext = ContextImpl.createSystemContext(this);
        }
        return mSystemContext;
    }
}

说明:createSystemContext的内容就是创建一个LoadedApk,然后初始化一个ContextImpl对象。
注意到createSystemContext函数中,创建的LoadApk对应packageName为”android”,也就是framwork-res.apk。
由于该APK仅供SystemServer进程使用,因此创建的Context被定义为System Context。
现在该LoadedApk还没有得到framwork-res.apk实际的信息。
当PKMS启动,完成对应的解析后,AMS将重新设置这个LoadedApk。

static ContextImpl createSystemContext(ActivityThread mainThread) {
    //创建LoadedApk类,代表一个加载到系统中的APK
    //注意此时的LoadedApk只是一个空壳
    //PKMS还没有启动,无法得到有效的ApplicationInfo
    LoadedApk packageInfo = new LoadedApk(mainThread);

    //拿到ContextImpl 的对象
    ContextImpl context = new ContextImpl(null, mainThread, packageInfo, null, null, null, 0,
            null, null);
     //初始化资源信息
    context.setResources(packageInfo.getResources());
    context.mResources.updateConfiguration(context.mResourcesManager.getConfiguration(),
            context.mResourcesManager.getDisplayMetrics());
    return context;
}

4.3 SystemServiceManager 创建

说明: 通过 SystemServiceManager 的构造方法创建一个 SystemServiceManager 对象,并将该对象添加到 LocalServices 中。

源码:

private void run() {
    ...
    //1.创建SystemServiceManager对象,参考 [4.3.1]
    mSystemServiceManager = new SystemServiceManager(mSystemContext);
    mSystemServiceManager.setStartInfo(mRuntimeRestart,
            mRuntimeStartElapsedTime, mRuntimeStartUptime);
    //2.启动SystemServiceManager服务,参考[4.3.2]
    LocalServices.addService(SystemServiceManager.class, mSystemServiceManager);
    ...
}

4.3.1 [SystemServiceManager.java] SystemServiceManager()

说明:SystemServiceManager 对象主要用于管理 SystemService 的创建、启动等生命周期,SystemService 类是一个抽象类

在 SystemServiceManager 中都是通过反射创建 SystemService 中对象的,而且在 startService(@NonNull final SystemService service) 方法中,会将 SystemService 添加到 mServices 中,并调用 onStart() 方法

SystemServiceManager构造函数没有多少内容,主要是把传进来的system Context赋值给 mContext,供后续服务创建使用

源码:

public class SystemServiceManager {
    ...
    private final Context mContext;
    private final ArrayList<SystemService> mServices = new ArrayList<SystemService>();
    ...
    SystemServiceManager(Context context) {
        mContext = context;
    }

    public SystemService startService(String className) {
        final Class<SystemService> serviceClass;
        try {
            //通过反射根据类名,拿到类对象
            serviceClass = (Class<SystemService>)Class.forName(className);
        } catch (ClassNotFoundException ex) {
            Slog.i(TAG, "Starting " + className);
            ...
        }
        return startService(serviceClass);
    }

    public <T extends SystemService> T startService(Class<T> serviceClass) {
        try {
            final String name = serviceClass.getName();
            // Create the service.
            final T service;
            ...
                service = constructor.newInstance(mContext);
            ...
            startService(service);
            return service;
        } finally {
            Trace.traceEnd(Trace.TRACE_TAG_SYSTEM_SERVER);
        }
    }
    
    public void startService(@NonNull final SystemService service) {
        // Register it.
        mServices.add(service);
        // Start it.
        long time = SystemClock.elapsedRealtime();
        try {
            service.onStart();  //调用各个服务中的onStart()方法完成服务启动
        } catch (RuntimeException ex) {
            throw new RuntimeException("Failed to start service " + service.getClass().getName()
                    + ": onStart threw an exception", ex);
        }
    }
}

4.3.2 [LocalServices.java] addService(SystemServiceManager.class, mSystemServiceManager);

说明:把SystemServiceManager的对象加入到本地服务的全局注册表中

源码:

public final class LocalServices {
    private LocalServices() {}

    private static final ArrayMap<Class<?>, Object> sLocalServiceObjects =
            new ArrayMap<Class<?>, Object>();

    //返回实现指定接口的本地服务实例对象
    @SuppressWarnings("unchecked")
    public static <T> T getService(Class<T> type) {
        synchronized (sLocalServiceObjects) {
            return (T) sLocalServiceObjects.get(type);
        }
    }

    //将指定接口的服务实例添加到本地服务的全局注册表中
    public static <T> void addService(Class<T> type, T service) {
        synchronized (sLocalServiceObjects) {
            if (sLocalServiceObjects.containsKey(type)) {
                throw new IllegalStateException("Overriding service registration");
            }
            sLocalServiceObjects.put(type, service);
        }
    }

    //删除服务实例,只能在测试中使用。
    public static <T> void removeServiceForTest(Class<T> type) {
        synchronized (sLocalServiceObjects) {
            sLocalServiceObjects.remove(type);
        }
    }
}

4.4 ActivityTaskManagerService 服务启动

说明:ActivityTaskManagerService简称ATM,Android10中引入新功能,用来管理Activity的启动、调度等功能

源码:

private void startBootstrapServices() {
    ...
    //启动ATM
    atm = mSystemServiceManager.startService(
                ActivityTaskManagerService.Lifecycle.class).getService();
    ...
}

4.4.1 ATM服务启动过程

说明:从4.3.1 中我们知道SystemServiceManager.startService最终调用的是启动对象中的onStart方法

因此ATM启动,最终会调用ActivityTaskManagerService.Lifecycle.onStart()来启动ATM服务

源码:

public static final class Lifecycle extends SystemService {
        private final ActivityTaskManagerService mService;

        public Lifecycle(Context context) {
            super(context);
            //1.创建ActivityTaskManagerService,得到对象,参考[4.4.2]
            mService = new ActivityTaskManagerService(context);
        }

        @Override
        public void onStart() {
            publishBinderService(Context.ACTIVITY_TASK_SERVICE, mService);
            //2.启动ATM服务,,参考[4.4.3]
            mService.start();
        }
        ...
        public ActivityTaskManagerService getService() {
            return mService;
        }
    }

4.4.2 ActivityTaskManagerService 对象创建

说明:ActivityTaskManagerService简称ATM, Android10新引入功能,用来管理Activity的启动、调度等功能

Android10 中把原先在AMS中activity的管理移动到ATM中

从Android 10的代码路径可以看出,管理Activity的ATM被放入到的wm路径中,这个路径原先归WindowManagerService -WMS控制,谷歌的目的也是希望在将来把activity和window融合在一起,减少冗余代码以及AMS和WMS的协调工作

ATM的路径为:frameworks\base\services\core\java\com\android\server\wm

AMS的路径为:frameworks\base\services\core\java\com\android\server\am

ATM服务提供了AIDL接口供

public class ActivityTaskManagerService extends IActivityTaskManager.Stub {
    final Context mUiContext;
    final ActivityThread mSystemThread;
    final ActivityTaskManagerInternal mInternal;

    //ActivityStackSupervisor 是ATM中用来管理Activity启动和调度的核心类
    public ActivityStackSupervisor mStackSupervisor;
    //Activity 容器的根节点
    RootActivityContainer mRootActivityContainer;
    //WMS 负责窗口的管理
    WindowManagerService mWindowManager;
    
    //这是我们目前认为是"Home" Activity的过程
    WindowProcessController mHomeProcess;
    
    public ActivityTaskManagerService(Context context) {
        //拿到System Context
        mContext = context;  
        mFactoryTest = FactoryTest.getMode();

        //取出的是ActivityThread的静态变量sCurrentActivityThread
        //这意味着mSystemThread与SystemServer中的ActivityThread一致
        mSystemThread = ActivityThread.currentActivityThread();
        
        //拿到System UI Context
        mUiContext = mSystemThread.getSystemUiContext();
        mLifecycleManager = new ClientLifecycleManager();
        //拿到LocalService的对象
        mInternal = new LocalService();
        GL_ES_VERSION = SystemProperties.getInt("ro.opengles.version", GL_ES_VERSION_UNDEFINED);
    }
}

4.4.3 [ActivityTaskManagerService.java] start()

说明:将 ActivityTaskManagerInternal添加到本地服务的全局注册表中,ActivityTaskManagerInternal为抽象类

源码:

private void start() {
    LocalServices.addService(ActivityTaskManagerInternal.class, mInternal);
}

4.5 ActivityManagerService 服务启动

说明:ActivityManagerService简称AMS,在Android 10的版本中,Activity的管理和调度移到ATM中,AMS负责 service,broadcast,provider的管理和调度

源码:

private void startBootstrapServices() {
    ...
    //启动AMS
    mActivityManagerService = ActivityManagerService.Lifecycle.startService(mSystemServiceManager, atm);
    ...
}

4.5.1 AMS服务启动过程

说明:从4.3.1 中我们知道SystemServiceManager.startService最终调用的是启动对象中的onStart方法

因此AMS服务启动,最终会调用ActivityManagerService.Lifecycle.onStart()来启动ATM服务

源码:

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

    public Lifecycle(Context context) {
        super(context);
        //1.创建ActivityManagerService,得到对象,传入ATM的对象,参考[4.5.2]
        mService = new ActivityManagerService(context, sAtm);
    }

    @Override
    public void onStart() {
        mService.start();
    }
    ...
    public ActivityManagerService getService() {
        return mService;
    }
}

4.5.2 AMS 对象创建

说明:Android10中,Activity的管理和调度放入到ATM中执行,AMS中保留 service,broadcast,provider的管理和调度

构造函数初始化主要工作就是初始化一些变量,供之后的service,broadcast,provider的管理和调度

源码:

public class ActivityManagerService extends IActivityManager.Stub
        implements Watchdog.Monitor, BatteryStatsImpl.BatteryCallback {
    public ActivityManagerService(Context systemContext, ActivityTaskManagerService atm) {
        ...
        //AMS的运行上下文与SystemServer一致
        mContext = systemContext;
        ...
        //取出的是ActivityThread的静态变量sCurrentActivityThread
        //这意味着mSystemThread与SystemServer中的ActivityThread一致
        mSystemThread = ActivityThread.currentActivityThread();
        mUiContext = mSystemThread.getSystemUiContext();

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

        //创建 BroadcastQueue 前台广播对象,处理超时时长是 10s
        mFgBroadcastQueue = new BroadcastQueue(this, mHandler,
                "foreground", foreConstants, false);
        //创建 BroadcastQueue 后台广播对象,处理超时时长是 60s
        mBgBroadcastQueue = new BroadcastQueue(this, mHandler,
                "background", backConstants, true);
        //创建 BroadcastQueue 分流广播对象,处理超时时长是 60s
        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);
        
        //得到ATM的对象,调用ATM.initialize
        mActivityTaskManager = atm;
        mActivityTaskManager.initialize(mIntentFirewall, mPendingIntentController,
                DisplayThread.get().getLooper());
        //得到ATM的服务信息
        mAtmInternal = LocalServices.getService(
ActivityTaskManagerInternal.class);

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

4.5.3 [ActivityManagerService.java] start()

说明:start中做了两件事

1)启动 CPU 监控线程,在启动 CPU 监控线程之前,首先将进程复位

2)注册电池状态服务和权限管理服务

源码:

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

    //2.注册电池状态和权限管理服务
    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");
    }
}

4.6 [SystemServer.java] setSystemProcess()

说明:为系统进程设置应用程序实例并开始

源码:

private void startOtherServices() {
     //参考[4.6.1]
     Set up the Application instance for the system process and get started.
     mActivityManagerService.setSystemProcess();
 }

4.6.1 [ActivityManagerService.java] setSystemProcess()

说明:AMS的setSystemProcess主要有五个主要的功能:

  1. 注册一些服务:包括 activity、procstats、meminfo、gfxinfo、dbinfo、permission、processinfo
  2. 获取package名为“android”的应用的 ApplicationInfo;
  3. 为ActivityThread 安装 system application相关信息,将framework-res.apk对应的ApplicationInfo安装到LoadedApk中的mApplicationInfo
  4. 为systemserver 主进程开辟一个ProcessRecord来维护进程的相关信息
  5. AMS进程管理相关的操作。

源码:

public void setSystemProcess() {
  try {
      //1.注册一些服务到ServiceManager:包括 activity、procstats、meminfo、gfxinfo、dbinfo、permission、processinfo
      ServiceManager.addService(Context.ACTIVITY_SERVICE, this, /* allowIsolated= */ true,
              DUMP_FLAG_PRIORITY_CRITICAL | DUMP_FLAG_PRIORITY_NORMAL | DUMP_FLAG_PROTO);
      ServiceManager.addService(ProcessStats.SERVICE_NAME, mProcessStats);
      ServiceManager.addService("meminfo", new MemBinder(this), /* allowIsolated= */ false,
              DUMP_FLAG_PRIORITY_HIGH);
      ServiceManager.addService("gfxinfo", new GraphicsBinder(this));
      ServiceManager.addService("dbinfo", new DbBinder(this));
      if (MONITOR_CPU_USAGE) {
          ServiceManager.addService("cpuinfo", new CpuBinder(this),
                  /* allowIsolated= */ false, DUMP_FLAG_PRIORITY_CRITICAL);
      }
      ServiceManager.addService("permission", new PermissionController(this));
      ServiceManager.addService("processinfo", new ProcessInfoService(this));

      //2.通过解析framework-res.apk里的AndroidManifest.xml获得ApplicationInfo
      ApplicationInfo info = mContext.getPackageManager().getApplicationInfo(
              "android", STOCK_PM_FLAGS | MATCH_SYSTEM_ONLY);
      //3.为ActivityThread 安装 system application相关信息,将framework-res.apk对应的ApplicationInfo安装到LoadedApk中的mApplicationInfo
      mSystemThread.installSystemApplicationInfo(info, getClass().getClassLoader());

       //4.为systemserver 主进程开辟一个ProcessRecord来维护进程的相关信息
      synchronized (this) {
          ProcessRecord app = mProcessList.newProcessRecordLocked(info, info.processName,
                  false,
                  0,
                  new HostingRecord("system"));
          app.setPersistent(true); //设置进程常驻
          app.pid = MY_PID;  //为ProcessRecord赋值当前进程ID,即system_server进程ID
          app.getWindowProcessController().setPid(MY_PID);
          app.maxAdj = ProcessList.SYSTEM_ADJ;
          app.makeActive(mSystemThread.getApplicationThread(), mProcessStats);
          mPidsSelfLocked.put(app); //将ProcessRecord放到mPidSelfLocked里统一管理
          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);
                      }
                  }
              }
          });
  }

4.7 完成ActivityManagerService 最后工作[ActivityManagerService.java] systemReady()

说明: AMS的systemReady 处理分为三个阶段

阶段1:主要是调用一些关键服务的初始化函数, 然后杀死那些没有FLAG_PERSISTENT却在AMS启动完成前已经存在的进程,

同时获取一些配置参数。 需要注意的是,由于只有Java进程才会向AMS注册,而一般的Native进程不会向AMS注册,因此此处杀死的进程是Java进程。

阶段2:执行goingCallback的处理,主要的工作就是通知一些服务可以进行systemReady、systemRunning相关的工作,并进行启动服务或应用进程的工作

阶段3:启动Home Activity,当启动结束,并发送ACTION_BOOT_COMPLETED广播时,AMS的启动过程告一段落

源码:

   private void startOtherServices() {
        mActivityManagerService.systemReady(() -> {xxxxxgoingCallbackxxx,
BOOT_TIMINGS_TRACE_LOG);
    }

    public void systemReady(final Runnable goingCallback, TimingsTraceLog traceLog) {
        阶段1:关键服务的初始化
        阶段2:goingCallback处理
        阶段3:启动Home Activity,完成AMS启动
    }

4.7.1 systemReady 阶段1

说明:主要是调用一些关键服务的初始化函数, 然后杀死那些没有 FLAG_PERSISTENT 却在AMS启动完成前已经存在的进程, 同时获取一些配置参数。 需要注意的是,由于只有Java进程才会向AMS注册,而一般的Native进程不会向AMS注册,因此此处杀死的进程是Java进程。

源码:

public void systemReady(final Runnable goingCallback, TimingsTraceLog traceLog) {
    synchronized(this) {
        //第一次进入mSystemReady 为false,不走该流程
        if (mSystemReady) {
            if (goingCallback != null) {
                goingCallback.run();
            }
            return;
        }

        /** PowerSaveMode_start */
        Settings.System.putInt(mContext.getContentResolver(),
                ActivityTaskManagerService.SUPER_POWER_SAVE_MODE,
                ActivityTaskManagerService.SUPER_POWER_SAVE_MODE_NORMAL);
        /** PowerSaveMode_end */

        //这一部分主要是调用一些关键服务SystemReady相关的函数,
        //进行一些等待AMS初始完,才能进行的工作
        mActivityTaskManager.onSystemReady();
        mUserController.onSystemReady();
        mAppOpsService.systemReady();
        ...
        mSystemReady = true;
    }

    try {
        sTheRealBuildSerial = IDeviceIdentifiersPolicyService.Stub.asInterface(
                ServiceManager.getService(Context.DEVICE_IDENTIFIERS_SERVICE))
                .getSerial();
    } catch (RemoteException e) {}

    ArrayList<ProcessRecord> procsToKill = null;
    synchronized(mPidsSelfLocked) {
        //mPidsSelfLocked 中保存当前正在运行的所有进程的信息
        for (int i=mPidsSelfLocked.size()-1; i>=0; i--) {
            ProcessRecord proc = mPidsSelfLocked.valueAt(i);
            //在AMS启动完成前,如果没有FLAG_PERSISTENT标志的进程已经启动了,
            //就将这个进程加入到procsToKill中
            if (!isAllowedWhileBooting(proc.info)){
                if (procsToKill == null) {
                    procsToKill = new ArrayList<ProcessRecord>();
                }
                procsToKill.add(proc);
            }
        }
    }

    //收集已经启动的进程并杀死,排除persistent常驻进程
    synchronized(this) {
        //利用removeProcessLocked关闭procsToKill中的进程
        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");
            }
        }
        //至此系统准备完毕
        mProcessesReady = true;
    }
    ...
    mUgmInternal.onSystemReady();

}

4.7.2 systemReady 阶段2

说明:执行goingCallback的处理,主要的工作就是通知一些服务可以进行systemReady相关的工作,并进行启动服务或应用进程的工作

源码:

public void systemReady(final Runnable goingCallback, TimingsTraceLog traceLog) {
    ...
    //1.调用参数传入的runnable对象,SystemServer中有具体的定义,参考[4.7.2.1]
    if (goingCallback != null) goingCallback.run();
    ...
    //调用所有系统服务的onStartUser接口
    mSystemServiceManager.startUser(currentUserId);
    synchronized (this) {
        //启动persistent为1的application所在的进程,参考[4.7.2.2]
        startPersistentApps(PackageManager.MATCH_DIRECT_BOOT_AWARE);
        // Start up initial activity.
        mBooting = true;
        ...
}

4.7.2.1 goingCallback.run()

说明:监控Native的crash,启动WebView,执行一些服务的systemReady 和systemRunning方法

源码:

private void startOtherServices() {
  mActivityManagerService.systemReady(() -> {
  //阶段 550
  mSystemServiceManager.startBootPhase(
              SystemService.PHASE_ACTIVITY_MANAGER_READY);
  ...
  //监控Native的crash
  mActivityManagerService.startObservingNativeCrashes();
  , BOOT_TIMINGS_TRACE_LOG);
  ...
  //启动WebView
  mWebViewUpdateService.prepareWebViewInSystemServer();
  //启动systemUI,参考[4.7.2.3]
  startSystemUi(context, windowManagerF);
  
  // 执行一系列服务的systemReady方法
  networkManagementF.systemReady();
  ipSecServiceF.systemReady();
  networkStatsF.systemReady();
  connectivityF.systemReady();
  networkPolicyF.systemReady(networkPolicyInitReadySignal);
  ...
  //阶段 600
  mSystemServiceManager.startBootPhase(
              SystemService.PHASE_THIRD_PARTY_APPS_CAN_START);
  
  //执行一系列服务的systemRunning方法
  locationF.systemRunning();
  countryDetectorF.systemRunning();
  networkTimeUpdaterF.systemRunning();
  inputManagerF.systemRunning();
  telephonyRegistryF.systemRunning();
  mediaRouterF.systemRunning();
  mmsServiceF.systemRunning();
  ...
}

4.7.2.2 [ActivityManagerService.java] startPersistentApps

说明:启动persistent为1的application所在的进程

源码:

void startPersistentApps(int matchFlags) {
  if (mFactoryTest == FactoryTest.FACTORY_TEST_LOW_LEVEL) return;
  
  synchronized (this) {
      try {
           //从PKMS中得到persistent为1的ApplicationInfo
          final List<ApplicationInfo> apps = AppGlobals.getPackageManager()
                  .getPersistentApplications(STOCK_PM_FLAGS | matchFlags).getList();
          for (ApplicationInfo app : apps) {
               //由于framework-res.apk已经由系统启动,所以此处不再启动它
              if (!"android".equals(app.packageName)) {
                   //addAppLocked中将启动application所在进程 
                  addAppLocked(app, null, false, null /* ABI override */);
              }
          }
      } catch (RemoteException ex) {
      }
  }
}

4.7.2.3 启动systemUI startSystemUi

说明:启动system UI, 启动服务,服务名称”com.android.systemui/.SystemUIService”

源码:

[SystemServer.java]

private static void startSystemUi(Context context, WindowManagerService windowManager) {
  Intent intent = new Intent();
  intent.setComponent(new ComponentName("com.android.systemui",
          "com.android.systemui.SystemUIService"));
  intent.addFlags(Intent.FLAG_DEBUG_TRIAGED_MISSING);
  //Slog.d(TAG, "Starting service: " + intent);
  context.startServiceAsUser(intent, UserHandle.SYSTEM);
  windowManager.onSystemUiStarted();
}

4.7.3 systemReady 阶段3

说明:启动Home Activity,当启动结束,并发送ACTION_BOOT_COMPLETED广播时,AMS的启动过程告一段落

源码:

public  void systemReady(final Runnable goingCallback, TimingsTraceLog traceLog) {
  ...
  //1.通过ATM,启动Home Activity,参考[4.7.3.1]
  mAtmInternal.startHomeOnAllDisplays(currentUserId, "systemReady");
  ...
  //2.发送一些广播消息
  try {
      //system发送广播 ACTION_USER_STARTED = "android.intent.action.USER_STARTED";
      Intent intent = new Intent(Intent.ACTION_USER_STARTED);
      intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY
              | Intent.FLAG_RECEIVER_FOREGROUND);
      intent.putExtra(Intent.EXTRA_USER_HANDLE, currentUserId);
      broadcastIntentLocked(null, null, intent,
              null, null, 0, null, null, null, OP_NONE,
              null, false, false, MY_PID, SYSTEM_UID, callingUid, callingPid,
              currentUserId);
      //system发送广播 ACTION_USER_STARTING= "android.intent.action.USER_STARTING";
      intent = new Intent(Intent.ACTION_USER_STARTING);
      intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
      intent.putExtra(Intent.EXTRA_USER_HANDLE, currentUserId);
      broadcastIntentLocked(null, null, intent,
              null, new IIntentReceiver.Stub() {
                  @Override
                  public void performReceive(Intent intent, int resultCode, String data,
                          Bundle extras, boolean ordered, boolean sticky, int sendingUser)
                          throws RemoteException {
                  }
              }, 0, null, null,
              new String[] {INTERACT_ACROSS_USERS}, OP_NONE,
              null, true, false, MY_PID, SYSTEM_UID, callingUid, callingPid,
              UserHandle.USER_ALL);
      } catch (Throwable t) {
          Slog.wtf(TAG, "Failed sending first user broadcasts", t);
      } finally {
          Binder.restoreCallingIdentity(ident);
  }
}

4.7.3.1 [ActivityTaskManagerService] startHomeOnAllDisplays

说明:启动Home Activity

源码:

[ActivityTaskManagerService.java]

public boolean startHomeOnAllDisplays(int userId, String reason) {
    synchronized (mGlobalLock) {
        //调用RootActivityContainer的startHomeOnAllDisplays(),最终到startHomeOnDisplay()
        return mRootActivityContainer.startHomeOnAllDisplays(userId, reason);
    }
}

[RootActivityContainer.java]

boolean startHomeOnDisplay(int userId, String reason, int displayId, boolean allowInstrumenting,
        boolean fromHomeKey) {
    // Fallback to top focused display if the displayId is invalid.
    if (displayId == INVALID_DISPLAY) {
        displayId = getTopDisplayFocusedStack().mDisplayId;
    }

    Intent homeIntent = null;
    ActivityInfo aInfo = null;
    if (displayId == DEFAULT_DISPLAY) {
        //home intent有CATEGORY_HOME
        homeIntent = mService.getHomeIntent();
         //根据intent中携带的ComponentName,利用PKMS得到ActivityInfo
        aInfo = resolveHomeActivity(userId, homeIntent);
    } else if (shouldPlaceSecondaryHomeOnDisplay(displayId)) {
        Pair<ActivityInfo, Intent> info =
                RootActivityContainerMifavor.resolveSecondaryHomeActivityPcMode(this, userId, displayId);
        aInfo = info.first;
        homeIntent = info.second;
    }
    if (aInfo == null || homeIntent == null) {
        return false;
    }

    if (!canStartHomeOnDisplay(aInfo, displayId, allowInstrumenting)) {
        return false;
    }

    // Updates the home component of the intent.
    homeIntent.setComponent(new ComponentName(aInfo.applicationInfo.packageName, aInfo.name));
    homeIntent.setFlags(homeIntent.getFlags() | FLAG_ACTIVITY_NEW_TASK);
    // Updates the extra information of the intent.
    if (fromHomeKey) {
        homeIntent.putExtra(WindowManagerPolicy.EXTRA_FROM_HOME_KEY, true);
    }
    // Update the reason for ANR debugging to verify if the user activity is the one that
    // actually launched.
    final String myReason = reason + ":" + userId + ":" + UserHandle.getUserId(
            aInfo.applicationInfo.uid) + ":" + displayId;
    //启动Home Activity--Luncher
    mService.getActivityStartController().startHomeActivity(homeIntent, aInfo, myReason,
            displayId);
    return true;
}

5.Android10中AMS的一些变化

在Android 10 中安卓为了将来的方案更设计更加明确,对AMS做了很多修改,安卓的最终目的是把activity 和window融合,在Android 10.0上只是简单的代码路径变化,整体逻辑还是跟Android 9.0 类似

Android 10中引入了ActivityTaskManager--ATM的概念。

5.1 Android P 的冗余问题

Android 9.0 及以前版本,Acitivity 管理由AMS 和WMS 协作完成,导致在AMS 和WMS 中都有相似功能的实体,除了大量的代码冗余之外,二者之间的协作也非常困难。

5.2 Android 10的变化

从Android 10.0 的代码变更看,google 最终的目的是把activity 和window融合,目前发布的版本虽然做了大量的代码变更,但和P 之前的版本的流程变化不大,

目前只是简单的把代码整理到一起了,还属于中间状态,按android文档介绍,完全融合在M 甚至更靠后的版本才能完成。

目前已完成的工作:

  • 把AMS 下面只和activity 管理相关的代码移到WMS的目录下,actvityStack、activityRecord 等文件,全部移到WMS 目录下,和window 统一管理.
  • AMS 中部分文件拆分,把原来activity和其他组件融合在一起处理的文件进行拆分,activity 相关部分单独拆分,移到WMS 中统一管理。比如ActivityManagerService.java 拆分成了ActivityManagerService.java 和ActivityTaskManagerService.java 两个文件,activity 的启动由ActivityTaskManagerService.java 负责:
  • 因为Activity 和window的管理统一由WMS 完成,不再需要之前的DispayWindowController、stackWindowController 来居中协调,可以把display、stack、task 等统一管理。最终要做到完全融合,以stack 为例,完成后会把taskstack的功能完全融合进activityStack,目前只做到了在activityStack 中包含taskstack。创建、管理流程也随之发生变化。

6.总结

AMS的启动主要经历了如下几个阶段:

  • 为SystemServer进程创建Android运行环境,例如System Context
  • 启动AMS,做一些初始化的工作
  • 将SystemServer进程纳入到AMS的进程管理体系中
  • AMS启动完成,通知服务或应用完成后续的工作,调用一些服务的systemReady()方法中,
  • 启动Luncher,完成AMS的启动工作