在 SystemServer 中简单分析了 AMS 的流程, 这篇就详细地讲解 AMS 的启动流程

注意一点:AMS 所在的进程是属于 SystemServer 中的

时序图

AMS 流程

  • 创建 AMS 对象
  • 调用 ams.setSystemProcess
  • 调用 ams.installSystemProviders
  • 调用 ams.systemReady

ActivityThread 创建

在 startBootstrapServices 之前有一个流程是 createSystemContext, 该过程会创建对象有 ActivityThread,Instrumentation, ContextImpl,LoadedApk,Application, 这些都是后面 AMS 要用到的对象, 请注意它们是在这里创建的

    private void createSystemContext() {
        ActivityThread activityThread = ActivityThread.systemMain();
        mSystemContext = activityThread.getSystemContext();
        mSystemContext.setTheme(DEFAULT_SYSTEM_THEME);
    <span class="hljs-keyword">final</span> Context systemUiContext = activityThread.getSystemUiContext();
    systemUiContext.setTheme(DEFAULT_SYSTEM_THEME);
}
复制代码

创建 AMS 对象

startBootstrapServices

private void startBootstrapServices() {
    ...
    // 启动 AMS 服务
    mActivityManagerService = mSystemServiceManager.startService(
            ActivityManagerService.Lifecycle.class).getService();
<span class="hljs-comment">//设置AMS的系统服务管理器</span>
mActivityManagerService.setSystemServiceManager(mSystemServiceManager);
<span class="hljs-comment">//设置AMS的APP安装器</span>
mActivityManagerService.setInstaller(installer);
<span class="hljs-comment">//初始化AMS相关的PMS</span>
mActivityManagerService.initPowerManagement();
...

<span class="hljs-comment">//设置SystemServer</span>
mActivityManagerService.setSystemProcess();

}

复制代码

startService

    public SystemService startService(String className) {
        final Class<SystemService> serviceClass;
        try {
            serviceClass = (Class<SystemService>)Class.forName(className);
        } catch (ClassNotFoundException ex) {
            ......
        }
        return startService(serviceClass);
    }
<span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">startService</span><span class="hljs-params">(@NonNull <span class="hljs-keyword">final</span> SystemService service)</span> </span>{
    <span class="hljs-comment">// Register it.</span>
    mServices.add(service);
    <span class="hljs-comment">// Start it.</span>
    <span class="hljs-keyword">long</span> time = SystemClock.elapsedRealtime();
    <span class="hljs-keyword">try</span> {
        service.onStart();
    } <span class="hljs-keyword">catch</span> (RuntimeException ex) {
        .....
    }
    warnIfTooLong(SystemClock.elapsedRealtime() - time, service, <span class="hljs-string">"onStart"</span>);
}
复制代码

这部分比较简单, 主要是添加服务, 并调用服务的 onStart 函数

ActivityManagerService.Lifecycle.class

    public static final class Lifecycle extends SystemService {
        private final ActivityManagerService mService;
    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-title">Lifecycle</span><span class="hljs-params">(Context context)</span> </span>{
        <span class="hljs-keyword">super</span>(context);
        mService = <span class="hljs-keyword">new</span> ActivityManagerService(context);
    }

    <span class="hljs-meta">@Override</span>
    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">onStart</span><span class="hljs-params">()</span> </span>{
        mService.start();
    }

    <span class="hljs-meta">@Override</span>
    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">onCleanupUser</span><span class="hljs-params">(<span class="hljs-keyword">int</span> userId)</span> </span>{
        mService.mBatteryStatsService.onCleanupUser(userId);
    }

    <span class="hljs-function"><span class="hljs-keyword">public</span> ActivityManagerService <span class="hljs-title">getService</span><span class="hljs-params">()</span> </span>{
        <span class="hljs-keyword">return</span> mService;
    }
}
复制代码

继承 SystemService, 代表是一个系统服务, 里面主要是创建 ActivityManagerService

ActivityManagerService 对象创建

public ActivityManagerService(Context systemContext) {
    mContext = systemContext;
    mFactoryTest = FactoryTest.getMode();
    mSystemThread = ActivityThread.currentActivityThread();
<span class="hljs-comment">//创建名为"ActivityManager"的前台线程,并获取mHandler</span>
mHandlerThread = <span class="hljs-keyword">new</span> ServiceThread(TAG, android.os.Process.THREAD_PRIORITY_FOREGROUND, <span class="hljs-keyword">false</span>);
mHandlerThread.start();

mHandler = <span class="hljs-keyword">new</span> MainHandler(mHandlerThread.getLooper());

<span class="hljs-comment">//通过UiThread类,创建名为"android.ui"的线程</span>
mUiHandler = <span class="hljs-keyword">new</span> UiHandler();

......

<span class="hljs-comment">//创建目录/data/system</span>
File dataDir = Environment.getDataDirectory();
File systemDir = <span class="hljs-keyword">new</span> File(dataDir, <span class="hljs-string">"system"</span>);
systemDir.mkdirs();

<span class="hljs-comment">//创建服务BatteryStatsService</span>
mBatteryStatsService = <span class="hljs-keyword">new</span> BatteryStatsService(systemDir, mHandler);
mBatteryStatsService.getActiveStatistics().readLocked();
......

<span class="hljs-comment">//创建进程统计服务,信息保存在目录/data/system/procstats,</span>
mProcessStats = <span class="hljs-keyword">new</span> ProcessStatsService(<span class="hljs-keyword">this</span>, <span class="hljs-keyword">new</span> File(systemDir, <span class="hljs-string">"procstats"</span>));
......
<span class="hljs-comment">//CPU使用情况的追踪器执行初始化</span>
mProcessCpuTracker.init();
......
mRecentTasks = <span class="hljs-keyword">new</span> RecentTasks(<span class="hljs-keyword">this</span>);
<span class="hljs-comment">// 创建ActivityStackSupervisor对象</span>
mStackSupervisor = <span class="hljs-keyword">new</span> ActivityStackSupervisor(<span class="hljs-keyword">this</span>, mRecentTasks);
mTaskPersister = <span class="hljs-keyword">new</span> TaskPersister(systemDir, mStackSupervisor, mRecentTasks);

<span class="hljs-comment">//创建名为"CpuTracker"的线程</span>
mProcessCpuThread = <span class="hljs-keyword">new</span> Thread(<span class="hljs-string">"CpuTracker"</span>) {
    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">run</span><span class="hljs-params">()</span> </span>{
     ......
    }
};
......

}

复制代码

该过程共创建了 3 个线程

  • ActivityManager
  • android.ui
  • CpuTracker

start

mSystemServiceManager.startService 会调用服务的 onStart, 在 AMS 里 onStart 会调用他的 start

private void start() {
    Process.removeAllProcessGroups(); // 移除所有的进程组
    mProcessCpuThread.start(); // 开启 CpuTracker 线程
mBatteryStatsService.publish(mContext); <span class="hljs-comment">//启动电池统计服务</span>
mAppOpsService.publish(mContext);
<span class="hljs-comment">//创建LocalService,并添加到LocalServices</span>
LocalServices.addService(ActivityManagerInternal.class, <span class="hljs-keyword">new</span> LocalService());

}

复制代码

调用 ams.setSystemProcess

这个步骤还是在 startBootstrapServices 中执行的

    public void setSystemProcess() {
        try {
            ServiceManager.addService(Context.ACTIVITY_SERVICE, this, true);
            ServiceManager.addService(ProcessStats.SERVICE_NAME, mProcessStats);
            ServiceManager.addService("meminfo", new MemBinder(this));
            ServiceManager.addService("gfxinfo", new GraphicsBinder(this));
            ServiceManager.addService("dbinfo", new DbBinder(this));
            if (MONITOR_CPU_USAGE) {
                ServiceManager.addService("cpuinfo", new CpuBinder(this));
            }
            ServiceManager.addService("permission", new PermissionController(this));
            ServiceManager.addService("processinfo", new ProcessInfoService(this));
        ApplicationInfo info = mContext.getPackageManager().getApplicationInfo(
                <span class="hljs-string">"android"</span>, STOCK_PM_FLAGS | MATCH_SYSTEM_ONLY);
        mSystemThread.installSystemApplicationInfo(info, getClass().getClassLoader());

        ......
    } <span class="hljs-keyword">catch</span> (PackageManager.NameNotFoundException e) {
        <span class="hljs-keyword">throw</span> <span class="hljs-keyword">new</span> RuntimeException(
                <span class="hljs-string">"Unable to find android system package"</span>, e);
    }
}
复制代码

如果之前看过笔者写的 binder 系列, 应该知道 ServiceManager.addService 主要就是添加服务

该函数的主要作用是注册服务, 以及为系统进程设置 Application 单例并启动, 是由 installSystemApplicationInfo 函数完成的

该函数最终会执行到 LoadedApk 的 installSystemApplicationInfo 函数, 来设置包名为 'android' 的 package 信息

    /**
     * Sets application info about the system package.
     */
    void installSystemApplicationInfo(ApplicationInfo info, ClassLoader classLoader) {
        assert info.packageName.equals("android");
        mApplicationInfo = info;
        mClassLoader = classLoader;
    }
复制代码

调用 ams.installSystemProviders

在执行完 startBootstrapServices 后, 最后会运行 startOtherServices 函数

private void startOtherServices() {
  ......
  // 安装系统 Provider 
  mActivityManagerService.installSystemProviders();
  ......

mActivityManagerService.systemReady(new Runnable() {
public void run() {
……
}
}
}

复制代码

安装服务, 就是在某某链表中添加

installSystemProviders 中会调用 mSystemThread.installSystemProviders(providers)

 try {
        ActivityManager.getService().publishContentProviders(
                getApplicationThread(), results);
        } catch (RemoteException ex) {
            throw ex.rethrowFromSystemServer();
        }
复制代码

那最终调用到 AMS 的 publishContentProviders 函数, 这个函数就是把 providers 放到 map 里等等操作

调用 ams.systemReady

关于 systemReady 在 SystemServer 的启动流程中介绍过了

AMS 是最后一个启动的服务, 会调用 mActivityManagerService.systemReady

mActivityManagerService.systemReady(new Runnable() {
    public void run() {
        // 启动 WebView
      WebViewFactory.prepareWebViewInSystemServer();
      // 启动系统 UI
      startSystemUi(context);
  <span class="hljs-comment">// 执行一系列服务的systemReady方法</span>
  networkScoreF.systemReady();
  networkManagementF.systemReady();
  networkStatsF.systemReady();

  ......

  <span class="hljs-comment">//执行一系列服务的systemRunning方法</span>
  wallpaper.systemRunning();
  inputMethodManager.systemRunning(statusBarF);
  location.systemRunning();

}

});

复制代码

systemReady 大致流程

public final class ActivityManagerService{
<span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">systemReady</span><span class="hljs-params">(<span class="hljs-keyword">final</span> Runnable goingCallback)</span> </span>{
    ...<span class="hljs-comment">//更新操作</span>
    mSystemReady = <span class="hljs-keyword">true</span>; <span class="hljs-comment">//系统处于ready状态</span>
    removeProcessLocked(proc, <span class="hljs-keyword">true</span>, <span class="hljs-keyword">false</span>, <span class="hljs-string">"system update done"</span>);<span class="hljs-comment">//杀掉所有非persistent进程</span>
    mProcessesReady = <span class="hljs-keyword">true</span>;  <span class="hljs-comment">//进程处于ready状态</span>

    goingCallback.run(); <span class="hljs-comment">//这里有可能启动进程</span>

    addAppLocked(info, <span class="hljs-keyword">false</span>, <span class="hljs-keyword">null</span>); <span class="hljs-comment">//启动所有的persistent进程</span>
    mBooting = <span class="hljs-keyword">true</span>;  <span class="hljs-comment">//正在启动中</span>
    startHomeActivityLocked(mCurrentUserId, <span class="hljs-string">"systemReady"</span>); <span class="hljs-comment">//启动桌面</span>
    mStackSupervisor.resumeTopActivitiesLocked(); <span class="hljs-comment">//恢复栈顶的Activity</span>
}

}

复制代码
  • Android

    开放手机联盟(一个由 30 多家科技公司和手机公司组成的团体)已开发出 Android,Android 是第一个完整、开放、免费的手机平台。

    293 引用
感谢    赞同    分享    收藏    关注    反对    举报    ...