ActivityManagerService在Android系统起到很重要的作用,总管这四大组件、进程管理调度和监测统计等,AMS其实跑在SystemServer进程里,生命周期跟随SystemServer进程。
本文主要参考ActivityManagerService的启动过程
由于AMS是由系统进程SystemServer初始化的,所以从SystemServer的启动开始看起。
系统启动时,Zygote进程会从Native层调用SystemServer的main函数,该函数会直接创建SystemServer的对象,并调用run函数开始初始化,可以看到SystemServer的初始化主要涉及以下几部分:
public static void main(String[] args) {
new SystemServer().run();
}
private void run() {
//开始系统进程启动前的初始化操作
try {
// Prepare the main looper thread (this thread).
android.os.Process.setThreadPriority(
android.os.Process.THREAD_PRIORITY_FOREGROUND);
android.os.Process.setCanSelfBackground(false);
//启动主线程的Looper,主线程的Looper不可以退出,子线程则可以退出
Looper.prepareMainLooper();
Looper.getMainLooper().setSlowLogThresholdMs(
SLOW_DISPATCH_THRESHOLD_MS, SLOW_DELIVERY_THRESHOLD_MS);
// Initialize native services.
System.loadLibrary("android_servers");
// Initialize the system context.
createSystemContext();
//创建SystemServiceManager,用来管理所有的系统服务
// Create the system service manager.
mSystemServiceManager = new SystemServiceManager(mSystemContext);
mSystemServiceManager.setStartInfo(mRuntimeRestart,
mRuntimeStartElapsedTime, mRuntimeStartUptime);
//LocalServices类似SystemServiceManager,区别在于LocalServices管理同一进程的Service
LocalServices.addService(SystemServiceManager.class, mSystemServiceManager);
// Prepare the thread pool for init tasks that can be parallelized
SystemServerInitThreadPool.get();
} finally {
traceEnd(); // InitBeforeStartServices
}
//开始启动各种必要的系统服务
traceBeginAndSlog("StartServices");
startBootstrapServices();
startCoreServices();
startOtherServices();
SystemServerInitThreadPool.shutdown();
//开始SystemServer进程的loop循环
Looper.loop();
throw new RuntimeException("Main thread loop unexpectedly exited");
}
private void createSystemContext() {
//创建系统进程的主线程
ActivityThread activityThread = ActivityThread.systemMain();
mSystemContext = activityThread.getSystemContext();
mSystemContext.setTheme(DEFAULT_SYSTEM_THEME);
final Context systemUiContext = activityThread.getSystemUiContext();
systemUiContext.setTheme(DEFAULT_SYSTEM_THEME);
}
上节说过AMS的启动在startBootstrapServices,看下该函数的具体实现,可以看到启动AMS并不是直接启动的,而是经过Lifecycle这个类来处理,Lifecycle是AMS的内部类,继承SystemService。
private void startBootstrapServices() {
//启动Watchdog,监控系统服务性能
traceBeginAndSlog("StartWatchdog");
final Watchdog watchdog = Watchdog.getInstance();
watchdog.start();
traceEnd();
//开始启动AMS和ActivityTaskManagerService
traceBeginAndSlog("StartActivityManager");
// TODO: Might need to move after migration to WM.
ActivityTaskManagerService atm = mSystemServiceManager.startService(
ActivityTaskManagerService.Lifecycle.class).getService();
mActivityManagerService = ActivityManagerService.Lifecycle.startService(
mSystemServiceManager, atm);
mActivityManagerService.setSystemServiceManager(mSystemServiceManager);
mActivityManagerService.setInstaller(installer);
mWindowManagerGlobalLock = atm.getGlobalLock();
traceEnd();
//将SystemServer设置为系统进程
traceBeginAndSlog("SetSystemProcess");
mActivityManagerService.setSystemProcess();
traceEnd();
// 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
//将AMS添加到Watchdog进行检测
traceBeginAndSlog("InitWatchdog");
watchdog.init(mSystemContext, mActivityManagerService);
traceEnd();
}
其实在Lifecycle构造函数中就把AMS进行了初始化,那什么时候开始构造的Lifecycle类的呢?可以看到,在startService函数中,把Lifecycle类传入了SystemServiceManager的startService函数中,所以最终的启动是通过SystemServiceManager来处理。
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;
//(1) 其实最终还是交给SystemServiceManager处理startService
return ssm.startService(ActivityManagerService.Lifecycle.class).getService();
}
@Override
public void onStart() {
//(2) 最终会回调onStart,然后调用AMS的start方法
mService.start();
}
}
来到SystemServiceManager的代码逻辑中,startService函数中,主要是通过反射来构造SystemService,而此时传入的是ActivityManagerService.Lifecycle类,所以构造的是Lifecycle,从而开始构造AMS,完成初始化,获得AMS对象,将其加入mServices列表中。
//所有注册过的系统服务都保存在mServices这个列表里
private final ArrayList<SystemService> mServices = new ArrayList<SystemService>();
SystemServiceManager(Context context) {
mContext = context;
}
/**
* 通过反射将将服务创建,这个地方传入的是ActivityManagerService.Lifecycle类,所以构造的Lifecycle类
* Starts a service by class name.
* @return The service instance.
*/
public SystemService startService(String className) {
final Class<SystemService> serviceClass;
try {
serviceClass = (Class<SystemService>)Class.forName(className);
} catch (ClassNotFoundException ex) {
.....
}
return startService(serviceClass);
}
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);
} catch (InstantiationException ex) {
}
startService(service);
return service;
} finally {
Trace.traceEnd(Trace.TRACE_TAG_SYSTEM_SERVER);
}
}
//Service启动完成后,将Service加入mServices列表,然后回调对应service的onStart函数
public void startService(@NonNull final SystemService service) {
// Register it.
mServices.add(service);
// Start it.
try {
service.onStart();
} catch (RuntimeException ex) {
....
}
}
从AMS的构造函数中可以看出其主要的职责:
public ActivityManagerService(Context systemContext, ActivityTaskManagerService atm) {
//系统上下文
mContext = systemContext;
//系统进程的主线程,SystemServer初始化时创建
mSystemThread = ActivityThread.currentActivityThread();
mUiContext = mSystemThread.getSystemUiContext();
//处理消息的线程,比如ANR处理
mHandlerThread = new ServiceThread(TAG,
THREAD_PRIORITY_FOREGROUND, false /*allowIo*/);
mHandlerThread.start();
mHandler = new MainHandler(mHandlerThread.getLooper());
//进程内存相关统计和处理,ProcessList保存进程信息,根据Adj优先级杀进程
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);
//创建广播队列,分前台后台,并分别设置不同的超时时间:前台10s,后台60s
// Broadcast policy parameters
final BroadcastConstants foreConstants = new BroadcastConstants(
Settings.Global.BROADCAST_FG_CONSTANTS);
foreConstants.TIMEOUT = BROADCAST_FG_TIMEOUT;
final BroadcastConstants backConstants = new BroadcastConstants(
Settings.Global.BROADCAST_BG_CONSTANTS);
backConstants.TIMEOUT = BROADCAST_BG_TIMEOUT;
..........
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;
//管理Service和Provider组件的相关类
mServices = new ActiveServices(this);
mProviderMap = new ProviderMap(this);
mPackageWatchdog = PackageWatchdog.getInstance(mUiContext);
mAppErrors = new AppErrors(mUiContext, this, mPackageWatchdog);
//创建目录system/data/
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());
.......
mOomAdjProfiler.batteryPowerChanged(mOnBattery);
//进程状态的统计
mProcessStats = new ProcessStatsService(this, new File(systemDir, "procstats"));
mActivityTaskManager = atm;
mActivityTaskManager.initialize(mIntentFirewall, mPendingIntentController,
DisplayThread.get().getLooper());
mAtmInternal = LocalServices.getService(ActivityTaskManagerInternal.class);
//CPU监控线程
mProcessCpuThread = new Thread("CpuTracker") {
@Override
public void run() {
.....
}
};
mHiddenApiBlacklist = new HiddenApiSettings(mHandler, mContext);
//将自己加入Watchdog的监控
Watchdog.getInstance().addMonitor(this);
Watchdog.getInstance().addThread(mHandler);
}
在SystemServer进程的启动过程中,我们发现,SystemServer进程是通过调用AMS的setSystemProcess函数来将自己注册成系统服务的,该函数主要功能:
public void setSystemProcess() {
try {
ServiceManager.addService(Context.ACTIVITY_SERVICE, this, /* allowIsolated= */ true,
DUMP_FLAG_PRIORITY_CRITICAL | DUMP_FLAG_PRIORITY_NORMAL | DUMP_FLAG_PROTO);
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));
ApplicationInfo info = mContext.getPackageManager().getApplicationInfo(
"android", STOCK_PM_FLAGS | MATCH_SYSTEM_ONLY);
mSystemThread.installSystemApplicationInfo(info, getClass().getClassLoader());
synchronized (this) {
//创建进程的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; //设置进程优先级,内存不足时会根据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需要处理的业务非常多,包括四大组件的启动和生命周期的管理,以及进程的内存性能相关的统计。