AMS(ActivityManagerService)主要負(fù)責(zé)四大組件的啟動(dòng)啡氢、切換焊夸、調(diào)度以及應(yīng)用進(jìn)程的管理和調(diào)度工作幕屹。
Android系統(tǒng)啟動(dòng)流程:首先會(huì)從ROM中預(yù)定義的地方加載引導(dǎo)程序BootLoader到RAM中敬飒,并執(zhí)行BootLoader程序啟動(dòng)Linux Kernel痕鳍,然后啟動(dòng)用戶級(jí)別的第一個(gè)進(jìn)程init進(jìn)程硫豆。init進(jìn)程會(huì)解析init.rc腳本做一些初始化工作,包括掛載系統(tǒng)文件笼呆、創(chuàng)建工作目錄以及啟動(dòng)系統(tǒng)服務(wù)進(jìn)程等熊响,其中系統(tǒng)服務(wù)進(jìn)程包括Zygote、ServiceManager诗赌、Media等汗茄。在Zygote中會(huì)進(jìn)一步啟動(dòng)system_server進(jìn)程,然后system_server進(jìn)程中會(huì)啟動(dòng)AMS铭若、WMS洪碳、PMS等服務(wù),這些服務(wù)啟動(dòng)后叼屠,AMS就會(huì)打開Launcher應(yīng)用的home Activity瞳腌,最終就看到了手機(jī)桌面。
AMS是在SystemServer中被添加的
//SystemServer.java
/**
* The main entry point from zygote.
*/
public static void main(String[] args) {
//new SystemServer()中創(chuàng)建了ActivityThread
new SystemServer().run();
}
private void run() {
//創(chuàng)建主線程Looper
Looper.prepareMainLooper();
//創(chuàng)建系統(tǒng)context(new ContextImpl)和加載系統(tǒng)資源
createSystemContext();
//啟動(dòng)引導(dǎo)服務(wù)
startBootstrapServices();
//啟動(dòng)核心服務(wù)
startCoreServices();
//啟動(dòng)其它服務(wù)
startOtherServices();
//loop循環(huán)
Looper.loop();
}
SystemServer類的main中初始化SystemServer對(duì)象镜雨,調(diào)用run方法:
1)createSystemContext:創(chuàng)建系統(tǒng)上下文
2)startBootstrapServices:啟動(dòng)引導(dǎo)服務(wù)
3)startCoreServices:啟動(dòng)核心服務(wù)
4)startOtherServices:啟動(dòng)其它服務(wù)
5)Looper.loop:loop循環(huán)
在startBootstrapServices中啟動(dòng)了AMS
private void startBootstrapServices() {
//啟動(dòng)AMS
mActivityManagerService = ActivityManagerService.Lifecycle.startService(
mSystemServiceManager, atm);
mActivityManagerService.setSystemServiceManager(mSystemServiceManager);
mActivityManagerService.setInstaller(installer);
//③將AMS注冊(cè)到ServiceManager中
mActivityManagerService.setSystemProcess();
}
public static final class Lifecycle extends SystemService {
private final ActivityManagerService mService;
private static ActivityTaskManagerService sAtm;
//ActivityManagerService.Lifecycle這個(gè)類的構(gòu)造方法
public Lifecycle(Context context) {
super(context);
//①創(chuàng)建AMS實(shí)例
mService = new ActivityManagerService(context, sAtm);
}
public static ActivityManagerService startService(
SystemServiceManager ssm, ActivityTaskManagerService atm) {
sAtm = atm;
//通過LifeCycle的getService返回AMS對(duì)象
return ssm.startService(ActivityManagerService.Lifecycle.class).getService();
}
@Override
public void onStart() {
//②啟動(dòng)AMS
mService.start();
}
public ActivityManagerService getService() {
return mService;
}
}
public <T extends SystemService> T startService(Class<T> serviceClass) {
//通過反射創(chuàng)建AMS對(duì)象嫂侍,會(huì)調(diào)到上面ActivityManagerService.Lifecycle構(gòu)造方法
Constructor<T> constructor = serviceClass.getConstructor(Context.class);
service = constructor.newInstance(mContext);
startService(service);
return service;
}
// Services that should receive lifecycle events.
private final ArrayList<SystemService> mServices = new ArrayList<SystemService>();
public void startService(@NonNull final SystemService service) {
// Register it.
mServices.add(service);
//開啟服務(wù)
service.onStart();
}
①創(chuàng)建AMS實(shí)例:new ActivityManagerService
public ActivityManagerService(Context systemContext, ActivityTaskManagerService atm) {
mInjector = new Injector();
//獲取系統(tǒng)上下文環(huán)境
mContext = systemContext;
//獲取當(dāng)前ActivityThread線程
mSystemThread = ActivityThread.currentActivityThread();
//賦值mUiContext
mUiContext = mSystemThread.getSystemUiContext();
//創(chuàng)建Handler線程,用來處理handler消息
mHandlerThread = new ServiceThread(TAG,
THREAD_PRIORITY_FOREGROUND, false /*allowIo*/);
mHandlerThread.start();
mHandler = new MainHandler(mHandlerThread.getLooper());
//處理ui相關(guān)msg的Handler
mUiHandler = mInjector.getUiHandler(this);
//初始化前臺(tái)廣播的隊(duì)列荚坞,設(shè)置10s超時(shí)
mFgBroadcastQueue = new BroadcastQueue(this, mHandler,
"foreground", foreConstants, false);
//初始化后臺(tái)廣播的隊(duì)列挑宠,設(shè)置60s超時(shí)
mBgBroadcastQueue = new BroadcastQueue(this, mHandler,
"background", backConstants, true);
//初始化離線廣播的隊(duì)列,設(shè)置60s超時(shí)
mOffloadBroadcastQueue = new BroadcastQueue(this, mHandler,
"offload", offloadConstants, true);
mBroadcastQueues[0] = mFgBroadcastQueue;
mBroadcastQueues[1] = mBgBroadcastQueue;
mBroadcastQueues[2] = mOffloadBroadcastQueue;
//初始化管理Service的ActiveServices對(duì)象
mServices = new ActiveServices(this);
mProviderMap = new ProviderMap(this);
mPackageWatchdog = PackageWatchdog.getInstance(mUiContext);
mAppErrors = new AppErrors(mUiContext, this, mPackageWatchdog);
//創(chuàng)建電池狀態(tài)服務(wù)
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);
//啟動(dòng)一個(gè)線程跟進(jìn)CPU當(dāng)前狀態(tài)信息
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);
}
}
}
}
//看門狗西剥,監(jiān)聽進(jìn)程
Watchdog.getInstance().addMonitor(this);
Watchdog.getInstance().addThread(mHandler);
}
②啟動(dòng)AMS
private void start() {
//移除所有的進(jìn)程組
removeAllProcessGroups();
//啟動(dòng)Cpu進(jìn)程
mProcessCpuThread.start();
//啟動(dòng)電池狀態(tài)服務(wù)
mBatteryStatsService.publish();
mAppOpsService.publish(mContext);
//創(chuàng)建本地服務(wù)并注冊(cè)痹栖,將創(chuàng)建的本地服務(wù)放入本地服務(wù)集合完成注冊(cè)
LocalServices.addService(ActivityManagerInternal.class, new LocalService());
//等待mProcessCpuThread完成初始化后亿汞,釋放鎖
try {
mProcessCpuInitLatch.await();
} catch (InterruptedException e) {
Slog.wtf(TAG, "Interrupted wait during start", e);
Thread.currentThread().interrupt();
throw new IllegalStateException("Interrupted wait during start");
}
}
1)removeAllProcessGroups:移除所有的進(jìn)程組
2)mProcessCpuThread.start():啟動(dòng)CpuTracker線程
3)mBatteryStatsService.publish():啟動(dòng)電池狀態(tài)服務(wù)
4)LocalServices.addService(ActivityManagerInternal.class, new LocalService()):創(chuàng)建本地服務(wù)并放入本地服務(wù)集合
③將AMS注冊(cè)到ServiceManager中 setSystemProcess
public void setSystemProcess() {
try {
//將AMS注冊(cè)到ServiceManager中
ServiceManager.addService(Context.ACTIVITY_SERVICE, this, /* allowIsolated= */ true,
DUMP_FLAG_PRIORITY_CRITICAL | DUMP_FLAG_PRIORITY_NORMAL | DUMP_FLAG_PROTO);
//注冊(cè)進(jìn)程狀態(tài)服務(wù)
ServiceManager.addService(ProcessStats.SERVICE_NAME, mProcessStats);
//注冊(cè)內(nèi)存Binder
ServiceManager.addService("meminfo", new MemBinder(this), /* allowIsolated= */ false,
DUMP_FLAG_PRIORITY_HIGH);
//注冊(cè)圖像信息Binder
ServiceManager.addService("gfxinfo", new GraphicsBinder(this));
//注冊(cè)數(shù)據(jù)庫Binder
ServiceManager.addService("dbinfo", new DbBinder(this));
if (MONITOR_CPU_USAGE) {
//注冊(cè)監(jiān)控CPU使用狀態(tài)Binder
ServiceManager.addService("cpuinfo", new CpuBinder(this),
/* allowIsolated= */ false, DUMP_FLAG_PRIORITY_CRITICAL);
}
//注冊(cè)權(quán)限控制Binder
ServiceManager.addService("permission", new PermissionController(this));
//注冊(cè)進(jìn)程服務(wù)Binder
ServiceManager.addService("processinfo", new ProcessInfoService(this));
//查詢并處理ApplicationInfo
ApplicationInfo info = mContext.getPackageManager().getApplicationInfo(
"android", STOCK_PM_FLAGS | MATCH_SYSTEM_ONLY);
//將Application信息配置到ActivityThread中
mSystemThread.installSystemApplicationInfo(info, getClass().getClassLoader());
synchronized (this) {
//創(chuàng)建并處理ProcessRecord
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);
}
}
}
});
}
1)添加了各種服務(wù)瞭空,如AMS
2)mSystemThread.installSystemApplicationInfo:最終調(diào)到LoadedApk,這是應(yīng)用的基本信息
接著看startOtherServices
private void startOtherServices() {
//AMS與WMS關(guān)聯(lián)
mActivityManagerService.setWindowManager(wm);
//安裝ContentProvider
mActivityManagerService.installSystemProviders();
//所有的服務(wù)已經(jīng)準(zhǔn)備就緒
mActivityManagerService.systemReady(() -> {
//啟動(dòng)系統(tǒng)UI
startSystemUi(context, windowManagerF);
//執(zhí)行一系列服務(wù)的systemReady
networkStatsF.systemReady();
//...
}
}
installSystemProviders
public final void installSystemProviders() {
List<ProviderInfo> providers;
synchronized (this) {
//找到名為"system"的進(jìn)程,就是setSystemProcess中創(chuàng)建的ProcessRecord對(duì)象
ProcessRecord app = mProcessList.mProcessNames.get("system", SYSTEM_UID);
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) {
//移除非系統(tǒng)provider
Slog.w(TAG, "Not installing system proc provider " + pi.name
+ ": not system .apk");
providers.remove(i);
}
}
}
}
if (providers != null) {
//安全所有的系統(tǒng)provider
mSystemThread.installSystemProviders(providers);
}
synchronized (this) {
mSystemProvidersInstalled = true;
}
mConstants.start(mContext.getContentResolver());
//創(chuàng)建核心Settings Observer咆畏,用于監(jiān)聽Settings的改變
mCoreSettingsObserver = new CoreSettingsObserver(this);
mActivityTaskManager.installSystemProviders();
//開發(fā)者權(quán)限
mDevelopmentSettingsObserver = new DevelopmentSettingsObserver();
SettingsToPropertiesMapper.start(mContext.getContentResolver());
mOomAdjuster.initSettings();
// Now that the settings provider is published we can consider sending
// in a rescue party.
RescueParty.onSettingsProviderPublished(mContext);
//mUsageStatsService.monitorPackages();
}
1)installSystemProviders:安裝系統(tǒng)Provider
2)new CoreSettingsObserver(this):創(chuàng)建CoreSettingsObserver南捂,用于監(jiān)聽系統(tǒng)設(shè)置的改變
systemReady
public void systemReady(final Runnable goingCallback, TimingsTraceLog traceLog) {
//啟動(dòng)Launcher界面
mAtmInternal.startHomeOnAllDisplays(currentUserId, "systemReady");
}
小結(jié):
1、new SystemServer()創(chuàng)建了ActivityThread
2旧找、SystemServer的run方法中:
1)通過createSystemContext方法創(chuàng)建系統(tǒng)上下文對(duì)象
2)在startBootstrapServices方法中調(diào)用構(gòu)造方法對(duì)AMS進(jìn)行初始化溺健,start方法啟動(dòng)AMS
3)調(diào)用setSystemProcess將AMS注冊(cè)到ServiceManager中
4)在startOtherServices中安裝了系統(tǒng)Provider
5)調(diào)用systemReady啟動(dòng)Launcher界面