概述
該篇基於AndroidQ,主要介紹系統啟動中的 AMS(ActivityManagerService)的啟動過程。
AMS對四大組件(AndroidQ將activity移到了ActivityTaskManagerService中,但也和AMS相關聯)進行管理和調度。同時,AMS也對進程、電池、內存、權限等進行管理。
AMS的啟動過程 和 結束 部分,主要跟蹤的代碼過程,加以簡單說明。代碼中添加了注釋,可做參考,有點長。如果只想簡單了解下,可以直接看下最后的 簡單總結 部分。
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/
下面具體看下幾個重要文件
frameworks/base/core/java/android/app/下:
- Activity.java:所有Activity的父類。
- ActivityManager.java:AMS的客戶端,提供給用戶可調用的api。
- ActivityThread.java:應用進程的主線程類,一般即UI線程。
frameworks/base/services/core/java/com/android/server/am/下:
- 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之間的關系。
AMS的啟動過程
系統啟動、AMS起點之前
系統啟動后Zygote進程第一個fork出SystemServer進程,進入到SystemServer:main()->run()->startBootstrapServices() 啟動引導服務,進而完成AMS的啟動。
下面是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()。
直接從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的啟動。
-
系統啟動后Zygote進程第一個fork出SystemServer進程
-
SystemServer->run()->createSystemContext():創建了系統的ActivityThread對象,運行環境mSystemContext、systemUiContext。
-
SystemServer->run()->startBootstrapServices()->ActivityManagerService.Lifecycle.startService():AMS在引導服務啟動方法中,通過構造函數
new ActivityManagerService()
進行了一些對象創建和初始化(除activity外3大組件的管理和調度對象創建;內存、電池、權限、性能、cpu等的監控等相關對象創建),start()啟動服務(移除進程組、啟動cpu線程、注冊權限、電池等服務)。 -
SystemServer->run()->startBootstrapServices()->setSystemServiceManager()、setInstaller()、initPowerManagement()、setSystemProcess():AMS創建后進行了一系列相關的初始化和設置。
setSystemProcess():將framework-res.apk的信息加入到SystemServer進程的LoadedApk中,並創建了SystemServer進程的ProcessRecord,加入到mPidsSelfLocked,由AMS統一管理。 -
SystemServer->run()->startOtherServices():AMS啟動后的后續工作,主要調用systemReady()和運行調用時傳入的goingCallback。
systemReady()/goingCallback:各種服務或進程等AMS啟動完成后需進一步完成的工作及系統相關初始化。 桌面應用在systemReady()方法中啟動,systemui在goingCallback中完成。當桌面應用啟動完成后,發送開機廣播ACTION_BOOT_COMPLETED,到此為止。
最后附上一個圖片,網上不少地方可以看見,幾個類的關系很清晰。