Android 8.0 ActivityManagerService 启动流程

ActivityManagerService(以下简称为 AMS)是 Android 中最核心的系统服务之一,我认为 AMS 最重要的功能有两个:

  1. 对应用程序进程的管理:应用程序进程的创建、销毁和优先级的调整
  2. 对应用程序进程中的四大组件进行管理:最常见的 Activity、Service 等四大组件的生命周期方法都是通过 AMS 间接地调度执行的

这篇文章对 Android 8.0 系统中的 AMS 启动流程加以分析。

一. 整体结构

首先,我们来看一下 AMS 中管理应用程序进程和应用程序进程中四大组件的相关类和他们的关系图


AMS.png

图片来源:Android7.1 ActivityManagerService概述

ActivityThread 是应用程序进程的入口,负责对应用程序进程中主线程的管理,被 AMS 调度从而直接调用四大组件的生命周期方法

在 AMS 中并不能直接管理四大组件,四大组件在 AMS 中都有一个对应的类,AMS 中管理的是 ActivityRecord 等对象,再通过 Binder 通信向 ApplicationThread 发送消息,ApplicationThread 再通过 Handler 将消息发送到主线程中,最后就会去调用四大组件的生命周期方法

应用程序进程中的四大组件 AMS 中的四大组件
Activity ActivityRecord
Service ServiceRecord
Broadcast BroadcastRecord
ContentProvider ContentProviderRecord

接下来,我们分析下 AMS 的启动流程

二. SystemServer 的启动

和之前分析 WMS 的启动一样,从 SystemServer 中开始分析。

2.1 SystemServer 初始化

public final class SystemServer {

    /**
     * The main entry point from zygote.
     */
    public static void main(String[] args) {
        new SystemServer().run();
    }

    private void run() {
        ......
        // 初始化虚拟机内存
        VMRuntime.getRuntime().clearGrowthLimit();
        VMRuntime.getRuntime().setTargetHeapUtilization(0.8f);
        
        //设置进程优先级,初始化 MainLooper
        android.os.Process.setThreadPriority(android.os.Process.THREAD_PRIORITY_FOREGROUND);
        android.os.Process.setCanSelfBackground(false);
        Looper.prepareMainLooper();
        
        // 加载 native services
        System.loadLibrary("android_servers");
        ......
        // 代码 1,初始化 System Context
        createSystemContext();
        
        // 代码 2,创建 SystemServiceManager 对象
        mSystemServiceManager = new SystemServiceManager(mSystemContext);
        mSystemServiceManager.setRuntimeRestarted(mRuntimeRestart);
        LocalServices.addService(SystemServiceManager.class, mSystemServiceManager);
        // 为初始化任务准备线程池
        SystemServerInitThreadPool.get();
        
        // 代码 3,启动系统服务
        try {
            traceBeginAndSlog("StartServices");
            startBootstrapServices();
            startCoreServices();
            startOtherServices();
            SystemServerInitThreadPool.shutdown();
        } catch (Throwable ex) {
            Slog.e("System", "******************************************");
            Slog.e("System", "************ Failure starting system services", ex);
            throw ex;
        } finally {
            traceEnd();
        }
        ......
        Looper.loop();
    }
}

从上面代码中可以看到,在 SystemServer 中也持有 Context 对象,这个 Context 真是无处不在。SystemServer 初始化过程中,我们主要分析三点:

  1. 代码 1 处初始化 SystemContext
  2. 代码 2 处创建 SystemServiceManager 对象
  3. 代码 3 处启动系统服务,共分为三种系统服务:系统引导服务(BootstrapServices)、核心服务(CoreServices)和其他服务(OtherServices)

2.2 初始化 SystemContext

首先来到 createSystemContext() 方法中,代码如下所示

    private void createSystemContext() {
        ActivityThread activityThread = ActivityThread.systemMain();
        mSystemContext = activityThread.getSystemContext();
        mSystemContext.setTheme(DEFAULT_SYSTEM_THEME);

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

createSystemContext() 中调用 ActivityThread.systemMain() 创建了一个 ActivityThread 对象,并设置了此 ActivityThread 对象 SystemContext 和 SystemUIContext 的主题,接着我们看下 ActivityThread.systemMain() 方法

public final class ActivityThread {

    ......

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

    ......

    private void attach(boolean system) {
        sCurrentActivityThread = this;
        mSystemThread = system;
        if (!system) {
            // 非系统启动
            ......
        } else {
            // 通过 SystemServer 启动 ActivityThread 对象
            android.ddm.DdmHandleAppName.setAppName("system_process",
                    UserHandle.myUserId());
            try {
                // 代码 1,创建 Instrumentation、Application、Context 对象
                mInstrumentation = new Instrumentation();
                ContextImpl context = ContextImpl.createAppContext(
                        this, getSystemContext().mPackageInfo);
                mInitialApplication = context.mPackageInfo.makeApplication(true, null);
                mInitialApplication.onCreate();
            } catch (Exception e) {
                throw new RuntimeException(
                        "Unable to instantiate Application():" + e.toString(), e);
            }
        }
        
        // 为 ViewRootImpl 设置配置更新回调,当系统资源配置(如:系统字体)发生变化时,通知系统配置发生变化
        ViewRootImpl.ConfigChangedCallback configChangedCallback
                = (Configuration globalConfig) -> {
            synchronized (mResourcesManager) {
                // We need to apply this change to the resources immediately, because upon returning
                // the view hierarchy will be informed about it.
                if (mResourcesManager.applyConfigurationToResourcesLocked(globalConfig,
                        null /* compat */)) {
                    updateLocaleListFromAppContext(mInitialApplication.getApplicationContext(),
                            mResourcesManager.getConfiguration().getLocales());

                    // This actually changed the resources! Tell everyone about it.
                    if (mPendingConfiguration == null
                            || mPendingConfiguration.isOtherSeqNewer(globalConfig)) {
                        mPendingConfiguration = globalConfig;
                        sendMessage(H.CONFIGURATION_CHANGED, globalConfig);
                    }
                }
            }
        };
        ViewRootImpl.addConfigCallback(configChangedCallback);
    }

    ......

}
  • 在代码 1 处,创建了一个 Instrumentation 对象和 Application 对象,可见 Application 不仅在应用程序进程中有,在 SystemServer 进程中也有
  • 在创建 Application 对象时,通过 getSystemContext() 方法可以得到System Context 对象
    public ContextImpl getSystemContext() {
        synchronized (this) {
            if (mSystemContext == null) {
                mSystemContext = ContextImpl.createSystemContext(this);
            }
            return mSystemContext;
        }
    }

getSystemContext() 方法中,最终调用了 ContextImpl.createSystemContext(ActivityThread mainThread) 方法创建了一个 System Context 对象,我们走到 ContextImpl 类中

class ContextImpl extends Context {

    ......

    static ContextImpl createSystemContext(ActivityThread mainThread) {
        LoadedApk packageInfo = new LoadedApk(mainThread);
        ContextImpl context = new ContextImpl(null, mainThread, packageInfo, null, null, null, 0,
                null);
        context.setResources(packageInfo.getResources());
        context.mResources.updateConfiguration(context.mResourcesManager.getConfiguration(),
                context.mResourcesManager.getDisplayMetrics());
        return context;
    }

    ......

    static ContextImpl createAppContext(ActivityThread mainThread, LoadedApk packageInfo) {
        if (packageInfo == null) throw new IllegalArgumentException("packageInfo");
        ContextImpl context = new ContextImpl(null, mainThread, packageInfo, null, null, null, 0,
                null);
        context.setResources(packageInfo.getResources());
        return context;
    }

    ......
}

在创建 System Context 对象时,首先创建了一个 LoadadApk 对象,然后通过 ContextImpl 构造方法创建了一个 Context 对象

2.3 SystemServiceManager 对象

然后再看下创建 SystemServiceManager 对象的创建

            // Create the system service manager.
            mSystemServiceManager = new SystemServiceManager(mSystemContext);
            mSystemServiceManager.setRuntimeRestarted(mRuntimeRestart);
            LocalServices.addService(SystemServiceManager.class, mSystemServiceManager);

通过 SystemServiceManager 的构造方法创建一个 SystemServiceManager 对象,并将该对象添加到 LocalServices 中,这两个类的源码都不复杂,简单分析一下

SystemServiceManager 对象主要用于管理 SystemService 的创建、启动等生命周期,SystemService 类是一个抽象类
在 SystemServiceManager 中都是通过反射创建 SystemService 中对象的,而且在 startService(@NonNull final SystemService service) 方法中,会将 SystemService 添加到 mServices 中,并调用 onStart() 方法

public class SystemServiceManager {

    private final Context mContext;

    // Services that should receive lifecycle events.
    private final ArrayList<SystemService> mServices = new ArrayList<SystemService>();
    
    ......

    SystemServiceManager(Context context) {
        mContext = context;
    }

    @SuppressWarnings("unchecked")
    public SystemService startService(String className) {
        final Class<SystemService> serviceClass;
        try {
            serviceClass = (Class<SystemService>)Class.forName(className);
        } catch (ClassNotFoundException ex) {
            Slog.i(TAG, "Starting " + className);
            throw new RuntimeException("Failed to create service " + className
                    + ": service class not found, usually indicates that the caller should "
                    + "have called PackageManager.hasSystemFeature() to check whether the "
                    + "feature is available on this device before trying to start the "
                    + "services that implement it", ex);
        }
        return startService(serviceClass);
    }

    public <T extends SystemService> T startService(Class<T> serviceClass) {
        try {
            final String name = serviceClass.getName();
            Slog.i(TAG, "Starting " + name);
            Trace.traceBegin(Trace.TRACE_TAG_SYSTEM_SERVER, "StartService " + name);

            // 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);
            } catch (InstantiationException ex) {
                ......
            }    

            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 = System.currentTimeMillis();
        try {
            service.onStart();
        } catch (RuntimeException ex) {
            throw new RuntimeException("Failed to start service " + service.getClass().getName()
                    + ": onStart threw an exception", ex);
        }
        warnIfTooLong(System.currentTimeMillis() - time, service, "onStart");
    }
  
    ......

}

LocalServices 中主要通过静态的 ArrayMap 持有所有的 Service 对象,它和 SystemServiceManager 有点类型,所不同的是,在 LocalServices 中持有的 Service 对象并不是 Binder 对象,只可以在同一进程中使用

public final class LocalServices {
    private LocalServices() {}

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

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

2.4 启动 AMS 系统服务

在上面的介绍中,一共有三种服务会被启动:系统引导服务(BootstrapServices)、核心服务(CoreServices)和其他服务(OtherServices),而 AMS 属于系统引导类服务

    private void startBootstrapServices() {
        Slog.i(TAG, "Reading configuration...");
        final String TAG_SYSTEM_CONFIG = "ReadingSystemConfig";
        traceBeginAndSlog(TAG_SYSTEM_CONFIG);
        SystemServerInitThreadPool.get().submit(SystemConfig::getInstance, TAG_SYSTEM_CONFIG);
        traceEnd();

        // 在 Installer 中会创建一些关键的目录,比如:/data/user
        traceBeginAndSlog("StartInstaller");
        Installer installer = mSystemServiceManager.startService(Installer.class);
        traceEnd();

        // 创建一些设备相关的信息
        traceBeginAndSlog("DeviceIdentifiersPolicyService");
        mSystemServiceManager.startService(DeviceIdentifiersPolicyService.class);
        traceEnd();

        // 代码 1,启动 AMS
        traceBeginAndSlog("StartActivityManager");
        mActivityManagerService = mSystemServiceManager.startService(
                ActivityManagerService.Lifecycle.class).getService();
        // 将 SystemServiceManager 对象设置给 AMS 对象
        mActivityManagerService.setSystemServiceManager(mSystemServiceManager);
        // 将 installer 设置给 AMS 对象
        mActivityManagerService.setInstaller(installer);
        traceEnd();
        
        ......
      
        // Now that the power manager has been started, let the activity manager
        // initialize power management features.
        traceBeginAndSlog("InitPowerManagement");
        mActivityManagerService.initPowerManagement();
        traceEnd();
      
        ......

        // Set up the Application instance for the system process and get started.
        traceBeginAndSlog("SetSystemProcess");
        mActivityManagerService.setSystemProcess();
        traceEnd();

        ......
    }
    
    ......

    private void startOtherServices() {
    
        ......
        traceBeginAndSlog("SetWindowManagerService");
        mActivityManagerService.setWindowManager(wm);
        traceEnd();
        ......
      
        mActivityManagerService.systemReady(() -> {

            ......

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

            ......
        }
    }
  • 在代码 1 处启动 AMS 时,通过 ActivityManagerService.Lifecycle 这个类,如下所示,ActivityManagerService.Lifecycle 类很简单,继承 SystemService,是一个 ActivityManagerService 的包装类
  • SystemServiceManager 通过 ActivityManagerService.Lifecycle 间接的持有了 AMS 的对象,然后调用了 AMS 的 initPowerManagement()setSystemProcess() 方法
  • startOtherServices() 方法中,创建了 WMS 对象,并将 WMS 对象设置进 AMS 中,最后调用了 AMS 的 systemReady(final Runnable goingCallback, BootTimingsTraceLog traceLog) 方法,告诉 AMS 可以启动运行了

在 ActivityManagerService.Lifecycle 通过 AMS 的构造方法创建了一个 AMS 对象并调用了其 start() 方法

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

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

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

        public ActivityManagerService getService() {
            return mService;
        }
    }

三. AMS 的启动流程

在上一节中,我们分析到了 AMS 的构造方法和 start() 方法,这一节就通过这个入口,详细的分析 AMS 的启动流程

3.1 AMS 的构造方法

public class ActivityManagerService extends IActivityManager.Stub
        implements Watchdog.Monitor, BatteryStatsImpl.BatteryCallback {

    ......

    public ActivityManagerService(Context systemContext) {
        LockGuard.installLock(this, LockGuard.INDEX_ACTIVITY);
        // 用于测试,可忽略
        mInjector = new Injector();
        // 设置 System Context 对象,此 systemContext 就是在 SystemServer 和 ActivityThread 中创建和使用的 System Context 对象
        mContext = systemContext;

        mFactoryTest = FactoryTest.getMode();
        // 设置 ActivityThread 对象,就是在 SystemServer 中创建的 ActivityThread 对象
        mSystemThread = ActivityThread.currentActivityThread();
        mUiContext = mSystemThread.getSystemUiContext();

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

        mPermissionReviewRequired = mContext.getResources().getBoolean(
                com.android.internal.R.bool.config_permissionReviewRequired);
        
        // 创建一个 Thread 和其对应的 Handler
        mHandlerThread = new ServiceThread(TAG,
                THREAD_PRIORITY_FOREGROUND, false /*allowIo*/);
        mHandlerThread.start();
        mHandler = new MainHandler(mHandlerThread.getLooper());
        mUiHandler = mInjector.getUiHandler(this);

        mConstants = new ActivityManagerConstants(this, mHandler);

        /* static; one-time init here */
        if (sKillHandler == null) {
            sKillThread = new ServiceThread(TAG + ":kill",
                    THREAD_PRIORITY_BACKGROUND, true /* allowIo */);
            sKillThread.start();
            sKillHandler = new KillHandler(sKillThread.getLooper());
        }

        // 创建 BroadcastQueue 前台广播对象,处理超时时长是 10s
        mFgBroadcastQueue = new BroadcastQueue(this, mHandler,
                "foreground", BROADCAST_FG_TIMEOUT, false);
        // 创建 BroadcastQueue 后台广播对象,处理超时时长是 60s
        mBgBroadcastQueue = new BroadcastQueue(this, mHandler,
                "background", BROADCAST_BG_TIMEOUT, true);
        mBroadcastQueues[0] = mFgBroadcastQueue;
        mBroadcastQueues[1] = mBgBroadcastQueue;
    
        // 创建 ActiveServices 对象,用于管理 ServiceRecord 对象
        mServices = new ActiveServices(this);
        // 创建 ProviderMap 对象,用于管理 ContentProviderRecord 对象
        mProviderMap = new ProviderMap(this);
        // 创建 AppErrors 对象,用于处理应用程序的异常
        mAppErrors = new AppErrors(mUiContext, this);

        // 初始化 /data/system 目录
        File dataDir = Environment.getDataDirectory();
        File systemDir = new File(dataDir, "system");
        systemDir.mkdirs();
        // 初始化电池状态信息,进程状态 和 应用权限管理
        mBatteryStatsService = new BatteryStatsService(systemDir, mHandler);
        mBatteryStatsService.getActiveStatistics().readLocked();
        mBatteryStatsService.scheduleWriteToDisk();
        mOnBattery = DEBUG_POWER ? true
                : mBatteryStatsService.getActiveStatistics().getIsOnBattery();
        mBatteryStatsService.getActiveStatistics().setCallback(this);

        mProcessStats = new ProcessStatsService(this, new File(systemDir, "procstats"));

        // 启动 Android 权限检查服务,注册对应的回调接口
        mAppOpsService = mInjector.getAppOpsService(new File(systemDir, "appops.xml"), mHandler);
        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);
                            }
                        }
                    }
                });

        mGrantFile = new AtomicFile(new File(systemDir, "urigrants.xml"));

        mUserController = new UserController(this);

        mVrController = new VrController(this);

        GL_ES_VERSION = SystemProperties.getInt("ro.opengles.version",
            ConfigurationInfo.GL_ES_VERSION_UNDEFINED);

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

        mTrackingAssociations = "1".equals(SystemProperties.get("debug.track-associations"));
        mTempConfig.setToDefaults();
        mTempConfig.setLocales(LocaleList.getDefault());
        mConfigurationSeq = mTempConfig.seq = 1;

        //创建 ActivityStackSupervisor 对象,是 AMS 中 ActivityRecord 和 TaskRecord 管理和调度的重要类
        mStackSupervisor = createStackSupervisor();
        mStackSupervisor.onConfigurationChanged(mTempConfig);
        mKeyguardController = mStackSupervisor.mKeyguardController;
        mCompatModePackages = new CompatModePackages(this, systemDir, mHandler);
        mIntentFirewall = new IntentFirewall(new IntentFirewallInterface(), mHandler);
        mTaskChangeNotificationController =
                new TaskChangeNotificationController(this, mStackSupervisor, mHandler);
        // 创建 ActivityStarter 对象,用于启动 Activity
        mActivityStarter = new ActivityStarter(this, mStackSupervisor);
        // 最近使用的 RecentTasks
        mRecentTasks = new RecentTasks(this, mStackSupervisor);
        
        // 创建一个用于更新 CPU 信息的线程
        mProcessCpuThread = new Thread("CpuTracker") {
            @Override
            public void run() {
                synchronized (mProcessCpuTracker) {
                    mProcessCpuInitLatch.countDown();
                    mProcessCpuTracker.init();
                }
                while (true) {
                    try {
                        try {
                            synchronized(this) {
                                final long now = SystemClock.uptimeMillis();
                                long nextCpuDelay = (mLastCpuTime.get()+MONITOR_CPU_MAX_TIME)-now;
                                long nextWriteDelay = (mLastWriteTime+BATTERY_STATS_TIME)-now;
                                //Slog.i(TAG, "Cpu delay=" + nextCpuDelay
                                //        + ", write delay=" + nextWriteDelay);
                                if (nextWriteDelay < nextCpuDelay) {
                                    nextCpuDelay = nextWriteDelay;
                                }
                                if (nextCpuDelay > 0) {
                                    mProcessCpuMutexFree.set(true);
                                    this.wait(nextCpuDelay);
                                }
                            }
                        } catch (InterruptedException e) {
                        }
                        updateCpuStatsNow();
                    } catch (Exception e) {
                        Slog.e(TAG, "Unexpected exception collecting process stats", e);
                    }
                }
            }
        };
        
        // 将此 AMS 对象添加到 Watchdog 中
        Watchdog.getInstance().addMonitor(this);
        Watchdog.getInstance().addThread(mHandler);
    }
    
    ......

}

在 AMS 的构造方法中主要做了以下事情:

  1. 初始化一些对象属性,包括 Context、ActivityThread、ServiceThread、MainHandler、ActivityManagerConstants 等对象
  2. 创建和管理四大组件相关的类对象,包括 BroadcastQueue、ActiveServices、ProviderMap、ActivityStackSupervisor、RecentTasks 和 ActivityStarter 等对象
  3. 创建一个 CPU 监控线程 mProcessCpuThread

3.2 一些初始化方法

start() 方法中,主要完成了以下两个事:

  1. 启动 CPU 监控线程,在启动 CPU 监控线程之前,首先将进程复位
  2. 注册电池状态服务和权限管理服务
    private void start() {
        // 在启动 CPU 监控线程之前,首先将进程复位
        removeAllProcessGroups();
        mProcessCpuThread.start();
      
        // 注册电池状态和权限管理服务
        mBatteryStatsService.publish(mContext);
        mAppOpsService.publish(mContext);
        Slog.d("AppOps", "AppOpsService published");
        LocalServices.addService(ActivityManagerInternal.class, new LocalService());
        // Wait for the synchronized block started in mProcessCpuThread,
        // so that any other acccess 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() 方法之外,还调用了 initPowerManagement()setSystemProcess()setWindowManager(WindowManagerService wm) 方法

    // 初始化一些 PowerManager 相关类
    public void initPowerManagement() {
        mStackSupervisor.initPowerManagement();
        mBatteryStatsService.initPowerManagement();
        mLocalPowerManager = LocalServices.getService(PowerManagerInternal.class);
        PowerManager pm = (PowerManager)mContext.getSystemService(Context.POWER_SERVICE);
        mVoiceWakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "*voice*");
        mVoiceWakeLock.setReferenceCounted(false);
    }

    // 初始化一些系统信息,包括 meminfo、gfxinfo、dbinfo、cpuinfo 等信息
    // 并创建一个系统进行信息类 ProcessRecord 对象
    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(
                    "android", STOCK_PM_FLAGS | MATCH_SYSTEM_ONLY);
            mSystemThread.installSystemApplicationInfo(info, getClass().getClassLoader());

            synchronized (this) {
                ProcessRecord app = newProcessRecordLocked(info, info.processName, false, 0);
                app.persistent = true;
                app.pid = MY_PID;
                app.maxAdj = ProcessList.SYSTEM_ADJ;
                app.makeActive(mSystemThread.getApplicationThread(), mProcessStats);
                synchronized (mPidsSelfLocked) {
                    mPidsSelfLocked.put(app.pid, app);
                }
                updateLruProcessLocked(app, false, null);
                updateOomAdjLocked();
            }
        } catch (PackageManager.NameNotFoundException e) {
            throw new RuntimeException(
                    "Unable to find android system package", e);
        }
    }

    // 持有 WMS 对象的引用,并为 mStackSupervisor 和 mActivityStarter 对象设置 WMS 对象
    public void setWindowManager(WindowManagerService wm) {
        mWindowManager = wm;
        mStackSupervisor.setWindowManager(wm);
        mActivityStarter.setWindowManager(wm);
    }

在所有初始化完成之后,会调用 systemReady(final Runnable goingCallback, BootTimingsTraceLog traceLog) 方法

    public void systemReady(final Runnable goingCallback, BootTimingsTraceLog traceLog) {
        synchronized(this) {
            if (mSystemReady) {
                // If we're done calling all the receivers, run the next "boot phase" passed in
                // by the SystemServer
                if (goingCallback != null) {
                    goingCallback.run();
                }
                return;
            }

            // 调用 mVrController、mUserController 等对象的 onSystemReady() 方法
            mLocalDeviceIdleController
                    = LocalServices.getService(DeviceIdleController.LocalService.class);
            mAssistUtils = new AssistUtils(mContext);
            mVrController.onSystemReady();
            // Make sure we have the current profile info, since it is needed for security checks.
            mUserController.onSystemReady();
            mRecentTasks.onSystemReadyLocked();
            mAppOpsService.systemReady();
            mSystemReady = true;
        }

        ......
        // 启动系统 Home 应用程序,也就是 Launcher 应用
        startHomeActivityLocked(currentUserId, "systemReady");
        ......
    }

systemReady(final Runnable goingCallback, BootTimingsTraceLog traceLog) 方法调完之后,AMS 系统服务大概的启动流程就分析完成了,启动时序图如下所示

AMS1.png

图片来源 ActivityManagerService启动解析

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 159,569评论 4 363
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 67,499评论 1 294
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 109,271评论 0 244
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 44,087评论 0 209
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 52,474评论 3 287
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 40,670评论 1 222
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 31,911评论 2 313
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 30,636评论 0 202
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 34,397评论 1 246
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 30,607评论 2 246
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 32,093评论 1 261
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 28,418评论 2 254
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 33,074评论 3 237
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 26,092评论 0 8
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 26,865评论 0 196
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 35,726评论 2 276
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 35,627评论 2 270

推荐阅读更多精彩内容