必备的系统知识#AMS

93 阅读12分钟

必备的系统知识#系统启动

必备的系统知识#AMS

必备的系统知识#PMS

必备的系统知识#Binder

必备的系统知识#Apk打包签名

必备的系统知识#Handler

一.概述

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

二.AMS的启动

1.AMS启动框图

  1. 初始化 SystemContext:

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

public static void main(String[] args) {
    new SystemServer().run();
}
 
private void run() {
    ...
    //1.初始化 System Context
    createSystemContext(); 
 
    //2.创建 SystemServiceManager 对象,用来启动后面的服务
    mSystemServiceManager = new SystemServiceManager(mSystemContext); 

    mSystemServiceManager.setStartInfo(mRuntimeRestart,
            mRuntimeStartElapsedTime, mRuntimeStartUptime);
    LocalServices.addService(SystemServiceManager.class, mSystemServiceManager);
    ...
    
    //3.启动服务
    startBootstrapServices();  //启动引导服务,4.启动ATMS AMS 5.为系统进程设置应用程序实例并开始
    startCoreServices();       //启动核心服务
    startOtherServices();      //启动其他服务, systemReady
    ...
}

2.阶段分析

1.SystemContext的初始化

SystemServer.java
private void createSystemContext() {
    //创建ActivityThread对象,然后调用该对象的attach函数。
    ActivityThread activityThread = ActivityThread.systemMain();  
    //获取system context
    mSystemContext = activityThread.getSystemContext();
    //设置系统主题
    mSystemContext.setTheme(DEFAULT_SYSTEM_THEME);
 
    //获取systemui context
    final Context systemUiContext = activityThread.getSystemUiContext();
    //设置systemUI 主题
    systemUiContext.setTheme(DEFAULT_SYSTEM_THEME);
}
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(); 
    thread.attach(true, 0);//参看后面
    return thread;
}

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();
    }
}
//对于系统进程而言,ActivityThread的attach函数最重要的工作
//就是创建了Instrumentation、Application和Context
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,参考
        ContextImpl context = ContextImpl.createAppContext(
                this, getSystemContext().mPackageInfo);
        
        //调用LoadedApk的makeApplication函数
        mInitialApplication = context.mPackageInfo.makeApplication(true, null);
        mInitialApplication.onCreate();
    }
    
}

ActivityThread.systemMain()代码分析:

ActivityThread是Android Framework中一个非常重要的类,它代表一个应用进程的主线程,其职责就是调度及执行在该线程中运行的四大组件。 注意到此处的ActivityThread创建于SystemServer进程中。 由于SystemServer中也运行着一些系统APK,例如framework-res.apk、SettingsProvider.apk等,因此也可以认为SystemServer是一个特殊的应用进程。AMS负责管理和调度进程,因此AMS需要通过Binder机制和应用进程通信。 为此,Android提供了一个IApplicationThread接口,该接口定义了AMS和应用进程之间的交互函数。 ActivityThread的构造函数比较简单,获取ResourcesManager的单例对象,比较关键的是它的成员变量。

对于系统进程而言,ActivityThread的attach函数最重要的工作就是创建了InstrumentationApplicationContext

Instrumentation是Android中的一个工具类,当该类被启用时,它将优先于应用中其它的类被初始化。 此时,系统先创建它,再通过它创建其它组件。

Context是Android中的一个抽象类,用于维护应用运行环境的全局信息。通过Context可以访问应用的资源和类,甚至进行系统级的操作,例如启动Activity、发送广播等。

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

activityThread.getSystemContext()代码分析:

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

ActivityThread.java
public ContextImpl getSystemContext() {
        synchronized (this) {
            if (mSystemContext == null) {
                //调用ContextImpl的静态函数createSystemContext
                mSystemContext = ContextImpl.createSystemContext(this);
            }
            return mSystemContext;
        }
    }
ContextImpl.java
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;
}

2.SystemServiceManager创建

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

我们从代码可以看到, 通过 SystemServiceManager 的构造方法创建一个SystemServiceManager 对象,并将该对象添加到 LocalServices 中。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);
        }
    }
}

3.ATMS的启动

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

我们知道SystemServiceManager.startService最终调用的是启动对象中的onStart方法因此ATM启动,最终会调用ActivityTaskManagerService.Lifecycle.onStart()来启动 ATM服务,启动后将ActivityTaskManagerInternal添加到本地服务的全局注册表中。

public static final class Lifecycle extends SystemService {
        private final ActivityTaskManagerService mService;
 
        public Lifecycle(Context context) {
            super(context);
            //1.创建ActivityTaskManagerService,得到对象
            mService = new ActivityTaskManagerService(context);
        }
 
        @Override
        public void onStart() {
            publishBinderService(Context.ACTIVITY_TASK_SERVICE, mService);
            //2.启动ATM服务,,
            mService.start();
        }
        ...
        public ActivityTaskManagerService getService() {
            return mService;
        }
    }

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

private void start() {
    //将 ActivityTaskManagerInternal添加到本地服务的全局注册表中,
    //ActivityTaskManagerInternal为抽象类
    LocalServices.addService(ActivityTaskManagerInternal.class, mInternal);
}

final class LocalService extends ActivityTaskManagerInternal {
   ...

}

4.AMS的启动

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

同ATMS一样,他也是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;
    }
}

//AMS中保留 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);
    }
}
//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");
    }
}

5.setSystemProcess

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

private void startBootstrapServices() {
     mActivityManagerService.setSystemProcess();
 }

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

注册一些服务:包括 activity、procstats、meminfo、gfxinfo、dbinfo、permission、processinfo

获取package名为“android”的应用的 ApplicationInfo;

为ActivityThread 安装 system application相关信息,将framework-res.apk对应的ApplicationInfo安装到LoadedApk中的mApplicationInfo

为systemserver 主进程开辟一个ProcessRecord来维护进程的相关信息

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

6.systemReady 启动桌面

   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启动
    }

AMS的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();
 
}

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

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

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

Ams.java
public  void systemReady(final Runnable goingCallback, TimingsTraceLog traceLog) {
  ...
  //1.通过ATM,启动Home Activity
  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);
  }
}
ATMS.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;
}

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) {
      }
  }
}

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