AMS
全称ActivityManagerService
,它作为一个系统服务管理着Activity
、Service
、ContentProvider
和BroadcastReceiver
这四大组件的启动,可以说ActivityManagerService
服务对于Android系统来讲十分的重要。文章将从AMS的启动
和AMS如何管理Activity的启动
这两方面来分析AMS在Android体系中所发挥的作用。
首先AMS的启动是在SystemServer
中完成的,SystemServer
负责启动各种各样的系统服务,这里就包括ActivityManagerService
。
SystemServer#startBootstrapServices
private void startBootstrapServices() {
//创建AMS,并通过系统服务管理器启动AMS
mActivityManagerService = mSystemServiceManager.startService(
ActivityManagerService.Lifecycle.class).getService();
//设置SystemServiceManager
mActivityManagerService.setSystemServiceManager(mSystemServiceManager);
//设置Installer服务
mActivityManagerService.setInstaller(installer);
//初始化与之相关的PowerManager
mActivityManagerService.initPowerManagement();
//将AMS和一些需要的服务注册到ServiceManager中(ServiceManager是由Init进程启动的)
mActivityManagerService.setSystemProcess();
}
SystemServer#startCoreServices
private void startCoreServices() {
//设置UsageStatsManager
mActivityManagerService.setUsageStatsManager(
LocalServices.getService(UsageStatsManagerInternal.class));
}
SystemServer#startOtherServices
private void startOtherServices() {
//为SystemServer进程安装ContentProvider对象
mActivityManagerService.installSystemProviders();
//设置WindowManager(WMS)
mActivityManagerService.setWindowManager(wm);
if (safeMode) {
//设置安全模式
mActivityManagerService.enterSafeMode();
}
if (safeMode) {
//设置安全模式的View
mActivityManagerService.showSafeModeOverlay();
}
//AMS启动完毕
mActivityManagerService.systemReady(() -> {
//标记SystemServer的阶段
mSystemServiceManager.startBootPhase(
SystemService.PHASE_ACTIVITY_MANAGER_READY);
try {
//开启独立的线程监听Native崩溃
mActivityManagerService.startObservingNativeCrashes();
....
开启WebView更新服务
启动系统ui
设置各种服务的onReady
....
}
}
}
上面三个方法中的代码就是SystemServer中关于ActivityManagerService的相关流程的核心代码。方法在SystemServer中的调用顺序是startBootstrapServices
->startCoreServices
->startOtherServices
。整体的流程可以归纳为几个核心的步骤:
1)创建AMS并启动。
2)将AMS注册到ServiceManager中。
3)为SystemServer进程安装ContentProvider对象。
4)标记AMS启动完毕。
首先来从SystemServiceManager的startService方法入手。
SystemServiceManager#startService
public <T extends SystemService> T startService(Class<T> serviceClass) {
try {
//获取类名
final String name = serviceClass.getName();
final T service;
try {
Constructor<T> constructor = serviceClass.getConstructor(Context.class);
//反射创建对象
service = constructor.newInstance(mContext);
}
....
startService(service);
return service;
}
....
}
SystemServiceManager#startService
public void startService(@NonNull final SystemService service) {
//添加到Service的集合中
mServices.add(service);
//时间戳
long time = SystemClock.elapsedRealtime();
try {
//启动服务
service.onStart();
}
....
//超时警告
warnIfTooLong(SystemClock.elapsedRealtime() - time, service, "onStart");
}
从以上代码可以看出SystemServiceManager通过传入的Class反射创建对象,最后调用service的onStart方法启动服务,这里传入的类型就是ActivityManagerService.Lifecycle.class。
public static final class Lifecycle extends SystemService {
private final ActivityManagerService mService;
public Lifecycle(Context context) {
super(context);
//创建ActivityManagerService
mService = new ActivityManagerService(context);
}
@Override
public void onStart() {
//启动服务,上方service.onStart()方法调用到的就是这里
mService.start();
}
@Override
public void onBootPhase(int phase) {
//设置启动阶段
mService.mBootPhase = phase;
if (phase == PHASE_SYSTEM_SERVICES_READY) {
mService.mBatteryStatsService.systemServicesReady();
mService.mServices.systemServicesReady();
}
}
@Override
public void onCleanupUser(int userId) {
mService.mBatteryStatsService.onCleanupUser(userId);
}
public ActivityManagerService getService() {
//返回ActivityManagerService实例对象
return mService;
}
}
可以看到ActivityManagerService.Lifecycle继承于SystemService,通过Lifecycle来完成ActivityManagerService对象的创建、启动和实例的返回。接下来分析ActivityManagerService的构造方法和start方法。
public ActivityManagerService(Context systemContext) {
....
//获取Context
mContext = systemContext;
//获取系统ActivityThread
mSystemThread = ActivityThread.currentActivityThread();
//获取系统ui Context
mUiContext = mSystemThread.getSystemUiContext();
....
//创建一个HandlerThread来接收AMS发送的消息
mHandlerThread = new ServiceThread(TAG,
THREAD_PRIORITY_FOREGROUND, false /*allowIo*/);
mHandlerThread.start();
mHandler = new MainHandler(mHandlerThread.getLooper());
mUiHandler = mInjector.getUiHandler(this);
//创建与启动proc线程
mProcStartHandlerThread = new ServiceThread(TAG + ":procStart",
THREAD_PRIORITY_FOREGROUND, false /* allowIo */);
mProcStartHandlerThread.start();
mProcStartHandler = new Handler(mProcStartHandlerThread.getLooper());
//一些管理的常量
mConstants = new ActivityManagerConstants(this, mHandler);
//前台广播队列
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;
//初始化Service相关的容器
mServices = new ActiveServices(this);
//初始化ProviderMap相关的容器
mProviderMap = new ProviderMap(this);
mAppErrors = new AppErrors(mUiContext, this);
//创建data/system/目录
File dataDir = Environment.getDataDirectory();
File systemDir = new File(dataDir, "system");
systemDir.mkdirs();
//初始化电量统计服务相关的信息
mBatteryStatsService = new BatteryStatsService(systemContext, 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"));
mAppOpsService = mInjector.getAppOpsService(new File(systemDir, "appops.xml"), mHandler);
mGrantFile = new AtomicFile(new File(systemDir, "urigrants.xml"), "uri-grants");
//创建系统的第一个user,userID为0,该用户具有管理员权限
mUserController = new UserController(this);
mVrController = new VrController(this);
//获取opengle的版本
GL_ES_VERSION = SystemProperties.getInt("ro.opengles.version",
ConfigurationInfo.GL_ES_VERSION_UNDEFINED);
....
//初始化StackSupervisor,该类是Activity启动和调度的核心类
mStackSupervisor = createStackSupervisor();
mActivityStartController = new ActivityStartController(this);
mRecentTasks = createRecentTasks();
mStackSupervisor.setRecentTasks(mRecentTasks);
//检查cpu的线程
mProcessCpuThread = new Thread("CpuTracker");
....
}
从上可以看出,ActivityManagerService的构造方法做了大量的初始化相关操作。首先记录运行需要的Context和ActivityThread。然后初始化广播、服务和contentProvider的相关存储变量,还会进行初始化电量统计服务等信息,还创建了ActivityStackSupervisor用来管理和调度Activity。
ActivityManagerService#start
private void start() {
//启动cpu检查线程
mProcessCpuThread.start();
//发布电量统计服务
mBatteryStatsService.publish();
mAppOpsService.publish(mContext);
//注册当前的服务到LocalServices,LocalService是AMS的内部类,间接对外暴露AMS的使用
LocalServices.addService(ActivityManagerInternal.class, new LocalService());
....
}
AMS的start相对简单,就是开启了几个相关服务和cpu的检查并将自身间接注册到LocalServices中。
接下来分析如何将AMS注册到ServiceManager中,这里需要来分析AMS的setSystemProcess方法。
ActivityManagerService#setSystemProcess
public void setSystemProcess() {
try {
//将AMS注册到ServiceManager中,key为“activity”
ServiceManager.addService(Context.ACTIVITY_SERVICE, this, /* allowIsolated= */ true,
DUMP_FLAG_PRIORITY_CRITICAL | DUMP_FLAG_PRIORITY_NORMAL | DUMP_FLAG_PROTO);
//注册各种各样的服务到ServiceManager中
ServiceManager.addService(ProcessStats.SERVICE_NAME, mProcessStats);
ServiceManager.addService("meminfo", new MemBinder(this), /* allowIsolated= */ false,
DUMP_FLAG_PRIORITY_HIGH);
ServiceManager.addService("gfxinfo", new GraphicsBinder(this));
ServiceManager.addService("dbinfo", new DbBinder(this));
if (MONITOR_CPU_USAGE) {
ServiceManager.addService("cpuinfo", new CpuBinder(this),
/* allowIsolated= */ false, DUMP_FLAG_PRIORITY_CRITICAL);
}
ServiceManager.addService("permission", new PermissionController(this));
ServiceManager.addService("processinfo", new ProcessInfoService(this));
//从PackageManager中查询包名为android的application,即framework-res的Application信息
ApplicationInfo info = mContext.getPackageManager().getApplicationInfo
"android", STOCK_PM_FLAGS | MATCH_SYSTEM_ONLY);
//将application信息配置到开始创建的activityThread中
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();
}
}
....
}
setSystemProcess方法最核心的一点就是将AMS注册到ServiceManager中,这样后续使用AMS的地方就可以通过ServiceManager来获取到了。
Android系统中有很多配置信息都需要保存,这些信息是保存在SettingsProvider中,而这个SettingsProvider也是运行在SystemServer进程中的,由于SystemServer进程依赖SettingsProvider,放在一个进程中可以减少进程间通信的效率损失。
public final void installSystemProviders() {
List<ProviderInfo> providers;
synchronized (this) {
//找到名称为”System”的进程,就是上一步创建的processRecord对象
ProcessRecord app = mProcessNames.get("system", SYSTEM_UID);
//找到所有和system进程相关的ContentProvider
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) {
//再次确认进程为system的provider,把不是该进程provider移除
providers.remove(i);
}
}
}
}
if (providers != null) {
//把provider安装到系统的ActivityThread中
mSystemThread.installSystemProviders(providers);
}
synchronized (this) {
//设置已安装标记位
mSystemProvidersInstalled = true;
}
//初始化各种Observer
mConstants.start(mContext.getContentResolver());
mCoreSettingsObserver = new CoreSettingsObserver(this);
mFontScaleSettingObserver = new FontScaleSettingObserver();
mDevelopmentSettingsObserver = new DevelopmentSettingsObserver();
GlobalSettingsToPropertiesMapper.start(mContext.getContentResolver());
RescueParty.onSettingsProviderPublished(mContext);
}
找到名称为system的进程对象,就是SystemServer进程,然后根据进程对象去查询所有有关的ContentProvider,调用系统进程的主线程ActivityThread安装所有相关的ContentProvider
AMS的启动最后阶段来到systemReady方法。
public void systemReady(final Runnable goingCallback, TimingsTraceLog traceLog) {
synchronized(this) {
if (mSystemReady) {
//回调SystemServer
if (goingCallback != null) {
goingCallback.run();
}
return;
}
mHasHeavyWeightFeature = mContext.getPackageManager().hasSystemFeature(
PackageManager.FEATURE_CANT_SAVE_STATE);
mLocalDeviceIdleController
= LocalServices.getService(DeviceIdleController.LocalService.class);
mAssistUtils = new AssistUtils(mContext);
//调用各种服务的Ready方法
mVrController.onSystemReady();
mUserController.onSystemReady();
mRecentTasks.onSystemReadyLocked();
mAppOpsService.systemReady();
mSystemReady = true;
}
try {
//获取设备识别字符串
sTheRealBuildSerial = IDeviceIdentifiersPolicyService.Stub.asInterface(
ServiceManager.getService(Context.DEVICE_IDENTIFIERS_SERVICE))
.getSerial();
} catch (RemoteException e) {}
//收集目前已经存在的进程
ArrayList<ProcessRecord> procsToKill = null;
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);
}
}
}
//销毁在AMS启动之前存在的进程
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");
}
}
mProcessesReady = true;
}
....
//初始化Settings变量
retrieveSettings();
//获取UserId
final int currentUserId = mUserController.getCurrentUserId();
synchronized (this) {
//读取权限
readGrantedUriPermissionsLocked();
}
//获取PowerManager并注册监听
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);
}
//调用callback方法,该方法在systemServer代码中实现
if (goingCallback != null) goingCallback.run();
//给BatteryStatsService发送状态
mBatteryStatsService.noteEvent(BatteryStats.HistoryItem.EVENT_USER_RUNNING_START,
Integer.toString(currentUserId), currentUserId);
mBatteryStatsService.noteEvent(BatteryStats.HistoryItem.EVENT_USER_FOREGROUND_START,
Integer.toString(currentUserId), currentUserId);
//SystemServiceManager设置UserId
mSystemServiceManager.startUser(currentUserId);
synchronized (this) {
....
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();
}
}
//开启HomeActivity
startHomeActivityLocked(currentUserId, "systemReady");
....
//最上层Activity获取焦点
mStackSupervisor.resumeFocusedStackTopActivityLocked();
mUserController.sendUserSwitchBroadcasts(-1, currentUserId);
....
}
}
SystemReady方法代码量也比较大,主要做了几种工作:
1.调用了几种AMS所需要的服务的onSystemReady回调。
2.移除并杀死了那些不该在AMS之前启动的进程。
3.回调SystemServer当前服务准备已经完成,SystemServer中会启动系统ui,开启WbView更新和调用各种服务的onReday。
4.启动HomeActivity。
上面分析了在SystemServer中AMS是如何启动的,AMS管理着四大组件的启动,这里以Activity为例简单分析一下AMS在Activity启动过程中所起到的作用。
Activity#startActivityForResult
public void startActivityForResult(@RequiresPermission Intent intent, int requestCode,
@Nullable Bundle options) {
//其实在Activity中startActivity方法最终都是调用到startActivityForResult,所以这里直接从startActivityForResult为入口进行分析。
....
//调用到Instrumentation的execStartActivity方法
Instrumentation.ActivityResult ar =
mInstrumentation.execStartActivity(
this, mMainThread.getApplicationThread(), mToken, this,
intent, requestCode, options);
....
}
Instrumentation#execStartActivity
public ActivityResult execStartActivity(
Context who, IBinder contextThread, IBinder token, String target,
Intent intent, int requestCode, Bundle options) {
....
//调用ActivityManager.getService获取AMS,并调用AMS的startActivity方法
int result = ActivityManager.getService()
.startActivity(whoThread, who.getBasePackageName(), intent,
intent.resolveTypeIfNeeded(who.getContentResolver()),
token, target, requestCode, 0, null, options);
....
}
ActivityManager#getService
public static IActivityManager getService() {
return IActivityManagerSingleton.get();
}
private static final Singleton<IActivityManager> IActivityManagerSingleton =
new Singleton<IActivityManager>() {
@Override
protected IActivityManager create() {
//通过ServiceManager获取AMS,之前AMS启动的流程中注册到了ServiceManager中
final IBinder b = ServiceManager.getService(Context.ACTIVITY_SERVICE);
final IActivityManager am = IActivityManager.Stub.asInterface(b);
return am;
}
};
从上面的代码可以看出startActivity方法经过调用来到了Instrumentation的execStartActivity最后获取到了AMS对象,即ActivityManagerService。之后调用的就是ActivityManagerService的startActivity方法了。
ActivityManagerService#startActivity
public final int startActivity(IApplicationThread caller, String callingPackage,
Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode,
int startFlags, ProfilerInfo profilerInfo, Bundle options) {
return startActivityAsUser(caller, callingPackage, intent, resolvedType, resultTo,
resultWho, requestCode, startFlags, profilerInfo, options,
UserHandle.getCallingUserId());
}
ActivityManagerService#startActivityAsUser
public final int startActivityAsUser(IApplicationThread caller, String callingPackage,
Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode,
int startFlags, ProfilerInfo profilerInfo, Bundle options, int userId) {
//调用到了mStackSupervisor来管理Activity
return mStackSupervisor.startActivityMayWait(caller, -1, callingPackage, intent,
resolvedType, null, null, resultTo, resultWho, requestCode, startFlags,
profilerInfo, null, null, options, false, userId, null, null);
}
现在方法调用来到了ActivityManagerService中了,整体Activity的启动流程还是挺复杂的,会涉及到Activity的栈管理、app进程管理等流程,这里就不进行代码分析了,感兴趣的可以看一下这篇文章Activity启动流程
AMS最为Android系统中的十分核心服务,管理着四大组件的启动,由SystemServer进程来启动。大体启动流程分为几步:
1. 在SystemServer服务中创建并启动AMS。
2. 调用AMS的构造方法和start方法,对AMS必要的内容进行初始化。
3. 将AMS注册到ServiceManager中,ServiceManager作为大管家管理AMS服务。AMS的使用直接通过ServiceManager来获取。
4. 将settingsProvider加载到系统进程systemServer中。
5. 在AMS启动完成后开启系统HomeActivity和systemUI。