基于Android 10源码分析
AMS 简介
ActivityManagerService是Android系统中一个特别重要的系统服务,也是我们上层APP打交道最多的系 统服务之一。ActivityManagerService(以下简称AMS) 主要负责四大组件的启动、切换、调度以及应 用进程的管理和调度工作。所有的APP应用都需要 与AMS打交道
Activity Manager的组成主要分为以下几个部分:
- 服务代理:由ActivityManagerProxy实现,用于与Server端提供的系统服务进行进程间通信
- 服务中枢:ActivityManagerNative继承自Binder并实现IActivityManager,它提供了服务接口和 Binder接口的相互转化功能,并在内部存储服务代理对像,并提供了getDefault方法返回服务代理
- Client:由ActivityManager封装一部分服务接口供Client调用。ActivityManager内部通过调用 ActivityManagerNative的getDefault方法,可以得到一个ActivityManagerProxy对像的引用,进而通过 该代理对像调用远程服务的方法
- Server:由ActivityManagerService实现,提供Server端的系统服务
AMS 的启动流程
AMS 是在 system_service 进程中创建的,并运行在 system_service 进程中,所以我们先分析下system_service启动过程。
system_service如何创建的详细流程可以看下Android系统启动综述。这里只做简单回顾
上图是Zygote启动过程的核心流程图,我们的system_service进程就是在
startSystemServer()
启动的。
system_service进程启动之后的主要如下,详见下图
接下来我们进入我们的代码跟踪
system_service 启动初始化
system_service 是Zygote 第一个fork
创建的服务进程,他主要工作是负责创建和维护各种核心服务 如 AMS 、WMS、PKMS 等等Framework 层使用的最为频繁核心服务。
启动入口 SystemService.main()
public static void main(String[] args) {
new SystemServer().run();
}
private void run() {
TimingsTraceAndSlog t = new TimingsTraceAndSlog();
try {
t.traceBegin("InitBeforeStartServices");
// 省略代码
// binder 相关设置
// Within the system server, when parceling exceptions, include the stack trace
Parcel.setStackTraceParceling(true);
// Ensure binder calls into the system always run at foreground priority.
BinderInternal.disableBackgroundScheduling(true);
// Increase the number of binder threads in system_server
BinderInternal.setMaxThreads(sMaxBinderThreads);
// 准备主线程 looper
// Prepare the main looper thread (this thread).
android.os.Process.setThreadPriority(
android.os.Process.THREAD_PRIORITY_FOREGROUND);
android.os.Process.setCanSelfBackground(false);
Looper.prepareMainLooper();
Looper.getMainLooper().setSlowLogThresholdMs(
SLOW_DISPATCH_THRESHOLD_MS, SLOW_DELIVERY_THRESHOLD_MS);
// 省略代码
// 初始化 SystemContext
createSystemContext();
// 创建 SystemServiceManager
mSystemServiceManager = new SystemServiceManager(mSystemContext);
mSystemServiceManager.setStartInfo(mRuntimeRestart,
mRuntimeStartElapsedTime, mRuntimeStartUptime);
LocalServices.addService(SystemServiceManager.class, mSystemServiceManager);
// 准备线程池,用来处理服务的创建
SystemServerInitThreadPool.start();
} finally {
t.traceEnd(); // InitBeforeStartServices
}
// 开始启动服务
try {
t.traceBegin("StartServices");
startBootstrapServices(t);
startCoreServices(t);
startOtherServices(t);
} catch (Throwable ex) {
throw ex;
} finally {
t.traceEnd(); // StartServices
}
// Loop forever.
Looper.loop();
throw new RuntimeException("Main thread loop unexpectedly exited");
}
复制代码
- SystemServer.main 初始化SystemServer对象,再调用对象的run()方法
- SystemServer.run
- createSystemContext
- startBootstrapServices 启动引导服务
- startCoreServices 启动核心服务
- startOtherServices 启动其他服务
- Looper.loop 进入loop循环
- SystemServer.run
SystemService.createSystemContext()
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);
}
复制代码
- ActivityThread.systemMain() 创建系统线程
- mSystemContext.setTheme 设置系统主题
ActivityThread.systemMain()
public static ActivityThread systemMain() {
if (!ActivityManager.isHighEndGfx()) {
ThreadedRenderer.disable(true);
} else {
ThreadedRenderer.enableForegroundTrimming();
}
ActivityThread thread = new ActivityThread();
thread.attach(true, 0);
return thread;
}
复制代码
-
new ActivityThread()
-
-
创建ApplicationThread对象
-
创建H (
class H extends Handler
) 对象,这时候mH的Looper 已经在SystemService.run()
准备就绪 -
mInitialApplication的赋值
-
- system_server进程是由ActivityThread.attach()过程赋值
- 普通app进程是由是由ActivityThread.handleBindApplication()过程赋值
-
ResourcesManager.getInstance() 获取资料管理实例
-
-
thread.attach(true, 0)
@UnsupportedAppUsage private void attach(boolean system, long startSeq) { sCurrentActivityThread = this; mSystemThread = system; if (!system) { // 不回执行这里 } else { try { //创建Instrumentation mInstrumentation = new Instrumentation(); mInstrumentation.basicInit(this); //1.先执行getSystemContext() 创建单例 mSystemContext //2.创建appContext ContextImpl context = ContextImpl.createAppContext( this, getSystemContext().mPackageInfo); //创建 Application 实例 mInitialApplication = context.mPackageInfo.makeApplication(true, null); //调用 Application onCreate mInitialApplication.onCreate(); } catch (Exception e) { //... } } //... } 复制代码
- 创建Instrumentation
- ContextImpl.createAppContext
- activityThread.getSystemContext
- ContextImpl.createSystemContext 单例模式创建mSystemContext对象
- 创建LoadedApk对象
- 创建ApplicationInfo对象
- 创建ClassLoader
- 创建ContextImpl
- 首次执行getSystemContext,会创建LoadedApk和contextImpl对象,接下来利用刚创建的LoadedApk对象来创建新的ContextImpl对象
- 创建LoadedApk对象
- ContextImpl.createSystemContext 单例模式创建mSystemContext对象
- activityThread.getSystemContext
- makeApplication
- initializeJavaContextClassLoader 设置当前线程的Context ClassLoader
- newApplication
- instantiateApplication 创建Application对象
- 将新创建的ContextImpl对象保存到Application的父类成员变量mBase
- 将新创建的LoadedApk对象保存到Application的父员变量mLoadedApk
- instantiateApplication 创建Application对象
- mInitialApplication.onCreate()
AMS启动过程
接着上面讲的system_service进程启动过程,下面进入AMS服务的启动.
SystemServer.startBootstrapServices()
启动我们的引导服务,我们的AMS就在这里启动。
private void startBootstrapServices(@NonNull TimingsTraceAndSlog t) {
// 尽早的启动Watchdog看门狗,当在启动过程中发生deadlock的时候可以让系统服务奔溃
final Watchdog watchdog = Watchdog.getInstance();
watchdog.start();
//...
// 启动安装服务
Installer installer = mSystemServiceManager.startService(Installer.class);
//...
//启动ATMS,比6.0的源码多出来跟ASM相关的服务。
//主要是将之前AMS 里面 Activity 相关的逻辑抽离,主要负责Activity管理和调度等工作
ActivityTaskManagerService atm = mSystemServiceManager.startService(
ActivityTaskManagerService.Lifecycle.class).getService();
//启动AMS 负责管理四大组件和进程,包括生命周期和状态切换。
mActivityManagerService = ActivityManagerService.Lifecycle.startService(
mSystemServiceManager, atm);
//设置mSystemServiceManager
mActivityManagerService.setSystemServiceManager(mSystemServiceManager);
//设置installer
mActivityManagerService.setInstaller(installer);
//...
//初始化AMS 相关的PMS, 必须在 PMS服务启动之后调用
mActivityManagerService.initPowerManagement();
//设置ApplicationInfo
mActivityManagerService.setSystemProcess();
//看门狗开始监听 AMS 服务,发现异常就会重启AMS
// 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
watchdog.init(mSystemContext, mActivityManagerService);
}
复制代码
- 开启Watchdog 看门狗
- 启动Installer安装服务
- mSystemServiceManager.startService 启动ATMS
- ActivityManagerService.Lifecycle.startService 启动AMS
- mActivityManagerService.setInstaller 设置AMS的APP安装器
- mActivityManagerService.initPowerManagement 初始化AMS相关的PMS
- mActivityManagerService.setSystemProcess 设置SystemServer
- watchdog.init 看门狗开始监听 AMS 服务,发现异常就会重启AMS
SystemServiceManager.startService 启动服务
ATMS 和 AMS 都会通过 mSystemServiceManager.startService启动。
public <T extends SystemService> T startService(Class<T> serviceClass) {
try {
//...
final T service;
try {
//通过反射创建构建Service 实例
Constructor<T> constructor = serviceClass.getConstructor(Context.class);
service = constructor.newInstance(mContext);
} catch (InstantiationException ex) {
//...
} catch (IllegalAccessException ex) {
//...
} catch (NoSuchMethodException ex) {
//...
} catch (InvocationTargetException ex) {
//...
}
startService(service);
return service;
} finally {
//...
}
}
public void startService(@NonNull final SystemService service) {
//实例缓存到mServices容器
mServices.add(service);
try {
//调用服务的onStart方法
service.onStart();
} catch (RuntimeException ex) {
//...
}
}
复制代码
这里要注意的是ActivityTaskManagerService.Lifecycle
和 ActivityManagerService.Lifecycle
都是 SystemService
的子类 他们都实现了onStart的方法。所以service.onStart()
分别调用的是对应重载的onStart
方法。
这里核心流程是创建service实例,然后start 服务
-
创建ActivityTaskManagerService实例
@VisibleForTesting(visibility = VisibleForTesting.Visibility.PACKAGE) public ActivityTaskManagerService(Context context) { mContext = context; mFactoryTest = FactoryTest.getMode(); //系统线程 mSystemThread = ActivityThread.currentActivityThread(); mUiContext = mSystemThread.getSystemUiContext(); //创建生命周期管理 mLifecycleManager = new ClientLifecycleManager(); //创建ActivityTaskManagerInternal 实例 mInternal = new LocalService(); //... } 复制代码
LocalService 继承自 ActivityTaskManagerInternal
-
ActivityTaskManagerService.Lifecycle.onStart()
public void onStart() { //将ActivityTaskManagerService 服务添加到ServiceManager(Binder 大管家中) publishBinderService(Context.ACTIVITY_TASK_SERVICE, mService); //启动服务 mService.start(); } 复制代码
-
ActivityTaskManagerService.onStart()
private void start() { // 将 ActivityTaskManagerInternal 添加到 system_service进程中 的全局容器中 ,方便该进程通过LocalServices 来获取service实例 LocalServices.addService(ActivityTaskManagerInternal.class, mInternal); } 复制代码
-
-
创建ActivityManagerService实例
-
ActivityManagerService.Lifecycle.onStart()
最终掉ActivityManagerService.start()
private void start() { //移除所有的进程组 removeAllProcessGroups(); //启动CpuTracker线程 mProcessCpuThread.start(); //启动电池统计服务 mBatteryStatsService.publish(); mAppOpsService.publish(); //ActivityManagerInternal实例添加到LocalServices中,进程共享 LocalServices.addService(ActivityManagerInternal.class, mInternal); //通知 ActivityTaskManagerService 可以获取 ActivityManagerInternal实例 mActivityTaskManager.onActivityManagerInternalAdded(); mPendingIntentController.onActivityManagerInternalAdded(); try { mProcessCpuInitLatch.await(); } catch (InterruptedException e) { //... } } 复制代码
ActivityManagerService.setSystemProcess
public void setSystemProcess() {
try {
//将AMS 服务添加到ServiceManager(Binder 大管家)
ServiceManager.addService(Context.ACTIVITY_SERVICE, this, /* allowIsolated= */ true,
DUMP_FLAG_PRIORITY_CRITICAL | DUMP_FLAG_PRIORITY_NORMAL | DUMP_FLAG_PROTO);
//省略代码, 这里有一些 binder 实例 或 服务添加到ServiceManager 代码 MemBinder GraphicsBinder DbBinder CacheBinder CpuBinder 等
// 创建 ApplicationInfo
ApplicationInfo info = mContext.getPackageManager().getApplicationInfo(
"android", STOCK_PM_FLAGS | MATCH_SYSTEM_ONLY);
//初始化 ApplicationInfo
mSystemThread.installSystemApplicationInfo(info, getClass().getClassLoader());
//创建ProcessRecord对象
synchronized (this) {
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);
addPidLocked(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);
}
//...
}
复制代码
- 注册服务。首先将ActivityManagerService注册到ServiceManager中,其次将几个与系统性能调试相关 的服务注册到ServiceManager。
- 查询并处理ApplicationInfo。首先调用PackageManagerService的接口,查询包名为android的应用程 序的ApplicationInfo信息,对应于framework-res.apk。然后以该信息为参数调用ActivityThread上的 installSystemApplicationInfo方法。
- 创建并处理ProcessRecord。调用ActivityManagerService上的newProcessRecordLocked,创建一个 ProcessRecord类型的对象,并保存该对象的信息
SystemServer.startOtherServices()
private void startOtherServices(@NonNull TimingsTraceAndSlog t) {
//....
try {
//....
//设置WMS管理
mActivityManagerService.setWindowManager(wm);
//安装系统Provider
//创建核心Settings Observer,用于监控Settings的改变
mActivityManagerService.installSystemProviders();
//....
} catch (Throwable e) {
//....
}
//....
//调用 AMS systemReady
mActivityManagerService.systemReady(() -> {
mSystemServiceManager.startBootPhase(t, SystemService.PHASE_ACTIVITY_MANAGER_READY);
//...
try {
//startSystemUi 启动系统UI
startSystemUi(context, windowManagerF);
} catch (Throwable e) {
//...
}
//... 执行一系列服务的systemReady 和 systemRunning
mSystemServiceManager.startBootPhase(t, SystemService.PHASE_THIRD_PARTY_APPS_CAN_START);
}, t);
}
复制代码
-
mActivityManagerService.setWindowManager设置WMS管理
-
mActivityManagerService.installSystemProviders 安装系统Provider;创建核心Settings Observer,用于监控Settings的改变
-
mActivityManagerService.systemReady 通知AMS 系统准备就绪
-
通知AMS 相关联的内部服务 系统服务准备就绪
-
startSystemUi 启动系统UI
-
mSystemServiceManager.startBootPhase 通知
mSystemServiceManager.mServices
所有serviceonBootPhase
回调public void startBootPhase(@NonNull TimingsTraceAndSlog t, int phase) { if (phase <= mCurrentPhase) { throw new IllegalArgumentException("Next phase must be larger than previous"); } mCurrentPhase = phase; try { final int serviceLen = mServices.size(); for (int i = 0; i < serviceLen; i++) { final SystemService service = mServices.get(i); try { service.onBootPhase(mCurrentPhase); } catch (Exception ex) { //... } } } finally { t.traceEnd(); } } 复制代码
-
AMS.Lifecycle.onBootPhase 通知AMS 状态变化
public void onBootPhase(int phase) { mService.mBootPhase = phase; if (phase == PHASE_SYSTEM_SERVICES_READY) { mService.mBatteryStatsService.systemServicesReady(); mService.mServices.systemServicesReady(); } else if (phase == PHASE_ACTIVITY_MANAGER_READY) { mService.startBroadcastObservers(); } else if (phase == PHASE_THIRD_PARTY_APPS_CAN_START) { mService.mPackageWatchdog.onPackagesReady(); } } 复制代码
-
-
小结
system_server进程,从源码角度划分为引导服务、核心服务、其他服务3类。
- 引导服务(7个):ActivityManagerService、PowerManagerService、LightsService、DisplayManagerService、PackageManagerService、UserManagerService、SensorService;
- 核心服务(3个):BatteryService、UsageStatsService、WebViewUpdateService;
- 其他服务(70个+):AlarmManagerService、VibratorService等。
服务的启动SystemServiceManager.startService:
- 功能:
- 创建服务对象;
- 执行该服务的onStart()方法;该方法会执行上面的SM.addService();
- 根据启动到不同的阶段会回调onBootPhase()方法;
- 另外,还有多用户模式下用户状态的改变也会有回调方法;例如onStartUser();
- 特点:服务往往自身或内部类继承于SystemService;
AMS小结
AMS 属于系统服务中的引导服务,运行在system_service 进程中。跟很多其他服务有着比较密切的交互。
在AMS的启动过程中,AMS服务会将自己的服务注册到ServiceManager中,从而支持跨进程的Binder通信;
在system_service进程中,可以通过引用或者LocalServices服务容器获取对应服务进行交互
- SystemServiceManager 中mServices 容器缓存了所有通过 SystemServiceManager启动的服务
- LocalServices 缓存了各服务的内部实现LocalService 如
LocalService extends ActivityManagerInternal
这些定义在服务的内部类,其他进程可以同过LocalServices.getService()
获取实例