Android 8.0 ActivityManagerService 啟動流程

ActivityManagerService(以下簡稱為 AMS)是 Android 中最核心的系統(tǒng)服務(wù)之一,我認為 AMS 最重要的功能有兩個:

  1. 對應用程序進程的管理:應用程序進程的創(chuàng)建、銷毀和優(yōu)先級的調(diào)整
  2. 對應用程序進程中的四大組件進行管理:最常見的 Activity、Service 等四大組件的生命周期方法都是通過 AMS 間接地調(diào)度執(zhí)行的

這篇文章對 Android 8.0 系統(tǒng)中的 AMS 啟動流程加以分析。

一. 整體結(jié)構(gòu)

首先机久,我們來看一下 AMS 中管理應用程序進程和應用程序進程中四大組件的相關(guān)類和他們的關(guān)系圖


AMS.png

圖片來源:Android7.1 ActivityManagerService概述

ActivityThread 是應用程序進程的入口凡泣,負責對應用程序進程中主線程的管理,被 AMS 調(diào)度從而直接調(diào)用四大組件的生命周期方法

在 AMS 中并不能直接管理四大組件轨帜,四大組件在 AMS 中都有一個對應的類魄咕,AMS 中管理的是 ActivityRecord 等對象,再通過 Binder 通信向 ApplicationThread 發(fā)送消息蚌父,ApplicationThread 再通過 Handler 將消息發(fā)送到主線程中哮兰,最后就會去調(diào)用四大組件的生命周期方法

應用程序進程中的四大組件 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() {
        ......
        // 初始化虛擬機內(nèi)存
        VMRuntime.getRuntime().clearGrowthLimit();
        VMRuntime.getRuntime().setTargetHeapUtilization(0.8f);
        
        //設(shè)置進程優(yōu)先級,初始化 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右遭,創(chuàng)建 SystemServiceManager 對象
        mSystemServiceManager = new SystemServiceManager(mSystemContext);
        mSystemServiceManager.setRuntimeRestarted(mRuntimeRestart);
        LocalServices.addService(SystemServiceManager.class, mSystemServiceManager);
        // 為初始化任務(wù)準備線程池
        SystemServerInitThreadPool.get();
        
        // 代碼 3,啟動系統(tǒng)服務(wù)
        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 處創(chuàng)建 SystemServiceManager 對象
  3. 代碼 3 處啟動系統(tǒng)服務(wù)滚婉,共分為三種系統(tǒng)服務(wù):系統(tǒng)引導服務(wù)(BootstrapServices)、核心服務(wù)(CoreServices)和其他服務(wù)(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() 中調(diào)用 ActivityThread.systemMain() 創(chuàng)建了一個 ActivityThread 對象满哪,并設(shè)置了此 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) {
            // 非系統(tǒng)啟動
            ......
        } else {
            // 通過 SystemServer 啟動 ActivityThread 對象
            android.ddm.DdmHandleAppName.setAppName("system_process",
                    UserHandle.myUserId());
            try {
                // 代碼 1劝篷,創(chuàng)建 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 設(shè)置配置更新回調(diào)娇妓,當系統(tǒng)資源配置(如:系統(tǒng)字體)發(fā)生變化時像鸡,通知系統(tǒng)配置發(fā)生變化
        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 處,創(chuàng)建了一個 Instrumentation 對象和 Application 對象哈恰,可見 Application 不僅在應用程序進程中有只估,在 SystemServer 進程中也有
  • 在創(chuàng)建 Application 對象時,通過 getSystemContext() 方法可以得到System Context 對象
    public ContextImpl getSystemContext() {
        synchronized (this) {
            if (mSystemContext == null) {
                mSystemContext = ContextImpl.createSystemContext(this);
            }
            return mSystemContext;
        }
    }

getSystemContext() 方法中着绷,最終調(diào)用了 ContextImpl.createSystemContext(ActivityThread mainThread) 方法創(chuàng)建了一個 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;
    }

    ......
}

在創(chuàng)建 System Context 對象時,首先創(chuàng)建了一個 LoadadApk 對象荠医,然后通過 ContextImpl 構(gòu)造方法創(chuàng)建了一個 Context 對象

2.3 SystemServiceManager 對象

然后再看下創(chuàng)建 SystemServiceManager 對象的創(chuàng)建

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

通過 SystemServiceManager 的構(gòu)造方法創(chuàng)建一個 SystemServiceManager 對象吁脱,并將該對象添加到 LocalServices 中桑涎,這兩個類的源碼都不復雜,簡單分析一下

SystemServiceManager 對象主要用于管理 SystemService 的創(chuàng)建兼贡、啟動等生命周期攻冷,SystemService 類是一個抽象類
在 SystemServiceManager 中都是通過反射創(chuàng)建 SystemService 中對象的,而且在 startService(@NonNull final SystemService service) 方法中遍希,會將 SystemService 添加到 mServices 中等曼,并調(diào)用 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 中主要通過靜態(tài)的 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 系統(tǒng)服務(wù)

在上面的介紹中废封,一共有三種服務(wù)會被啟動:系統(tǒng)引導服務(wù)(BootstrapServices)州泊、核心服務(wù)(CoreServices)和其他服務(wù)(OtherServices),而 AMS 屬于系統(tǒng)引導類服務(wù)

    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 中會創(chuàng)建一些關(guān)鍵的目錄虱饿,比如:/data/user
        traceBeginAndSlog("StartInstaller");
        Installer installer = mSystemServiceManager.startService(Installer.class);
        traceEnd();

        // 創(chuàng)建一些設(shè)備相關(guān)的信息
        traceBeginAndSlog("DeviceIdentifiersPolicyService");
        mSystemServiceManager.startService(DeviceIdentifiersPolicyService.class);
        traceEnd();

        // 代碼 1拥诡,啟動 AMS
        traceBeginAndSlog("StartActivityManager");
        mActivityManagerService = mSystemServiceManager.startService(
                ActivityManagerService.Lifecycle.class).getService();
        // 將 SystemServiceManager 對象設(shè)置給 AMS 對象
        mActivityManagerService.setSystemServiceManager(mSystemServiceManager);
        // 將 installer 設(shè)置給 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 的對象披蕉,然后調(diào)用了 AMS 的 initPowerManagement()setSystemProcess() 方法
  • startOtherServices() 方法中颈畸,創(chuàng)建了 WMS 對象,并將 WMS 對象設(shè)置進 AMS 中没讲,最后調(diào)用了 AMS 的 systemReady(final Runnable goingCallback, BootTimingsTraceLog traceLog) 方法眯娱,告訴 AMS 可以啟動運行了

在 ActivityManagerService.Lifecycle 通過 AMS 的構(gòu)造方法創(chuàng)建了一個 AMS 對象并調(diào)用了其 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 的啟動流程

在上一節(jié)中,我們分析到了 AMS 的構(gòu)造方法和 start() 方法爬凑,這一節(jié)就通過這個入口徙缴,詳細的分析 AMS 的啟動流程

3.1 AMS 的構(gòu)造方法

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

    ......

    public ActivityManagerService(Context systemContext) {
        LockGuard.installLock(this, LockGuard.INDEX_ACTIVITY);
        // 用于測試,可忽略
        mInjector = new Injector();
        // 設(shè)置 System Context 對象嘁信,此 systemContext 就是在 SystemServer 和 ActivityThread 中創(chuàng)建和使用的 System Context 對象
        mContext = systemContext;

        mFactoryTest = FactoryTest.getMode();
        // 設(shè)置 ActivityThread 對象于样,就是在 SystemServer 中創(chuàng)建的 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);
        
        // 創(chuàng)建一個 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());
        }

        // 創(chuàng)建 BroadcastQueue 前臺廣播對象,處理超時時長是 10s
        mFgBroadcastQueue = new BroadcastQueue(this, mHandler,
                "foreground", BROADCAST_FG_TIMEOUT, false);
        // 創(chuàng)建 BroadcastQueue 后臺廣播對象潘靖,處理超時時長是 60s
        mBgBroadcastQueue = new BroadcastQueue(this, mHandler,
                "background", BROADCAST_BG_TIMEOUT, true);
        mBroadcastQueues[0] = mFgBroadcastQueue;
        mBroadcastQueues[1] = mBgBroadcastQueue;
    
        // 創(chuàng)建 ActiveServices 對象穿剖,用于管理 ServiceRecord 對象
        mServices = new ActiveServices(this);
        // 創(chuàng)建 ProviderMap 對象,用于管理 ContentProviderRecord 對象
        mProviderMap = new ProviderMap(this);
        // 創(chuàng)建 AppErrors 對象卦溢,用于處理應用程序的異常
        mAppErrors = new AppErrors(mUiContext, this);

        // 初始化 /data/system 目錄
        File dataDir = Environment.getDataDirectory();
        File systemDir = new File(dataDir, "system");
        systemDir.mkdirs();
        // 初始化電池狀態(tài)信息糊余,進程狀態(tài) 和 應用權(quán)限管理
        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 權(quán)限檢查服務(wù)秀又,注冊對應的回調(diào)接口
        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;

        //創(chuàng)建 ActivityStackSupervisor 對象,是 AMS 中 ActivityRecord 和 TaskRecord 管理和調(diào)度的重要類
        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);
        // 創(chuàng)建 ActivityStarter 對象啄刹,用于啟動 Activity
        mActivityStarter = new ActivityStarter(this, mStackSupervisor);
        // 最近使用的 RecentTasks
        mRecentTasks = new RecentTasks(this, mStackSupervisor);
        
        // 創(chuàng)建一個用于更新 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 的構(gòu)造方法中主要做了以下事情:

  1. 初始化一些對象屬性涮坐,包括 Context、ActivityThread誓军、ServiceThread袱讹、MainHandler、ActivityManagerConstants 等對象
  2. 創(chuàng)建和管理四大組件相關(guān)的類對象昵时,包括 BroadcastQueue捷雕、ActiveServices、ProviderMap壹甥、ActivityStackSupervisor救巷、RecentTasks 和 ActivityStarter 等對象
  3. 創(chuàng)建一個 CPU 監(jiān)控線程 mProcessCpuThread

3.2 一些初始化方法

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

  1. 啟動 CPU 監(jiān)控線程句柠,在啟動 CPU 監(jiān)控線程之前浦译,首先將進程復位
  2. 注冊電池狀態(tài)服務(wù)和權(quán)限管理服務(wù)
    private void start() {
        // 在啟動 CPU 監(jiān)控線程之前,首先將進程復位
        removeAllProcessGroups();
        mProcessCpuThread.start();
      
        // 注冊電池狀態(tài)和權(quán)限管理服務(wù)
        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() 方法之外溯职,還調(diào)用了 initPowerManagement()精盅、setSystemProcess()setWindowManager(WindowManagerService wm) 方法

    // 初始化一些 PowerManager 相關(guān)類
    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);
    }

    // 初始化一些系統(tǒng)信息,包括 meminfo谜酒、gfxinfo叹俏、dbinfo、cpuinfo 等信息
    // 并創(chuàng)建一個系統(tǒng)進行信息類 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 對象設(shè)置 WMS 對象
    public void setWindowManager(WindowManagerService wm) {
        mWindowManager = wm;
        mStackSupervisor.setWindowManager(wm);
        mActivityStarter.setWindowManager(wm);
    }

在所有初始化完成之后粘驰,會調(diào)用 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;
            }

            // 調(diào)用 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;
        }

        ......
        // 啟動系統(tǒng) Home 應用程序述么,也就是 Launcher 應用
        startHomeActivityLocked(currentUserId, "systemReady");
        ......
    }

systemReady(final Runnable goingCallback, BootTimingsTraceLog traceLog) 方法調(diào)完之后蝌数,AMS 系統(tǒng)服務(wù)大概的啟動流程就分析完成了,啟動時序圖如下所示

AMS1.png

圖片來源 ActivityManagerService啟動解析

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末度秘,一起剝皮案震驚了整個濱河市顶伞,隨后出現(xiàn)的幾起案子,更是在濱河造成了極大的恐慌敷钾,老刑警劉巖枝哄,帶你破解...
    沈念sama閱讀 206,126評論 6 481
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件,死亡現(xiàn)場離奇詭異阻荒,居然都是意外死亡挠锥,警方通過查閱死者的電腦和手機,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 88,254評論 2 382
  • 文/潘曉璐 我一進店門侨赡,熙熙樓的掌柜王于貴愁眉苦臉地迎上來蓖租,“玉大人粱侣,你說我怎么就攤上這事”突拢” “怎么了齐婴?”我有些...
    開封第一講書人閱讀 152,445評論 0 341
  • 文/不壞的土叔 我叫張陵,是天一觀的道長稠茂。 經(jīng)常有香客問我柠偶,道長,這世上最難降的妖魔是什么睬关? 我笑而不...
    開封第一講書人閱讀 55,185評論 1 278
  • 正文 為了忘掉前任诱担,我火速辦了婚禮,結(jié)果婚禮上电爹,老公的妹妹穿的比我還像新娘蔫仙。我一直安慰自己,他們只是感情好丐箩,可當我...
    茶點故事閱讀 64,178評論 5 371
  • 文/花漫 我一把揭開白布摇邦。 她就那樣靜靜地躺著,像睡著了一般屎勘。 火紅的嫁衣襯著肌膚如雪施籍。 梳的紋絲不亂的頭發(fā)上,一...
    開封第一講書人閱讀 48,970評論 1 284
  • 那天挑秉,我揣著相機與錄音法梯,去河邊找鬼苔货。 笑死犀概,一個胖子當著我的面吹牛,可吹牛的內(nèi)容都是我干的夜惭。 我是一名探鬼主播姻灶,決...
    沈念sama閱讀 38,276評論 3 399
  • 文/蒼蘭香墨 我猛地睜開眼,長吁一口氣:“原來是場噩夢啊……” “哼诈茧!你這毒婦竟也來了产喉?” 一聲冷哼從身側(cè)響起,我...
    開封第一講書人閱讀 36,927評論 0 259
  • 序言:老撾萬榮一對情侶失蹤敢会,失蹤者是張志新(化名)和其女友劉穎曾沈,沒想到半個月后,有當?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體鸥昏,經(jīng)...
    沈念sama閱讀 43,400評論 1 300
  • 正文 獨居荒郊野嶺守林人離奇死亡塞俱,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點故事閱讀 35,883評論 2 323
  • 正文 我和宋清朗相戀三年,在試婚紗的時候發(fā)現(xiàn)自己被綠了吏垮。 大學時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片障涯。...
    茶點故事閱讀 37,997評論 1 333
  • 序言:一個原本活蹦亂跳的男人離奇死亡罐旗,死狀恐怖,靈堂內(nèi)的尸體忽然破棺而出唯蝶,到底是詐尸還是另有隱情九秀,我是刑警寧澤,帶...
    沈念sama閱讀 33,646評論 4 322
  • 正文 年R本政府宣布粘我,位于F島的核電站鼓蜒,受9級特大地震影響,放射性物質(zhì)發(fā)生泄漏征字。R本人自食惡果不足惜友酱,卻給世界環(huán)境...
    茶點故事閱讀 39,213評論 3 307
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望柔纵。 院中可真熱鬧缔杉,春花似錦、人聲如沸搁料。這莊子的主人今日做“春日...
    開封第一講書人閱讀 30,204評論 0 19
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽郭计。三九已至霸琴,卻和暖如春,著一層夾襖步出監(jiān)牢的瞬間昭伸,已是汗流浹背梧乘。 一陣腳步聲響...
    開封第一講書人閱讀 31,423評論 1 260
  • 我被黑心中介騙來泰國打工, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留庐杨,地道東北人选调。 一個月前我還...
    沈念sama閱讀 45,423評論 2 352
  • 正文 我出身青樓,卻偏偏與公主長得像灵份,于是被迫代替她去往敵國和親仁堪。 傳聞我的和親對象是個殘疾皇子,可洞房花燭夜當晚...
    茶點故事閱讀 42,722評論 2 345

推薦閱讀更多精彩內(nèi)容