Learn Some Framework-5 ActivityManagerService[Initialize]
在之前的章节,我们花了大量时间为大家介绍ServiceManager与Binder机制,在这一章节开始我们通过对ActivityManagerService这个Android核心的SystemService的学习,来理解系统级的Java Service是如何工作的
我们在介绍Zygote与SystemServer一章时介绍过, startBootstrapServices启动了Android启动必不可少的几个系统级的Service,他们是Installer, AMS, PowerManagerService, LightService, PMS和SensorService, 其中的AMS就是我们今天的主角ActivityManagerService.
AMS的启动代码如下:
private void startBootstrapServices() {
...
// Activity manager runs the show.
mActivityManagerService = mSystemServiceManager.startService(
ActivityManagerService.Lifecycle.class).getService();
mActivityManagerService.setSystemServiceManager(mSystemServiceManager);
mActivityManagerService.setInstaller(installer);
...
// Set up the Application instance for the system process and get started.
mActivityManagerService.setSystemProcess();
...
}
可以看出,从Marshmallow开始,AMS其实是被其一个Inner Class Lifecycle叫起,Lifecycle的实现非常简单:
public static final class Lifecycle extends SystemService {
private final ActivityManagerService mService;
public Lifecycle(Context context) {
super(context);
mService = new ActivityManagerService(context);
}
@Override
public void onStart() {
mService.start();
}
public ActivityManagerService getService() {
return mService;
}
}
这是一个静态的内部类,于是他的生命周期实现了与AMS的隔离,在它的constructor内,一个新的AMS的实例被构造出来,接着,在它的onStart方法内,AMS被启动。
我们先来看AMS的constructor:
// 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) {
mContext = systemContext;
mFactoryTest = FactoryTest.getMode();
mSystemThread = ActivityThread.currentActivityThread();
Slog.i(TAG, "Memory class: " + ActivityManager.staticGetMemoryClass());
mHandlerThread = new ServiceThread(TAG,
android.os.Process.THREAD_PRIORITY_FOREGROUND, false /*allowIo*/);
mHandlerThread.start();
mHandler = new MainHandler(mHandlerThread.getLooper());
mUiHandler = new UiHandler();
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;
mServices = new ActiveServices(this);
mProviderMap = new ProviderMap(this);
// TODO: Move creation of battery stats service outside of activity manager service.
File dataDir = Environment.getDataDirectory();
File systemDir = new File(dataDir, "system");
systemDir.mkdirs();
mBatteryStatsService = new BatteryStatsService(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 = new AppOpsService(new File(systemDir, "appops.xml"), mHandler);
mGrantFile = new AtomicFile(new File(systemDir, "urigrants.xml"));
// User 0 is the first and only user that runs at boot.
mStartedUsers.put(UserHandle.USER_OWNER, new UserState(UserHandle.OWNER, true));
mUserLru.add(UserHandle.USER_OWNER);
updateStartedUserArrayLocked();
GL_ES_VERSION = SystemProperties.getInt("ro.opengles.version",
ConfigurationInfo.GL_ES_VERSION_UNDEFINED);
mTrackingAssociations = "1".equals(SystemProperties.get("debug.track-associations"));
mConfiguration.setToDefaults();
mConfiguration.setLocale(Locale.getDefault());
mConfigurationSeq = mConfiguration.seq = 1;
mProcessCpuTracker.init();
mCompatModePackages = new CompatModePackages(this, systemDir, mHandler);
mIntentFirewall = new IntentFirewall(new IntentFirewallInterface(), mHandler);
mRecentTasks = new RecentTasks(this);
mStackSupervisor = new ActivityStackSupervisor(this, mRecentTasks);
mTaskPersister = new TaskPersister(systemDir, mStackSupervisor, mRecentTasks);
mProcessCpuThread = new Thread("CpuTracker") {
@Override
public void run() {
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);
}
}
}
};
Watchdog.getInstance().addMonitor(this);
Watchdog.getInstance().addThread(mHandler);
}
这个方法很简单,但是涉及到很多AMS的概念,我们逐一介绍:
首先,入参的context的来源,可以发现:
整个过程,其实Context最早在SystemServer中初始化,之后SystemServer在构建SystemServiceManager时,带入了该Context,接下来就由SystemServiceManager将这个Context传给了各个系统级的Service线程。
接下来mFactoryTest是工厂模式的读取,这个涉及到开机的应用是HOME还是工厂测试应用,相关的知识点我们会在后续章节介绍,目前不影响阅读。
mSystemThread是当前ActivityThread的实例,对于AMS自然就是system_process的ActivityThread,它的构造是在我们上方diagram内ActivityThread#systemMain这个方法内,在这里面通过调用Activity#attach方法,将当前ActivityThread的实例attach。
mHandlerThread是一个ServiceThread,而ServiceThread继承至HandlerThread,于是这个实例其实目的就是提供一个Looper给接下来的MainHandler, 这个Handler并没有在SystemServer的main loop内处理消息,而是利用了AMS专属的ServiceThread,这样这个Handler便是AMS独有的,不会因为处理其他service的问题被阻塞。
mUiHandler是在UI线程(主线程)的Handler,主要处理一些UI相关的消息。
mFgBroadcastQueue, mBgBroadcastQueue是两个前后台广播存放的queue,我们之后的章节会讲到,根据是否是低内存设备,queue的长度会不同,原生的低内存设备存放25条,非低内存设备可以存放300条。
mBroadcastQueues是组织上面两个queue的地方。
mServices是ActiveService的实例,之后主要负责Service相关的操作。
mProviderMap是ProviderMap的实例,之后主要负责provider相关的操作。
接下来初始化system文件,并初始化电池电量监控,这部分我们在后续章节会有单独介绍。
mStartedUsers记录了User0作为第一个User。
接下来是一些MultiUser的处理。
GL_ES_VERSION是当前opengl的版本。
mIntentFirewall会更安全地处理XML内的Intent。
mRecentTasks记录了最近的Activity Task栈。
mStackSupervisor是Activity栈的处理者,我们稍后会看到,Activity的切换是透过它完成的。
mProcessCpuThread是记录CPU状态的一个线程。
Watchdog相关知识我们会在介绍ANR时再介绍。
接下来便进入了start:
private void start() {
Process.removeAllProcessGroups();
mProcessCpuThread.start();
mBatteryStatsService.publish(mContext);
mAppOpsService.publish(mContext);
Slog.d("AppOps", "AppOpsService published");
LocalServices.addService(ActivityManagerInternal.class, new LocalService());
}
实际上就是启动了constructor内的一些thread等。
最后就是setSystemProcess这个方法了:
public void setSystemProcess() {
try {
ServiceManager.addService(Context.ACTIVITY_SERVICE, this, true);
ServiceManager.addService(ProcessStats.SERVICE_NAME, mProcessStats);
ServiceManager.addService("meminfo", new MemBinder(this));
ServiceManager.addService("gfxinfo", new GraphicsBinder(this));
ServiceManager.addService("dbinfo", new DbBinder(this));
if (MONITOR_CPU_USAGE) {
ServiceManager.addService("cpuinfo", new CpuBinder(this));
}
ServiceManager.addService("permission", new PermissionController(this));
ServiceManager.addService("processinfo", new ProcessInfoService(this));
ApplicationInfo info = mContext.getPackageManager().getApplicationInfo(
"android", STOCK_PM_FLAGS);
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();
}
} catch (PackageManager.NameNotFoundException e) {
throw new RuntimeException(
"Unable to find android system package", e);
}
}
如同我们之前讲过的,其实这里便是在向ServiceManager注册一系列的Service,之后Client可以通过getService拿到这些Service的Bn端来实现与Bp端的通信。
至此,AMS的初始化就完成了,并不复杂,很多变量我们会在之后的学习中了解用意。