内容讲解
结合之前的写的 Activity启动过程 和 Service源码解析 两篇内容中我们都提到一个不可忽视的服务
ActivityManagerService 即 AMS
,我们下面就来讲解一下AMS
的启动过程和具体功效分析
AMS基础讲解
功效
- 负责四大组件的启动、调度和销毁
- 应用程序的进程管理和调度
启动过程源码解析
我们先分析AMS
在SystemService main函数
中的启动过程
[1] AMS是在SystemServer
进程中启动的主要入口
//zygote孵化的主要入口
public static void main(String[] args) {
new SystemServer().run();
}
[2] 我们来看一下在 run函数
中的工作
private void run() {
try {
...
//加载libandroid_server.so文件,初始化本地服务
System.loadLibrary("android_servers");
...
// 初始化系统上下文环境
createSystemContext();
//创建系统服务管理器.
mSystemServiceManager = new SystemServiceManager(mSystemContext);
mSystemServiceManager.setRuntimeRestarted(mRuntimeRestart);
//向系统本地服务添加系统服务管理器
LocalServices.addService(SystemServiceManager.class, mSystemServiceManager);
//获取线程池执行初始化任务
SystemServerInitThreadPool.get();
} finally {
traceEnd(); // InitBeforeStartServices
}
// Start services.
try {
traceBeginAndSlog("StartServices");
//[1]主干 -> 启动程序引导服务其中包括(AMS Activity管理器、PMS package管理器 [包管理器]、PMS power管理器[电源管理器])
startBootstrapServices();
startCoreServices();// 启动核心服务
startOtherServices();//启动其它服务
SystemServerInitThreadPool.shutdown(); //关闭初始化任务线程池
} catch (Throwable ex) {
...
} finally {
traceEnd();
}
...
}
[3] 接下来我们去 startBootstrapServices函数
中看看AMS启动流程
private void startBootstrapServices() {
//读取配置信息
final String TAG_SYSTEM_CONFIG = "ReadingSystemConfig";
traceBeginAndSlog(TAG_SYSTEM_CONFIG);
//在系统服务器初始化期间使用的线程池,提交任务
SystemServerInitThreadPool.get().submit(SystemConfig::getInstance, TAG_SYSTEM_CONFIG);
traceEnd();
...
//[1]启动AMS
mActivityManagerService = mSystemServiceManager.startService(
ActivityManagerService.Lifecycle.class).getService();
//设置AMS系统服务管理器
mActivityManagerService.setSystemServiceManager(mSystemServiceManager);
mActivityManagerService.setInstaller(installer);
traceEnd();
traceBeginAndSlog("StartPowerManager");
//启动PMS服务
mPowerManagerService = mSystemServiceManager.startService(PowerManagerService.class);
traceEnd();
traceBeginAndSlog("InitPowerManagement");
//初始化AMS相关的PMS服务
mActivityManagerService.initPowerManagement();
traceEnd();
...
traceBeginAndSlog("SetSystemProcess");
//[2]向ServiceManager中注册Binder服务
mActivityManagerService.setSystemProcess();
traceEnd();
...
}
[4] 可以看到 此处调用了startService函数
方法,以ActivityManagerService.Lifecycle.class
作为参数进行传递
public <T extends SystemService> T startService(Class<T> serviceClass) {
try {
final String name = serviceClass.getName(); //获取类型
Trace.traceBegin(Trace.TRACE_TAG_SYSTEM_SERVER, "StartService " + name);
// 创建服务
if (!SystemService.class.isAssignableFrom(serviceClass)) {
throw new RuntimeException("Failed to create " + name
+ ": service must extend " + SystemService.class.getName());
}
final T service;
try {
//通过反射创建 Lifecycle类型的service对象
Constructor<T> constructor = serviceClass.getConstructor(Context.class);
service = constructor.newInstance(mContext);
}
...
//调取startService多态
startService(service);
return service;
} finally {
Trace.traceEnd(Trace.TRACE_TAG_SYSTEM_SERVER);
}
}
public void startService(@NonNull final SystemService service) {
//服务注册,将创建的service添加到mServices集合中
mServices.add(service);
// Start it.
long time = SystemClock.elapsedRealtime();
try {
//开启服务
service.onStart();
} catch (RuntimeException ex) {
throw new RuntimeException("Failed to start service " + service.getClass().getName()
+ ": onStart threw an exception", ex);
}
warnIfTooLong(SystemClock.elapsedRealtime() - time, service, "onStart");
}
下面我们进入ActivityServiceManager类
中的看看AMS
是如何执行启动操作的
在SystemService启动AMS
时我们以ActivityManagerService.Lifecycle.class
作为参数进行传递的,我们知晓Lifecycle类
是ActivityManagerService的内部类
public static final class Lifecycle extends SystemService {
private final ActivityManagerService mService;
public Lifecycle(Context context) {
super(context);
//[1] 创建AMS的实例
mService = new ActivityManagerService(context);
}
@Override
public void onStart() {
//[2] 启动AMS
mService.start();
}
@Override
public void onCleanupUser(int userId) {
mService.mBatteryStatsService.onCleanupUser(userId);
}
//获取AMS服务
public ActivityManagerService getService() {
return mService;
}
}
[2] 创建AMS实例
public ActivityManagerService(Context systemContext) {
LockGuard.installLock(this, LockGuard.INDEX_ACTIVITY);
mInjector = new Injector();
mContext = systemContext; //获取系统上下文环境
mFactoryTest = FactoryTest.getMode();
mSystemThread = ActivityThread.currentActivityThread();//获取当前ActivityThread线程
mUiContext = mSystemThread.getSystemUiContext();
Slog.i(TAG, "Memory class: " + ActivityManager.staticGetMemoryClass());
mPermissionReviewRequired = mContext.getResources().getBoolean(
com.android.internal.R.bool.config_permissionReviewRequired);
mHandlerThread = new ServiceThread(TAG,
THREAD_PRIORITY_FOREGROUND, false /*allowIo*/); //创建前台线程
mHandlerThread.start(); //启动前台线程
mHandler = new MainHandler(mHandlerThread.getLooper());
mUiHandler = mInjector.getUiHandler(this);//创建UI线程
mConstants = new ActivityManagerConstants(this, mHandler);
...
//创建前台广播接收器,设置10秒超时
mFgBroadcastQueue = new BroadcastQueue(this, mHandler,
"foreground", BROADCAST_FG_TIMEOUT, false);
//创建后台广播接收器,设置60秒超时
mBgBroadcastQueue = new BroadcastQueue(this, mHandler,
"background", BROADCAST_BG_TIMEOUT, true);
//放入广播接收器数组中
mBroadcastQueues[0] = mFgBroadcastQueue;
mBroadcastQueues[1] = mBgBroadcastQueue;
//[1.1] 创建活动服务
mServices = new ActiveServices(this);
mProviderMap = new ProviderMap(this);
mAppErrors = new AppErrors(mUiContext, this);
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"));
//CUP执行状况
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(); //更新CUP状态
} catch (Exception e) {
Slog.e(TAG, "Unexpected exception collecting process stats", e);
}
}
}
};
Watchdog.getInstance().addMonitor(this);
Watchdog.getInstance().addThread(mHandler);
}
[3] 启动AMS
private void start(){
//移除所有进程组
removeAllProcessGroups();
//启动Cpu进程
mProcessCpuThread.start();
//启动电池状态服务
mBatteryStatsService.publish();
mAppOpsService.publish(mContext);
//创建本地服务并注册,将创建的本地服务放入到本地服务集合完成注册
LocalServices.addService(ActivityManagerInternal.class, new LocalService());
// 等待在mProcessCpuThread中启动的同步块,
//以便从主线程获得对mProcessCpuTracker的任何其他访问
//将在mProcessCpuTracker初始化期间被阻塞。
try {
mProcessCpuInitLatch.await();
} catch (InterruptedException e) {
Slog.wtf(TAG, "Interrupted wait during start", e);
Thread.currentThread().interrupt();
throw new IllegalStateException("Interrupted wait during start");
}
}
[4]向ServiceManger中注册Binder服务 mActivityManagerService.setSystemProcess()
public void setSystemProcess() {
try {
//注册Activity Service
ServiceManager.addService(Context.ACTIVITY_SERVICE, this, true);
//注册进程状态服务
ServiceManager.addService(ProcessStats.SERVICE_NAME, mProcessStats);
//注册内存Binder
ServiceManager.addService("meminfo", new MemBinder(this));
//注册图像信息Binder
ServiceManager.addService("gfxinfo", new GraphicsBinder(this));
//注册SQLite DB binder
ServiceManager.addService("dbinfo", new DbBinder(this));
//注册监控CPU使用状况Binder
if (MONITOR_CPU_USAGE) {
ServiceManager.addService("cpuinfo", new CpuBinder(this));
}
//注册权限控制Binder
ServiceManager.addService("permission", new PermissionController(this));
//注册进程管理Binder
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 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);
}
}
网友评论