Android10_原理機制系列_AMS之AMS的啓動

概述

該篇基於AndroidQ,主要介紹系統啓動中的 AMS(ActivityManagerService)的啓動過程。
AMS對四大組件(AndroidQ將activity移到了ActivityTaskManagerService中,但也和AMS相關聯)進行管理和調度。同時,AMS也對進程、電池、內存、權限等進行管理。html

AMS的啓動過程結束 部分,主要跟蹤的代碼過程,加以簡單說明。代碼中添加了註釋,可作參考,有點長。若是隻想簡單瞭解下,能夠直接看下最後的 簡單總結 部分。java

AMS相關目錄結構

AMS代碼主要在下面幾個目錄(AndroidQ上AMS相關部分功能移到了wm下):
frameworks/base/core/java/android/app/
frameworks/base/services/core/java/com/android/server/am/
frameworks/base/services/core/java/com/android/server/wm/react

下面具體看下幾個重要文件
frameworks/base/core/java/android/app/下:android

  • Activity.java:全部Activity的父類。
  • ActivityManager.java:AMS的客戶端,提供給用戶可調用的api。
  • ActivityThread.java:應用進程的主線程類,通常即UI線程。

frameworks/base/services/core/java/com/android/server/am/下:web

  • ActiveServices.java:控制service的啓動、重啓等。
  • ProcessRecord.java:記錄每一個進程的信息。

frameworks/base/services/core/java/com/android/server/wm/下:數據庫

  • ActivityRecord.java:activity對象信息的記錄。
  • ActivityStack.java/ActivityStackSupervisor.java:管理activity生命週期及堆棧等。
  • TaskRecord.java:任務棧記錄,管理一個任務的應用activity
  • ActivityTaskManagerService.java/ActivityTaskManagerInternal.java:管理activity的啓動和調度。

文末附上了一個圖片,是ActivityStack、ActivityStackSupervisor、TaskRecord、ActivityRecord、ProcessRecord之間的關係。

api

AMS的啓動過程

系統啓動、AMS起點以前

系統啓動後Zygote進程第一個fork出SystemServer進程,進入到SystemServer:main()->run()->startBootstrapServices() 啓動引導服務,進而完成AMS的啓動。app

下面是fork出SystemServer的過程,有很多地方須要進一步學習,瞭解下不作說明。
ZygoteInit.java:main()->forkSystemServer()->Zygote.java:forkSystemServer()->nativeForkSystemServer()->com_android_internal_os_Zygote.cpp:com_android_internal_os_Zygote_nativeForkSystemServer()->ZygoteInit.java->handleSystemServerProcess()。ide

直接從SystemServer的run()看:函數

//frameworks/base/services/java/com/android/server/SystemServer.java
private void run() {
    try {
        createSystemContext();
    }
    try {
        traceBeginAndSlog("StartServices");
        startBootstrapServices();
        startCoreServices();
        startOtherServices();
        SystemServerInitThreadPool.shutdown();
    }
}

private void createSystemContext() {
    ActivityThread activityThread = ActivityThread.systemMain();
    //初始化系統context,並設置主題
    mSystemContext = activityThread.getSystemContext();
    mSystemContext.setTheme(DEFAULT_SYSTEM_THEME);
    //初始化SystemUi context,並設置主題
    final Context systemUiContext = activityThread.getSystemUiContext();
    systemUiContext.setTheme(DEFAULT_SYSTEM_THEME);
}

createSystemContext()建立了兩個上下文,系統context和SystemUi context。這兩個挺重要,會傳入AMS中,這裏就是它們建立的地方。
接下來看下上面建立兩個上下文時的systemMain(),這個也很重要。

//ActivityThread.java
@UnsupportedAppUsage
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, 0);
    return thread;
}

@UnsupportedAppUsage
ActivityThread() {
    mResourcesManager = ResourcesManager.getInstance();
}

@UnsupportedAppUsage
private void attach(boolean system, long startSeq) {
    sCurrentActivityThread = this;
    mSystemThread = system;
    if (!system) {
        .......    
    } else {
        ......
        try {
            mInstrumentation = new Instrumentation();
            mInstrumentation.basicInit(this);
            ContextImpl context = ContextImpl.createAppContext(
                    this, getSystemContext().mPackageInfo);
            mInitialApplication = context.mPackageInfo.makeApplication(true, null);
            mInitialApplication.onCreate();
        }
        ......
    }
    .......
}

ActivityThread是當前進程的主線程。SystemServer初始化時ActivityThread.systemMain()建立的是系統進程(SystemServer進程)的主線程。
構造函數是獲取ResourcesManager的單例對象。
attach()這裏走的是系統進程(應用啓動也會走,那時system爲false,走的時應用進程),這裏建立了幾個重要的對象Instrumentation、Context、Application。
Instrumentation:很重要的一個基類,會優先實例化,容許檢測系統與應用全部交互。應用中AndroidManifest.xml的 標籤能夠定義其實現。
Context:上下文,應用運行環境的全局信息。這裏建立的是一個LoadedApk(packagename是android,即framework-res.apk),以此獲取了Context對象。(具體可追蹤ContextImpl.createAppContext())。
Application:保存應用的全局狀態。

AMS查看起點

這裏從startBootstrapServices()做爲AMS啓動的起點開始查看

//frameworks/base/services/java/com/android/server/SystemServer.java
private void startBootstrapServices() {
    ......
    // TODO: Might need to move after migration to WM.
    //part 0
    ActivityTaskManagerService atm = mSystemServiceManager.startService(
            ActivityTaskManagerService.Lifecycle.class).getService();
    //part 1
    mActivityManagerService = ActivityManagerService.Lifecycle.startService(
            mSystemServiceManager, atm);
    //part 2
    mActivityManagerService.setSystemServiceManager(mSystemServiceManager);
    //part 3
    mActivityManagerService.setInstaller(installer);
    // Now that the power manager has been started, let the activity manager
    // initialize power management features.
    //part 4
    mActivityManagerService.initPowerManagement();
    // Set up the Application instance for the system process and get started.
    //part 5
    mActivityManagerService.setSystemProcess();
    // Complete the watchdog setup with an ActivityManager instance and listen for reboots
    // Do this only after the ActivityManagerService is properly started as a system process
    //part 6
    watchdog.init(mSystemContext, mActivityManagerService);
}

注意上面的幾個部分(part0-part6),是其中mActivityManagerService相關的,依次來具體看看,瞭解AMS的啓動過程。

part 0:mSystemServiceManager.startService(ActivityTaskManagerService.Lifecycle.class).getService()

這句和ActivityManagerService.Lifecycle.startService()裏執行過程(part 1中)是同樣的,這裏不詳細說明,當看part 1部分就能知道。
這句建立了ActivityTaskManagerService對象,並調用了ActivityTaskManagerService中的start()方法啓動服務。

ActivityTaskManagerService是Android 10新引入的變化,也是系統服務,用來管理Activity啓動和調度,包括其容器(task、stacks、displays等)。這篇主要關於AMS的啓動,所以ActivityTaskManagerService這裏不贅述。
Android 10將原先AMS中對activity的管理和調度移到了ActivityTaskManagerService中,位置放到了wm下(見上面完整路徑),所以AMS負責四大組件中另外3個(service, broadcast, contentprovider)的管理和調度。

ActivityTaskManagerService.java上的註釋說明:
System service for managing activities and their containers (task, stacks, displays,... ).

part 1:ActivityManagerService.Lifecycle.startService()

//ActivityManagerService.java
public static final class Lifecycle extends SystemService {
    private final ActivityManagerService mService;
    private static ActivityTaskManagerService sAtm;

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

    public static ActivityManagerService startService(
            SystemServiceManager ssm, ActivityTaskManagerService atm) {
        sAtm = atm;
        return ssm.startService(ActivityManagerService.Lifecycle.class).getService();
    }
    
    @Override
    public void onStart() {
        mService.start();
    }
    
    public ActivityManagerService getService() {
        return mService;
    }

這裏的Lifecycle是AMS的內部類。ActivityManagerService.Lifecycle.startService()最終返回的是mService,即建立的AMS對象。

接着來具體看下這個過程的實現,ActivityManagerService.Lifecycle.startService()進入SystemServiceManager類的startService(),繼續看

//frameworks/base/services/core/java/com/android/server/SystemServiceManager.java
public <T extends SystemService> T startService(Class<T> serviceClass) {
    try {
        final String name = serviceClass.getName();
         // 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);
        } ......
        startService(service);
        return service;
    } 
}

public void startService(@NonNull final SystemService service) {
    // Register it.
    mServices.add(service);
    // Start it.
    long time = SystemClock.elapsedRealtime();
    try {
        service.onStart();
    } catch (RuntimeException ex) {
        ......
    }
    warnIfTooLong(SystemClock.elapsedRealtime() - time, service, "onStart");
}

SystemServiceManager中經過反射,調用了ActivityManagerService.Lifecycle的構造方法,而後startService(service) 中最終調用了service.onStart(),即ActivityManagerService.Lifecycle.onStart()。

題外話,這裏有幾個稍微注意下:

  • isAssignableFrom與instanceof:
    Class1.isAssignableFrom(Class2):都是Class類型 表示類或接口,判斷Class1是不是Class2的父類或父接口,或者相同。
    也能夠簡單看做:父類.class.isAssignableFrom(子類.class)。
    oo instanceof TypeName:oo是實例對象,TypeName是具體類名或接口名。判斷oo是不是TypeName的子類或接口實現。
    也能夠簡單看做:子類實例 instanceof 父類類型。
  • warnIfTooLong()中,時間elapsedRealtime()是包含深度睡眠的設備啓動時間,具體在Handler消息機制有提過。另外這裏的warn時間是SERVICE_CALL_WARN_TIME_MS -- 50ms。

接着須要看兩點:經過反射調用ActivityManagerService.Lifecycle的構造方法,主要new ActivityManagerService() 建立AMS對象,幹了些什麼須要瞭解;ActivityManagerService.Lifecycle.onStart()就是直接調用AMS的start()方法;

new ActivityManagerService()

// Note: This method is invoked on the main thread but may need to attach various
// handlers to other threads.  So take care to be explicit about the looper.
public ActivityManagerService(Context systemContext, ActivityTaskManagerService atm) {
    LockGuard.installLock(this, LockGuard.INDEX_ACTIVITY);
    mInjector = new Injector(); 
    //系統上下文,是在SystemServer進程fork出來後經過createSystemContext()建立的,即與SystemServer進程是一一致
    mContext = systemContext;

    mFactoryTest = FactoryTest.getMode();
    //系統進程的主線程 sCurrentActivityThread,這裏是systemMain()中建立的ActivityThread對象。即也與SystemServer同樣的。
    mSystemThread = ActivityThread.currentActivityThread();
    mUiContext = mSystemThread.getSystemUiContext();

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

    mHandlerThread = new ServiceThread(TAG,
            THREAD_PRIORITY_FOREGROUND, false /*allowIo*/);
    mHandlerThread.start();
    //處理AMS消息的handle
    mHandler = new MainHandler(mHandlerThread.getLooper());
    //UiHandler對應於Android中的Ui線程
    mUiHandler = mInjector.getUiHandler(this);

    mProcStartHandlerThread = new ServiceThread(TAG + ":procStart",
            THREAD_PRIORITY_FOREGROUND, false /* allowIo */);
    mProcStartHandlerThread.start();
    mProcStartHandler = new Handler(mProcStartHandlerThread.getLooper());

    mConstants = new ActivityManagerConstants(mContext, this, mHandler);
    final ActiveUids activeUids = new ActiveUids(this, true /* postChangesToAtm */);
    mProcessList.init(this, activeUids);
    mLowMemDetector = new LowMemDetector(this);
    mOomAdjuster = new OomAdjuster(this, mProcessList, activeUids);

    // Broadcast policy parameters
    final BroadcastConstants foreConstants = new BroadcastConstants(
            Settings.Global.BROADCAST_FG_CONSTANTS);
    foreConstants.TIMEOUT = BROADCAST_FG_TIMEOUT;//10s

    final BroadcastConstants backConstants = new BroadcastConstants(
            Settings.Global.BROADCAST_BG_CONSTANTS);
    backConstants.TIMEOUT = BROADCAST_BG_TIMEOUT;//60s
    final BroadcastConstants offloadConstants = new BroadcastConstants(
            Settings.Global.BROADCAST_OFFLOAD_CONSTANTS);
    offloadConstants.TIMEOUT = BROADCAST_BG_TIMEOUT;
    // by default, no "slow" policy in this queue
    offloadConstants.SLOW_TIME = Integer.MAX_VALUE;
    mEnableOffloadQueue = SystemProperties.getBoolean(
            "persist.device_config.activity_manager_native_boot.offload_queue_enabled", false);
    //建立幾種廣播相關對象,前臺廣播、後臺廣播、offload暫不瞭解TODO。
    mFgBroadcastQueue = new BroadcastQueue(this, mHandler,
            "foreground", foreConstants, false);
    mBgBroadcastQueue = new BroadcastQueue(this, mHandler,
            "background", backConstants, true);
    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);
    mPackageWatchdog = PackageWatchdog.getInstance(mUiContext);
    mAppErrors = new AppErrors(mUiContext, this, mPackageWatchdog);

    final File systemDir = SystemServiceManager.ensureSystemDir();

    // TODO: Move creation of battery stats service outside of activity manager service.
    mBatteryStatsService = new BatteryStatsService(systemContext, systemDir,
            BackgroundThread.get().getHandler());
    mBatteryStatsService.getActiveStatistics().readLocked();
    mBatteryStatsService.scheduleWriteToDisk();
    mOnBattery = DEBUG_POWER ? true
            : mBatteryStatsService.getActiveStatistics().getIsOnBattery();
    mBatteryStatsService.getActiveStatistics().setCallback(this);
    mOomAdjProfiler.batteryPowerChanged(mOnBattery);

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

    mAppOpsService = mInjector.getAppOpsService(new File(systemDir, "appops.xml"), mHandler);

    mUgmInternal = LocalServices.getService(UriGrantsManagerInternal.class);

    mUserController = new UserController(this);

    mPendingIntentController = new PendingIntentController(
            mHandlerThread.getLooper(), mUserController);

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

    mTrackingAssociations = "1".equals(SystemProperties.get("debug.track-associations"));
    mIntentFirewall = new IntentFirewall(new IntentFirewallInterface(), mHandler);

    //獲得ActivityTaskManagerService的對象,調用ATM.initialize
    mActivityTaskManager = atm;
    mActivityTaskManager.initialize(mIntentFirewall, mPendingIntentController,
            DisplayThread.get().getLooper());
    mAtmInternal = LocalServices.getService(ActivityTaskManagerInternal.class);

    mProcessCpuThread = new Thread("CpuTracker") {
        ......
    };

    mHiddenApiBlacklist = new HiddenApiSettings(mHandler, mContext);

    //加入Watchdog的監控
    Watchdog.getInstance().addMonitor(this);
    Watchdog.getInstance().addThread(mHandler);

    // bind background threads to little cores
    // this is expected to fail inside of framework tests because apps can't touch cpusets directly
    // make sure we've already adjusted system_server's internal view of itself first
    updateOomAdjLocked(OomAdjuster.OOM_ADJ_REASON_NONE);
    try {
        Process.setThreadGroupAndCpuset(BackgroundThread.get().getThreadId(),
                Process.THREAD_GROUP_SYSTEM);
        Process.setThreadGroupAndCpuset(
                mOomAdjuster.mAppCompact.mCompactionThread.getThreadId(),
                Process.THREAD_GROUP_SYSTEM);
    } catch (Exception e) {
        Slog.w(TAG, "Setting background thread cpuset failed");
    }

}

AMS的構造方法,主要完成一些對象的構造及變量的初始化,能夠看下上面的註釋。

  • 三大組件的(service、broadcast、provider)管理和調度(activity移到了ActivityTaskManagerService中,但此處也綁定了ActivityTaskManagerService對象)。
  • 監控內存、電池、權限(能夠了解下appops.xml)以及性能相關的對象或變量。mLowMemDetector、mBatteryStatsService、mProcessStats、mAppOpsService、mProcessCpuThread等。

AMS的start()

private void start() {
    //移除全部的進程組
    removeAllProcessGroups();
    //啓動CPU監控線程
    mProcessCpuThread.start();

    //註冊電池、權限管理相關服務
    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");
    }
}

start()主要:

  • 移除全部進程組,復位進程後,啓動CPU監控線程。mProcessCpuThread在前面構造函數中建立的線程。
  • 註冊電池、權限管理的相關服務
  • LocalService只能本進程使用,不可跨進程。

part 2:mActivityManagerService.setSystemServiceManager(mSystemServiceManager)

ActivityManagerService.java:
public void setSystemServiceManager(SystemServiceManager mgr) {
    mSystemServiceManager = mgr;
}

很簡單,將SystemServer.java中建立的SystemServiceManager對象mSystemServiceManager 設置到了AMS中。

part 3:mActivityManagerService.setInstaller(installer)

ActivityManagerService.java:
public void setInstaller(Installer installer) {
    mInstaller = installer;
}

一樣,將SystemServer.java中建立的Installer對象installer設置到AMS中。

part 4:mActivityManagerService.initPowerManagement()

ActivityManagerService.java:
public void initPowerManagement() {
    mActivityTaskManager.onInitPowerManagement();
    mBatteryStatsService.initPowerManagement();
    mLocalPowerManager = LocalServices.getService(PowerManagerInternal.class);
}

在前面建立AMS過程,mActivityTaskManager、mBatteryStatsService對象已建立 相關服務已註冊。這裏初始化電源管理的功能。

part 5:mActivityManagerService.setSystemProcess()

public void setSystemProcess() {
   try {
        //註冊服務activity
        ServiceManager.addService(Context.ACTIVITY_SERVICE, this, /* allowIsolated= */ true,
                DUMP_FLAG_PRIORITY_CRITICAL | DUMP_FLAG_PRIORITY_NORMAL | DUMP_FLAG_PROTO);
        //註冊服務procstats,進程狀態
        ServiceManager.addService(ProcessStats.SERVICE_NAME, mProcessStats);
        //註冊服務meminfo,內存信息
        ServiceManager.addService("meminfo", new MemBinder(this), /* allowIsolated= */ false,
                DUMP_FLAG_PRIORITY_HIGH);
        //註冊服務gfxinfo,圖像信息
        ServiceManager.addService("gfxinfo", new GraphicsBinder(this));
        //註冊服務dbinfo,數據庫信息
        ServiceManager.addService("dbinfo", new DbBinder(this));
        if (MONITOR_CPU_USAGE) {
            //註冊服務cpuinfo,cpu信息
            ServiceManager.addService("cpuinfo", new CpuBinder(this),
                    /* allowIsolated= */ false, DUMP_FLAG_PRIORITY_CRITICAL);
        }
        //註冊服務permission和processinfo,權限和進程信息
        ServiceManager.addService("permission", new PermissionController(this));
        ServiceManager.addService("processinfo", new ProcessInfoService(this));
        //獲取「android」應用的ApplicationInfo,並裝載到mSystemThread
        ApplicationInfo info = mContext.getPackageManager().getApplicationInfo(
                "android", STOCK_PM_FLAGS | MATCH_SYSTEM_ONLY);
        mSystemThread.installSystemApplicationInfo(info, getClass().getClassLoader());
        //建立ProcessRecord維護進程的相關信息
        synchronized (this) {
            ProcessRecord app = mProcessList.newProcessRecordLocked(info, info.processName,
                    false,
                    0,
                    new HostingRecord("system"));
            app.setPersistent(true);
            app.pid = MY_PID;//
            app.getWindowProcessController().setPid(MY_PID);
            app.maxAdj = ProcessList.SYSTEM_ADJ;
            app.makeActive(mSystemThread.getApplicationThread(), mProcessStats);
            mPidsSelfLocked.put(app);//
            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);
                        }
                    }
                }
            });
}

這個方法 設置系統進程,AMS的setSystemProcess主要:

  • 註冊一些服務:activity、procstats、meminfo、gfxinfo、dbinfo、cpuinfo、permission、processinfo
    關於服務的註冊涉及binder相關內容,能夠參考Binder機制
  • 起點部分,attach()過程獲取Context對象時經過ContextImpl.createAppContext()建立了一個LoadedApk(packagename是android,即framework-res.apk)。
    這裏獲取包名爲「android」的應用的ApplicationInfo對象,並將該ApplicationInfo信息安裝設置到SystemThread(系統進程主線程)。便可以理解,系統也是一個特殊的應用。
  • 建立ProcessRecord維護進程的相關信息,這裏MY_PID即爲SystemServer進程ID。
  • 啓動 檢測應用運行和交互。

part 6:watchdog.init(mSystemContext, mActivityManagerService)

初始化看門狗,AMS實列做爲參數設置進入。

結束

這個過程,即系統完成啓動,做爲結束大體看下(已算不屬於AMS的啓動了,是在AMS啓動以後)。咱們平時接觸比較多的,launcher、systemui都是在這個過程完成啓動的,最後發送開機廣播ACTION_BOOT_COMPLETED。
下面大體看下。

最開始講過在SystemServer的run()中,有

traceBeginAndSlog("StartServices");
startBootstrapServices();
startCoreServices();
startOtherServices();

上面講到的都是startBootstrapServices(),AMS的啓動在其中。最後,當引導服務、核心服務、其餘服務都完成後,會調用AMS中的systemReady()方法。

SystemServer.java:
private void startOtherServices() {
    mActivityManagerService.installSystemProviders();
    // Now that SettingsProvider is ready, reactivate SQLiteCompatibilityWalFlags
    SQLiteCompatibilityWalFlags.reset();
    ......
    mActivityManagerService.systemReady(() -> {
        ......//goingCallback
    }, BOOT_TIMINGS_TRACE_LOG);
}

systemReady()

ActivityManagerService.java:
public void systemReady(final Runnable goingCallback, TimingsTraceLog traceLog) {
    traceLog.traceBegin("PhaseActivityManagerReady");
    synchronized(this) {
        //第一次進入爲false
        if (mSystemReady) {
            ......
        }
        //關鍵服務等待systemReady,繼續完成一些初始化或進一步的工做
        mLocalDeviceIdleController
                = LocalServices.getService(DeviceIdleController.LocalService.class);
        mActivityTaskManager.onSystemReady();
        // Make sure we have the current profile info, since it is needed for security checks.
        mUserController.onSystemReady();
        mAppOpsService.systemReady();
        mSystemReady = true;
    }
    ......
    //mPidsSelfLocked中保留了當前正在運行的全部進程信息
    ArrayList<ProcessRecord> procsToKill = null;
    synchronized(mPidsSelfLocked) {
        for (int i=mPidsSelfLocked.size()-1; i>=0; i--) {
            ProcessRecord proc = mPidsSelfLocked.valueAt(i);
            //已啓動的進程,若進程沒有FLAG_PERSISTENT標誌,則會被加入到procsToKill中
            if (!isAllowedWhileBooting(proc.info)){
                if (procsToKill == null) {
                    procsToKill = new ArrayList<ProcessRecord>();
                }
                procsToKill.add(proc);
            }
        }
    }
    //關閉procsToKill中的全部進程
    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);
                mProcessList.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;
    }

    Slog.i(TAG, "System now ready");
    EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_AMS_READY, SystemClock.uptimeMillis());

    mAtmInternal.updateTopComponentForFactoryTest();
    mAtmInternal.getLaunchObserverRegistry().registerLaunchObserver(mActivityLaunchObserver);

    watchDeviceProvisioning(mContext);

    retrieveSettings();
    mUgmInternal.onSystemReady();

    final PowerManagerInternal pmi = LocalServices.getService(PowerManagerInternal.class);
    if (pmi != null) {
        pmi.registerLowPowerModeObserver(ServiceType.FORCE_BACKGROUND_CHECK,
                state -> updateForceBackgroundCheck(state.batterySaverEnabled));
        updateForceBackgroundCheck(
                pmi.getLowPowerState(ServiceType.FORCE_BACKGROUND_CHECK).batterySaverEnabled);
    } else {
        Slog.wtf(TAG, "PowerManagerInternal not found.");
    }
    //運行goingCallback,SystemServer調用時傳入的
    if (goingCallback != null) goingCallback.run();
    // Check the current user here as a user can be started inside goingCallback.run() from
    // other system services.
    final int currentUserId = mUserController.getCurrentUserId();
    ......
    final boolean bootingSystemUser = currentUserId == UserHandle.USER_SYSTEM;

    if (bootingSystemUser) {
        mSystemServiceManager.startUser(currentUserId);
    }

    synchronized (this) {
        // Only start up encryption-aware persistent apps; once user is
        // unlocked we'll come back around and start unaware apps
        startPersistentApps(PackageManager.MATCH_DIRECT_BOOT_AWARE);//FLX

        // Start up initial activity.
        mBooting = true;
        // Enable home activity for system user, so that the system can always boot. We don't
        // do this when the system user is not setup since the setup wizard should be the one
        // to handle home activity in this case.
        if (UserManager.isSplitSystemUser() &&
                Settings.Secure.getInt(mContext.getContentResolver(),
                     Settings.Secure.USER_SETUP_COMPLETE, 0) != 0) {
            ComponentName cName = new ComponentName(mContext, SystemUserHomeActivity.class);
            try {
                AppGlobals.getPackageManager().setComponentEnabledSetting(cName,
                        PackageManager.COMPONENT_ENABLED_STATE_ENABLED, 0,
                        UserHandle.USER_SYSTEM);
            } catch (RemoteException e) {
                throw e.rethrowAsRuntimeException();
            }
        }

        if (bootingSystemUser) {
            //啓動launcher的Activity.
            mAtmInternal.startHomeOnAllDisplays(currentUserId, "systemReady");
        }

        mAtmInternal.showSystemReadyErrorDialogsIfNeeded();
        
        //發送一些廣播ACTION_USER_STARTED  ACTION_USER_STARTING   
        if (bootingSystemUser) {
            ......
        traceLog.traceEnd(); // ActivityManagerStartApps
        traceLog.traceEnd(); // PhaseActivityManagerReady
    }
}


boolean isAllowedWhileBooting(ApplicationInfo ai) {
    return (ai.flags&ApplicationInfo.FLAG_PERSISTENT) != 0;
}

主要關注幾步:

  • 關鍵服務等繼續完成一些初始化或進一步工做
  • 已啓動的進程,若進程沒有FLAG_PERSISTENT標誌,則會被kill掉
  • 運行goingCallback,即調用時傳入的
  • 啓動launcher的Activity,即桌面應用
  • 發送一些廣播ACTION_USER_STARTED ACTION_USER_STARTING。

注:開機嚮導在這裏能夠在這裏跳過,注意 watchDeviceProvisioning(mContext)Settings.Secure.USER_SETUP_COMPLETE屬性。

goingCallback

//SystemServer.java:
traceBeginAndSlog("StartActivityManagerReadyPhase");
//啓動階段:550
mSystemServiceManager.startBootPhase(
        SystemService.PHASE_ACTIVITY_MANAGER_READY);
traceEnd();
traceBeginAndSlog("StartObservingNativeCrashes");
try {
    //監測Native Crash
    mActivityManagerService.startObservingNativeCrashes();
} catch (Throwable e) {
    reportWtf("observing native crashes", e);
}
traceEnd();

// No dependency on Webview preparation in system server. But this should
// be completed before allowing 3rd party
final String WEBVIEW_PREPARATION = "WebViewFactoryPreparation";
Future<?> webviewPrep = null;
if (!mOnlyCore && mWebViewUpdateService != null) {
    webviewPrep = SystemServerInitThreadPool.get().submit(() -> {
        Slog.i(TAG, WEBVIEW_PREPARATION);
        TimingsTraceLog traceLog = new TimingsTraceLog(
                SYSTEM_SERVER_TIMING_ASYNC_TAG, Trace.TRACE_TAG_SYSTEM_SERVER);
        traceLog.traceBegin(WEBVIEW_PREPARATION);
        ConcurrentUtils.waitForFutureNoInterrupt(mZygotePreload, "Zygote preload");
        mZygotePreload = null;
        //啓動WebView相關
        mWebViewUpdateService.prepareWebViewInSystemServer();
        traceLog.traceEnd();
    }, WEBVIEW_PREPARATION);
}

if (mPackageManager.hasSystemFeature(PackageManager.FEATURE_AUTOMOTIVE)) {
    traceBeginAndSlog("StartCarServiceHelperService");
    mSystemServiceManager.startService(CAR_SERVICE_HELPER_SERVICE_CLASS);
    traceEnd();
}

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

// Wait for all packages to be prepared
mPackageManagerService.waitForAppDataPrepared();

//啓動階段:600
mSystemServiceManager.startBootPhase(
        SystemService.PHASE_THIRD_PARTY_APPS_CAN_START);
traceEnd();

這裏幾個注意的

  • startBootPhase,啓動階段。這裏是550,600。這個表面大體啓動的階段,有助啓動了解,具體看下面解釋。
  • 在550階段,啓動了SystemUi。
SystemService.java:
/*
 * Boot Phases
 */
public static final int PHASE_WAIT_FOR_DEFAULT_DISPLAY = 100; // maybe should be a dependency?

/**
 * After receiving this boot phase, services can obtain lock settings data.
 */
public static final int PHASE_LOCK_SETTINGS_READY = 480;

/**
 * After receiving this boot phase, services can safely call into core system services
 * such as the PowerManager or PackageManager.
 */
public static final int PHASE_SYSTEM_SERVICES_READY = 500;

/**
 * After receiving this boot phase, services can safely call into device specific services.
 */
public static final int PHASE_DEVICE_SPECIFIC_SERVICES_READY = 520;

/**
 * After receiving this boot phase, services can broadcast Intents.
 */
public static final int PHASE_ACTIVITY_MANAGER_READY = 550;

/**
 * After receiving this boot phase, services can start/bind to third party apps.
 * Apps will be able to make Binder calls into services at this point.
 */
public static final int PHASE_THIRD_PARTY_APPS_CAN_START = 600;

/**
 * After receiving this boot phase, services can allow user interaction with the device.
 * This phase occurs when boot has completed and the home application has started.
 * System services may prefer to listen to this phase rather than registering a
 * broadcast receiver for ACTION_BOOT_COMPLETED to reduce overall latency.
 */
public static final int PHASE_BOOT_COMPLETED = 1000;

當桌面啓動完成後,發送開機廣播ACTION_BOOT_COMPLETED。(這裏不贅述,能夠從Launcher的resume階段開始,調用AMS.finishBooting()方法發送)

簡單總結

大體總結下AMS的啓動。

  1. 系統啓動後Zygote進程第一個fork出SystemServer進程

  2. SystemServer->run()->createSystemContext():建立了系統的ActivityThread對象,運行環境mSystemContext、systemUiContext

  3. SystemServer->run()->startBootstrapServices()->ActivityManagerService.Lifecycle.startService():AMS在引導服務啓動方法中,經過構造函數new ActivityManagerService()進行了一些對象建立和初始化(除activity外3大組件的管理和調度對象建立;內存、電池、權限、性能、cpu等的監控等相關對象建立)start()啓動服務(移除進程組、啓動cpu線程、註冊權限、電池等服務)

  4. SystemServer->run()->startBootstrapServices()->setSystemServiceManager()、setInstaller()、initPowerManagement()、setSystemProcess():AMS建立後進行了一系列相關的初始化和設置。
    setSystemProcess():將framework-res.apk的信息加入到SystemServer進程的LoadedApk中,並建立了SystemServer進程的ProcessRecord,加入到mPidsSelfLocked,由AMS統一管理

  5. SystemServer->run()->startOtherServices():AMS啓動後的後續工做,主要調用systemReady()和運行調用時傳入的goingCallback。
    systemReady()/goingCallback:各類服務或進程等AMS啓動完成後需進一步完成的工做及系統相關初始化。 桌面應用在systemReady()方法中啓動,systemui在goingCallback中完成。當桌面應用啓動完成後,發送開機廣播ACTION_BOOT_COMPLETED,到此爲止。

最後附上一個圖片,網上很多地方能夠看見,幾個類的關係很清晰。
ams_start

相關文章
相關標籤/搜索