AMS主要用来管理应用程序的生命周期,以及其核心组件,包括Activity,Service,Provider,Broadcast,Task等
之前整体架构如下图(O上已经废弃)
新的架构比较直接,简化了很多,直接调用IApplicationThread和IActivityManger这两个接口就可以完成Client和Service端的binder通信
核心record是进程的,各个Record的关系如下图
AMS本身是system_server进程里的的一个服务,在类SystemServer里完成初始化,并为其所在的进程system_server创建Android运行时环境,即主线程ActivityThread和Context具体子类ContextImpl,来满足AMS的运行环境条件;完成AMS的初始化;并将其自身所在的system_server进程其纳入调度中;最后通知其他模块,AMS已经ready了
大体初始化流程如下:
1.
先是在SysemServer的run方法里,在启动任何服务之前,调用createSystemContext方法
270 private void run() {
………………………………
378 // Initialize the system context.
379 createSystemContext();
380
381 // Create the system service manager.
382 mSystemServiceManager = new SystemServiceManager(mSystemContext);
383 mSystemServiceManager.setRuntimeRestarted(mRuntimeRestart);
384 LocalServices.addService(SystemServiceManager.class, mSystemServiceManager);
385 // Prepare the thread pool for init tasks that can be parallelized
386 SystemServerInitThreadPool.get();
387 } finally {
388 traceEnd(); // InitBeforeStartServices
389 }
390
391 // Start services.
392 try {
393 traceBeginAndSlog("StartServices");
394 startBootstrapServices();
395 startCoreServices();
396 startOtherServices();
397 SystemServerInitThreadPool.shutdown();
………………………………
createSystemContext方法
先执行ActivityThread的systemMain方法,再通过获取的线程对象获取SystemContext和systemUiContext,并为其设置主题
475 private void createSystemContext() {
476 ActivityThread activityThread = ActivityThread.systemMain();
477 mSystemContext = activityThread.getSystemContext();
478 mSystemContext.setTheme(DEFAULT_SYSTEM_THEME);
479
480 final Context systemUiContext = activityThread.getSystemUiContext();
481 systemUiContext.setTheme(DEFAULT_SYSTEM_THEME);
482 }
systemMain方法
systemMain方法先判断是不是低端设备,低端设备不用gpu做硬件加速。最后new一个ActivityThread对象并attch当前进程到相应的Instrumentation,Application,Context对象
6444 public static ActivityThread systemMain() {
6445 // The system process on low-memory devices do not get to use hardware
6446 // accelerated drawing, since this can add too much overhead to the
6447 // process.
6448 if (!ActivityManager.isHighEndGfx()) {
6449 ThreadedRenderer.disable(true);
6450 } else {
6451 ThreadedRenderer.enableForegroundTrimming();
6452 }
6453 ActivityThread thread = new ActivityThread();
6454 thread.attach(true);
6455 return thread;
6456 }
attach方法
attach后AMS随后可以通过这个ActivityThread里的ApplicationThread对象接口来调度相应进程里程序组件的执行。
1 我们看看ActivityThread的attach函数:
2
3 //此时,我们传入的参数为true,表示该ActivityThread是系统进程的ActivityThread
4 private void attach(boolean system) {
5 //创建出的ActivityThread保存在类的静态变量sCurrentActivityThread
6 //AMS中的大量操作将会依赖于这个ActivityThread
7 sCurrentActivityThread = this;
8 mSystemThread = system;
9
10 if (!system) {
11 //应用进程的处理流程
12 ..........
13 } else {
14 //系统进程的处理流程,该情况只在SystemServer中处理
15
16 // Don't set application object here -- if the system crashes,
17 // we can't display an alert, we just want to die die die.
18 //设置DDMS(Dalvik Debug Monitor Service)中看到的SystemServer进程的名称为“system_process”
19 android.ddm.DdmHandleAppName.setAppName("system_process",
20 UserHandle.myUserId());
21
22 try {
23 //创建ActivityThread中的重要成员:Instrumentation、Application和Context
24 mInstrumentation = new Instrumentation();
25 ContextImpl context = ContextImpl.createAppContext(
26 this, getSystemContext().mPackageInfo);
27 mInitialApplication = context.mPackageInfo.makeApplication(true, null);
28 mInitialApplication.onCreate();
29 } catch (Exception e) {
30 throw new RuntimeException(
31 "Unable to instantiate Application():" + e.toString(), e);
32 }
33 }
34
35 //以下系统进程和非系统进程均会执行
36 ................
37 //注册Configuration变化的回调通知
38 ViewRootImpl.addConfigCallback(new ComponentCallbacks2() {
39 @Override
40 public void onConfigurationChanged(Configuration newConfig) {
41 //当系统配置发生变化时(例如系统语言发生变化),回调该接口
42 ...............
43 }
44 .............
45 });
46 }
Instrumentation类
因为要监控各个组件的执行情况,所以系统需要使用这个类来创建各个组件,并用来在应用和AMS之间做通信交流
Context类
包含了应用运行环境的全局信息,可以访问资源和相应组件,进而做启动Activity和发送Broadcast等操作
Application类
保存应用的全部状态。上边attach创建的Application对象对应framework-res.apk
关系类图
2.
ActivityManagerService内部静态类Lifecycle继承于SystemService
1 2668 public static final class Lifecycle extends SystemService {
在SystemServer.java里被注册到SystemServiceManager的startService里,调用ActivityManagerService构造方法。ActivityMangerService则通过getService返回并被配置
226 private ActivityManagerService mActivityManagerService;
511 // Activity manager runs the show.
512 traceBeginAndSlog("StartActivityManager");
513 mActivityManagerService = mSystemServiceManager.startService(
514 ActivityManagerService.Lifecycle.class).getService();
515 mActivityManagerService.setSystemServiceManager(mSystemServiceManager);
516 mActivityManagerService.setInstaller(installer);
517 traceEnd();
ActivityManagerService后续被用来
- init Power Manager
527 // Now that the power manager has been started, let the activity manager
528 // initialize power management features.
529 traceBeginAndSlog("InitPowerManagement");
530 mActivityManagerService.initPowerManagement();
531 traceEnd();
- set System Process
613 // Set up the Application instance for the system process and get started.
614 traceBeginAndSlog("SetSystemProcess");
615 mActivityManagerService.setSystemProcess();
616 traceEnd();
- set Usage Stats Manager
654 // Tracks application usage stats.
655 traceBeginAndSlog("StartUsageService");
656 mSystemServiceManager.startService(UsageStatsService.class);
657 mActivityManagerService.setUsageStatsManager(
658 LocalServices.getService(UsageStatsManagerInternal.class));
659 traceEnd();
- install System Provider
787 traceBeginAndSlog("InstallSystemProviders");
788 mActivityManagerService.installSystemProviders();
789 traceEnd();
- 配给watchdog
807 traceBeginAndSlog("InitWatchdog");
808 final Watchdog watchdog = Watchdog.getInstance();
809 watchdog.init(context, mActivityManagerService);
810 traceEnd();
- set Window Manager
842 traceBeginAndSlog("SetWindowManagerService");
843 mActivityManagerService.setWindowManager(wm);
844 traceEnd();
- 配给Network Policy Manager Service
1055 traceBeginAndSlog("StartNetworkPolicyManagerService");
1056 try {
1057 networkPolicy = new NetworkPolicyManagerService(context,
1058 mActivityManagerService, networkStats, networkManagement);
1059 ServiceManager.addService(Context.NETWORK_POLICY_SERVICE, networkPolicy);
1060 } catch (Throwable e) {
1061 reportWtf("starting NetworkPolicy Service", e);
1062 }
1063 traceEnd();
- safe mode下AMS进入safe mode
1513 if (safeMode) {
1514 traceBeginAndSlog("EnterSafeModeAndDisableJitCompilation");
1515 mActivityManagerService.enterSafeMode();
1516 // Disable the JIT for the system_server process
1517 VMRuntime.getRuntime().disableJitCompilation();
1518 traceEnd();
- safe mode下显示相应覆盖界面
1577
1578 if (safeMode) {
1579 mActivityManagerService.showSafeModeOverlay();
1580 }
- 配AMS的App Ops Service给Power Manager Service
1597 traceBeginAndSlog("MakePowerManagerServiceReady");
1598 try {
1599 // TODO: use boot phase
1600 mPowerManagerService.systemReady(mActivityManagerService.getAppOpsService());
1601 } catch (Throwable e) {
1602 reportWtf("making Power Manager Service ready", e);
1603 }
1604 traceEnd();
1605
- 调用AMS的systemReady告诉他可以运行第三方code了,并在真正启动初始程序前通过lambda回调返回到SystemServer,调用其startBootPhase的PHEASE_ACTIVITY_MANAGER_READY通知到各个Service继续初始化。最后AMS start Observing Native Crashes
1641 // We now tell the activity manager it is okay to run third party
1642 // code. It will call back into us once it has gotten to the state
1643 // where third party code can really run (but before it has actually
1644 // started launching the initial applications), for us to complete our
1645 // initialization.
1646 mActivityManagerService.systemReady(() -> {
1647 Slog.i(TAG, "Making services ready");
1648 traceBeginAndSlog("StartActivityManagerReadyPhase");
1649 mSystemServiceManager.startBootPhase(
1650 SystemService.PHASE_ACTIVITY_MANAGER_READY);
1651 traceEnd();
1652 traceBeginAndSlog("StartObservingNativeCrashes");
1653 try {
1654 mActivityManagerService.startObservingNativeCrashes();
1655 } catch (Throwable e) {
1656 reportWtf("observing native crashes", e);
1657 }
1658 traceEnd();
AMS里的handler
kill流程
杀进程的基础工具是framework/base/core/java/android/os/Process.java里的三个方法
流程图:
说明:
- Process.killProcess(int pid): 杀pid进程
- Process.killProcessQuiet(int pid):杀pid进程,且不输出log信息
- Process.killProcessGroup(int uid, int pid):杀同一个uid下同一进程组下的所有进程
AMS里ProcessRecord的kill方法会调用Process里的这三个方法
void kill(String reason, boolean noisy) {
if (!killedByAm) {
if (noisy) {
Slog.i(TAG, "Killing " + toShortString() + " (adj " + setAdj + "): " + reason);
}
//调用该方法,则会输出EventLog, 最后一个参数reason代表是通过何在方法触发kill
EventLog.writeEvent(EventLogTags.AM_KILL, userId, pid, processName, setAdj, reason);
Process.killProcessQuiet(pid);
Process.killProcessGroup(info.uid, pid);
if (!persistent) {
killed = true;
killedByAm = true;
}
}
}
除此之外,lmk也会直接在kernel里杀进程
createSystemContext