ActivityManagerService啟動(dòng)分析

AMS系列:
1、Activity生命周期、啟動(dòng)模式和隱式啟動(dòng)總結(jié)
2、本文ActivityManagerService啟動(dòng)分析
3、ActivityMnagerService分析之啟動(dòng)一個(gè)Acitvity流程分析

本文分析代碼基于Android N,ActivityManagerService簡(jiǎn)稱AMS,其它類似;
“...”代表省略部分代碼

整體思路

1、android啟動(dòng)linux內(nèi)核,加載虛擬機(jī),走到framework啟動(dòng)Systemserver;
2、Systemserver啟動(dòng)Activity Manager,Package Manager,Window Manager等等一系列系統(tǒng)服務(wù);
3、分析AMS的啟動(dòng);
4、本文主要分析AMS初始化干了些什么,其他細(xì)節(jié)后續(xù)再分析;

簡(jiǎn)述Android啟動(dòng)

簡(jiǎn)單說(shuō)一下Android的啟動(dòng)過(guò)程:
Android基于Linux,前面和Linux大致相同
按下電源 -> BIOS自檢 -> 引導(dǎo)程序 -> 啟動(dòng)kernel -> 啟動(dòng)Init進(jìn)程(system\core\init\init.c) -> 開(kāi)啟虛擬機(jī)(Zygotes)
然后
Zygote會(huì)startSystemServer,而Systemserver就開(kāi)始啟動(dòng)framework層的各種公共服務(wù),AMS、WMS、PMS等...

Systemserver啟動(dòng)AMS

從Systemserver.run開(kāi)始,這里開(kāi)始啟動(dòng)各種服務(wù)

private void run() {
    ....
    // 初始化system Context
    createSystemContext();

    // 創(chuàng)建system manager
    mSystemServiceManager = new SystemServiceManager(mSystemContext);
    LocalServices.addService(SystemServiceManager.class, mSystemServiceManager);
    ...
    // Start services.
    try {
        Trace.traceBegin(Trace.TRACE_TAG_SYSTEM_SERVER, "StartServices");
        // 開(kāi)始引導(dǎo)Services,Installer創(chuàng)建user/data等目錄,
        // 以及MessageMonitorService,AMS,PowerManagerService,LightsService,DisplayManagerService,UserManagerService等
        startBootstrapServices();
        // 核心Services,BatteryService,UsageStatsService,WebViewUpdateService
        startCoreServices();
        // 其他Services,這里啟動(dòng)的服務(wù)最多,TelecomLoaderService,CameraService,AccountManagerService等等一系列Service
        startOtherServices();
    } 
    ...
    // Loop forever.
    Looper.loop();
    ...
}

其他服務(wù)的啟動(dòng)這里就不展開(kāi)了,這里開(kāi)始看AMS的啟動(dòng)

private void startBootstrapServices() {
    ...
    // 創(chuàng)建AMS
    mActivityManagerService = mSystemServiceManager.startService(
                ActivityManagerService.Lifecycle.class).getService();
    // 設(shè)置對(duì)象關(guān)聯(lián)
    mActivityManagerService.setSystemServiceManager(mSystemServiceManager);
        mActivityManagerService.setInstaller(installer);
    ...
        // 初始化power manager
    mActivityManagerService.initPowerManagement();
    ...
    // 為系統(tǒng)進(jìn)程設(shè)置應(yīng)用程序?qū)嵗?        mActivityManagerService.setSystemProcess();
}
private void startOtherServices() {
    ...
    // 和SettingsProvider關(guān)聯(lián)
    mActivityManagerService.installSystemProviders();
    ...
    // 設(shè)置對(duì)象關(guān)聯(lián)
    mActivityManagerService.setWindowManager(wm);
    ...
    // 當(dāng)AMS準(zhǔn)備好后,再啟動(dòng)。類似location的服務(wù)很多,在ready之前已經(jīng)創(chuàng)建服務(wù)并添加到ServiceManager中
    mActivityManagerService.systemReady(new Runnable() {
        ...
        startSystemUi(context);
        ...
        Watchdog.getInstance().start();
        ...
        if (locationF != null) locationF.systemRunning();
        ...
        ...
    }
}

1.創(chuàng)建ActivityManagerService

mActivityManagerService = mSystemServiceManager.startService(
ActivityManagerService.Lifecycle.class).getService();
實(shí)際就是返回一個(gè)new ActivityManagerService(context);

    public ActivityManagerService(Context systemContext) {
    // Context 和 ActvityThread
        mContext = systemContext;
        mFactoryTest = FactoryTest.getMode();
        mSystemThread = ActivityThread.currentActivityThread();

    // AMS運(yùn)行的線程和Handler,還有顯示相關(guān)的UiHandler
        mHandlerThread = new ServiceThread(TAG,
                android.os.Process.THREAD_PRIORITY_FOREGROUND, false /*allowIo*/);
        mHandlerThread.start();
        mHandler = new MainHandler(mHandlerThread.getLooper());
        mUiHandler = new UiHandler();

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

    // Broadcast管理的相關(guān)初始化
        mFgBroadcastQueue = new BroadcastQueue(this, mHandler,
                "foreground", BROADCAST_FG_TIMEOUT, false);
        mBgBroadcastQueue = new BroadcastQueue(this, mHandler,
                "background", BROADCAST_BG_TIMEOUT, true);
        mBroadcastQueues[0] = mFgBroadcastQueue;
        mBroadcastQueues[1] = mBgBroadcastQueue;

    // Server管理的相關(guān)初始化
        mServices = new ActiveServices(this);
    // Provider管理的相關(guān)初始化
        mProviderMap = new ProviderMap(this);
    // App錯(cuò)誤控制
        mAppErrors = new AppErrors(mContext, this);

        // 創(chuàng)建system文件路徑
        File dataDir = Environment.getDataDirectory();
        File systemDir = new File(dataDir, "system");
        systemDir.mkdirs();
    // 初始化BatteryStatsService
        mBatteryStatsService = new BatteryStatsService(systemDir, mHandler);
        mBatteryStatsService.getActiveStatistics().readLocked();
        mBatteryStatsService.scheduleWriteToDisk();
        mOnBattery = DEBUG_POWER ? true
                : mBatteryStatsService.getActiveStatistics().getIsOnBattery();
        mBatteryStatsService.getActiveStatistics().setCallback(this);

    // ProcessStatsService進(jìn)程來(lái)統(tǒng)計(jì)不用的app以及不好行為的app的信息
        mProcessStats = new ProcessStatsService(this, new File(systemDir, "procstats"));

    // 權(quán)限管理,安全機(jī)制
        mAppOpsService = new AppOpsService(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);

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

        mTrackingAssociations = "1".equals(SystemProperties.get("debug.track-associations"));

        mConfiguration.setToDefaults();
        mConfiguration.setLocales(LocaleList.getDefault());

        mConfigurationSeq = mConfiguration.seq = 1;
        mProcessCpuTracker.init();

    // 當(dāng)APK所運(yùn)行的設(shè)備不滿足要求時(shí),AMS會(huì)根據(jù)設(shè)置的參數(shù)以采用屏幕兼容的方式去運(yùn)行它
        mCompatModePackages = new CompatModePackages(this, systemDir, mHandler);
    // 一些校驗(yàn)
        mIntentFirewall = new IntentFirewall(new IntentFirewallInterface(), mHandler);
    // Activity管理的相關(guān)初始化
        mStackSupervisor = new ActivityStackSupervisor(this);
        mActivityStarter = new ActivityStarter(this, mStackSupervisor);
    // 最近任務(wù)
        mRecentTasks = new RecentTasks(this, mStackSupervisor);

    // 每半小時(shí)跟新CPU信息
        mProcessCpuThread = new Thread("CpuTracker") {
            @Override
            public void run() {
                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);
                    }
                }
            }
        };

    // 看門狗
        Watchdog.getInstance().addMonitor(this);
        Watchdog.getInstance().addThread(mHandler);

        /// M: AMEventHook event @{
        AMEventHookData.EndOfAMSCtor eventData =
            AMEventHookData.EndOfAMSCtor.createInstance();
        mAMEventHook.hook(AMEventHook.Event.AM_EndOfAMSCtor,
            eventData);
        /// M: AMEventHook event @}
    }

setSystemProcess

mActivityManagerService.setSystemProcess();
初始化一些服務(wù),為系統(tǒng)進(jìn)程設(shè)置應(yīng)用程序?qū)嵗?AMS得到systemserver的ProcessRecord,以便AMS管理systemserver.

    public void setSystemProcess() {
        try {
        // 添加各種服務(wù)
            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));

            /// M: ANRManager mechanism @{
            ServiceManager.addService("anrmanager", mANRManager, true);
            /// @}
    
        // 這里是獲得報(bào)名為“android”的apk信息,即獲得framework-res.apk
            ApplicationInfo info = mContext.getPackageManager().getApplicationInfo(
                    "android", STOCK_PM_FLAGS | MATCH_SYSTEM_ONLY);
        // 系統(tǒng)進(jìn)程加載framework-res.apk
            mSystemThread.installSystemApplicationInfo(info, getClass().getClassLoader());
        
        // AMS得到systemserver的ProcessRecord,以便AMS管理systemserver
            synchronized (this) {
        // 從info里得到systemserver所在的系統(tǒng)進(jìn)程的名字,然后封裝成一個(gè)ProcessRecord,即封裝系統(tǒng)進(jìn)程的信息
                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);
        }
    }

這里說(shuō)下,ProcessRecord描述一個(gè)app所在進(jìn)程的所有信息。因?yàn)锳MS是運(yùn)行在systemserver進(jìn)程中的,所以這里得到的實(shí)際就是systemserver

installSystemProviders

關(guān)聯(lián)管理SettingsProvider
mActivityManagerService.installSystemProviders();

    public final void installSystemProviders() {
        List<ProviderInfo> providers;
        synchronized (this) {
        // 得到名字為“system”,pid為Process.SYSTEM_UID的進(jìn)程,即systemserver所在系統(tǒng)進(jìn)程
            ProcessRecord app = mProcessNames.get("system", Process.SYSTEM_UID);
        // 得到運(yùn)行在系統(tǒng)進(jìn)程中的所有ContentProvider的ProviderInfo信息
            providers = generateApplicationProvidersLocked(app);
            if (providers != null) {
                for (int i=providers.size()-1; i>=0; i--) {
                    ProviderInfo pi = (ProviderInfo)providers.get(i);
                    if ((pi.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) == 0) {
                        Slog.w(TAG, "Not installing system proc provider " + pi.name
                                + ": not system .apk");
            // 過(guò)濾掉非系統(tǒng)進(jìn)程運(yùn)行的provider
                        providers.remove(i);
                    }
                }
            }
        }
    // 上面已經(jīng)過(guò)濾掉,剩下一個(gè)ContentProvider其實(shí)就是SettingsProvider
        if (providers != null) {
        // 安裝SettingsProvider
            mSystemThread.installSystemProviders(providers);
        }

    // 創(chuàng)建CoreSettingsObserver監(jiān)聽(tīng)SettingsProvider變化
        mCoreSettingsObserver = new CoreSettingsObserver(this);
        mFontScaleSettingObserver = new FontScaleSettingObserver();

        //mUsageStatsService.monitorPackages();
    }

systemReady

mActivityManagerService.systemReady(new Runnable(){}

先看public void systemReady(final Runnable goingCallback) {}

1、校驗(yàn)進(jìn)行systemReady

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

            mLocalDeviceIdleController
                    = LocalServices.getService(DeviceIdleController.LocalService.class);

            // Make sure we have the current profile info, since it is needed for security checks.
            mUserController.onSystemReady();
            mRecentTasks.onSystemReadyLocked();
            mAppOpsService.systemReady();
            mSystemReady = true;
        }

2.殺死之前系統(tǒng)進(jìn)程啟動(dòng)的進(jìn)程,除過(guò)persistent常駐進(jìn)程

  synchronized(mPidsSelfLocked) {
            for (int i=mPidsSelfLocked.size()-1; i>=0; i--) {
                ProcessRecord proc = mPidsSelfLocked.valueAt(i);
                if (!isAllowedWhileBooting(proc.info)){
                    if (procsToKill == null) {
                        procsToKill = new ArrayList<ProcessRecord>();
                    }
                    procsToKill.add(proc);
                }
            }
        }

        synchronized(this) {
            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);
                    removeProcessLocked(proc, true, false, "system update done");
                }
            }

            // Now that we have cleaned up any update processes, we
            // are ready to start launching real processes and know that
            // we won't trample on them any more.
            mProcessesReady = true;
        }

3.啟動(dòng)傳入的Runable

if (goingCallback != null) goingCallback.run();

4.啟動(dòng)launcher,即HomeActivity

startHomeActivityLocked(currentUserId, "systemReady");

5.發(fā)送啟動(dòng)廣播

try {
        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, AppOpsManager.OP_NONE,
                null, false, false, MY_PID, Process.SYSTEM_UID,
                currentUserId);
        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}, AppOpsManager.OP_NONE,
                null, true, false, MY_PID, Process.SYSTEM_UID, UserHandle.USER_ALL);
    } 

再看一下Runnable中做了什么

1、啟動(dòng)carash監(jiān)聽(tīng)

try {
    mActivityManagerService.startObservingNativeCrashes();
} 

2、WebView設(shè)置

if (!mOnlyCore) {
    Slog.i(TAG, "WebViewFactory preparation");
    Trace.traceBegin(Trace.TRACE_TAG_SYSTEM_SERVER, "WebViewFactoryPreparation");
    mWebViewUpdateService.prepareWebViewInSystemServer();
    Trace.traceEnd(Trace.TRACE_TAG_SYSTEM_SERVER);
}

3、啟動(dòng)systemUI

try {
    startSystemUi(context);
} 

4、在systemReady后,各種類開(kāi)始設(shè)置自己的參數(shù)

if (networkScoreF != null) networkScoreF.systemReady();
if (networkManagementF != null) networkManagementF.systemReady();
if (networkStatsF != null) networkStatsF.systemReady();
if (locationF != null) locationF.systemRunning();
...//等等,很多類似方法

總結(jié)

AMS啟動(dòng)簡(jiǎn)要概括:
1、new AMS 準(zhǔn)備Handler、初始化四大組件相關(guān)、權(quán)限、多用戶、看門狗
2、setSystemProcess 加載framework-res.apk,和systemserver進(jìn)程建立關(guān)系
3、installSystemProviders 配置ContentProvider即SettingsProvider
4、systemReady 最后工作,啟動(dòng)launcher,systemUI,發(fā)送啟動(dòng)廣播,其他各類組件準(zhǔn)備好

Read the fucking sources code!

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容