【8.0.0_r4】AMS架构与流程分析

守給你的承諾、 提交于 2020-01-08 04:18:16

 

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方法

 1 270    private void run() {
 2 ………………………………
 3 378            // Initialize the system context.
 4 379            createSystemContext();
 5 380
 6 381            // Create the system service manager.
 7 382            mSystemServiceManager = new SystemServiceManager(mSystemContext);
 8 383            mSystemServiceManager.setRuntimeRestarted(mRuntimeRestart);
 9 384            LocalServices.addService(SystemServiceManager.class, mSystemServiceManager);
10 385            // Prepare the thread pool for init tasks that can be parallelized
11 386            SystemServerInitThreadPool.get();
12 387        } finally {
13 388            traceEnd();  // InitBeforeStartServices
14 389        }
15 390
16 391        // Start services.
17 392        try {
18 393            traceBeginAndSlog("StartServices");
19 394            startBootstrapServices();
20 395            startCoreServices();
21 396            startOtherServices();
22 397            SystemServerInitThreadPool.shutdown();
23 ………………………………

createSystemContext方法

先执行ActivityThread的systemMain方法,再通过获取的线程对象获取SystemContext和systemUiContext,并为其设置主题

1 475    private void createSystemContext() {
2 476        ActivityThread activityThread = ActivityThread.systemMain();
3 477        mSystemContext = activityThread.getSystemContext();
4 478        mSystemContext.setTheme(DEFAULT_SYSTEM_THEME);
5 479
6 480        final Context systemUiContext = activityThread.getSystemUiContext();
7 481        systemUiContext.setTheme(DEFAULT_SYSTEM_THEME);
8 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  1 我们看看ActivityThread的attach函数:
 2  2 
 3  3 //此时,我们传入的参数为true,表示该ActivityThread是系统进程的ActivityThread
 4  4 private void attach(boolean system) {
 5  5     //创建出的ActivityThread保存在类的静态变量sCurrentActivityThread
 6  6     //AMS中的大量操作将会依赖于这个ActivityThread
 7  7     sCurrentActivityThread = this;
 8  8     mSystemThread = system;
 9  9 
10 10     if (!system) {
11 11         //应用进程的处理流程
12 12         ..........
13 13     } else { 
14 14         //系统进程的处理流程,该情况只在SystemServer中处理
15 15 
16 16         // Don't set application object here -- if the system crashes,
17 17         // we can't display an alert, we just want to die die die.
18 18         //设置DDMS(Dalvik Debug Monitor Service)中看到的SystemServer进程的名称为“system_process”
19 19         android.ddm.DdmHandleAppName.setAppName("system_process",
20 20                 UserHandle.myUserId());
21 21 
22 22         try {
23 23             //创建ActivityThread中的重要成员:Instrumentation、Application和Context
24 24             mInstrumentation = new Instrumentation();
25 25             ContextImpl context = ContextImpl.createAppContext(
26 26                         this, getSystemContext().mPackageInfo);
27 27             mInitialApplication = context.mPackageInfo.makeApplication(true, null);
28 28             mInitialApplication.onCreate();
29 29         } catch (Exception e) {
30 30             throw new RuntimeException(
31 31                     "Unable to instantiate Application():" + e.toString(), e);
32 32         }
33 33     }
34 34 
35 35     //以下系统进程和非系统进程均会执行
36 36     ................
37 37     //注册Configuration变化的回调通知
38 38     ViewRootImpl.addConfigCallback(new ComponentCallbacks2() {
39 39         @Override
40 40         public void onConfigurationChanged(Configuration newConfig) {
41 41             //当系统配置发生变化时(例如系统语言发生变化),回调该接口
42 42             ...............
43 43         }
44 44         .............
45 45     });
46 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返回并被配置

1 226    private ActivityManagerService mActivityManagerService;
1 511        // Activity manager runs the show.
2 512        traceBeginAndSlog("StartActivityManager");
3 513        mActivityManagerService = mSystemServiceManager.startService(
4 514                ActivityManagerService.Lifecycle.class).getService();
5 515        mActivityManagerService.setSystemServiceManager(mSystemServiceManager);
6 516        mActivityManagerService.setInstaller(installer);
7 517        traceEnd();

 

ActivityManagerService后续被用来

 

  • init Power Manager
1 527        // Now that the power manager has been started, let the activity manager
2 528        // initialize power management features.
3 529        traceBeginAndSlog("InitPowerManagement");
4 530        mActivityManagerService.initPowerManagement();
5 531        traceEnd();

 

  • set System Process
1 613        // Set up the Application instance for the system process and get started.
2 614        traceBeginAndSlog("SetSystemProcess");
3 615        mActivityManagerService.setSystemProcess();
4 616        traceEnd();

 

  • set Usage Stats Manager
1 654        // Tracks application usage stats.
2 655        traceBeginAndSlog("StartUsageService");
3 656        mSystemServiceManager.startService(UsageStatsService.class);
4 657        mActivityManagerService.setUsageStatsManager(
5 658                LocalServices.getService(UsageStatsManagerInternal.class));
6 659        traceEnd();

 

  • install System Provider
1 787            traceBeginAndSlog("InstallSystemProviders");
2 788            mActivityManagerService.installSystemProviders();
3 789            traceEnd();

 

  • 配给watchdog
1 807            traceBeginAndSlog("InitWatchdog");
2 808            final Watchdog watchdog = Watchdog.getInstance();
3 809            watchdog.init(context, mActivityManagerService);
4 810            traceEnd();

 

  • set Window Manager
1 842            traceBeginAndSlog("SetWindowManagerService");
2 843            mActivityManagerService.setWindowManager(wm);
3 844            traceEnd();

 

  • 配给Network Policy Manager Service
1 1055                traceBeginAndSlog("StartNetworkPolicyManagerService");
2 1056                try {
3 1057                    networkPolicy = new NetworkPolicyManagerService(context,
4 1058                            mActivityManagerService, networkStats, networkManagement);
5 1059                    ServiceManager.addService(Context.NETWORK_POLICY_SERVICE, networkPolicy);
6 1060                } catch (Throwable e) {
7 1061                    reportWtf("starting NetworkPolicy Service", e);
8 1062                }
9 1063                traceEnd();

 

  • safe mode下AMS进入safe mode
1 1513        if (safeMode) {
2 1514            traceBeginAndSlog("EnterSafeModeAndDisableJitCompilation");
3 1515            mActivityManagerService.enterSafeMode();
4 1516            // Disable the JIT for the system_server process
5 1517            VMRuntime.getRuntime().disableJitCompilation();
6 1518            traceEnd();

 

  • safe mode下显示相应覆盖界面
1 1577
2 1578        if (safeMode) {
3 1579            mActivityManagerService.showSafeModeOverlay();
4 1580        }

 

  • 配AMS的App Ops Service给Power Manager Service
1 1597        traceBeginAndSlog("MakePowerManagerServiceReady");
2 1598        try {
3 1599            // TODO: use boot phase
4 1600            mPowerManagerService.systemReady(mActivityManagerService.getAppOpsService());
5 1601        } catch (Throwable e) {
6 1602            reportWtf("making Power Manager Service ready", e);
7 1603        }
8 1604        traceEnd();
9 1605

 

  • 调用AMS的systemReady告诉他可以运行第三方code了,并在真正启动初始程序前通过lambda回调返回到SystemServer,调用其startBootPhase的PHEASE_ACTIVITY_MANAGER_READY通知到各个Service继续初始化。最后AMS start Observing Native Crashes
 1 1641        // We now tell the activity manager it is okay to run third party
 2 1642        // code.  It will call back into us once it has gotten to the state
 3 1643        // where third party code can really run (but before it has actually
 4 1644        // started launching the initial applications), for us to complete our
 5 1645        // initialization.
 6 1646        mActivityManagerService.systemReady(() -> {
 7 1647            Slog.i(TAG, "Making services ready");
 8 1648            traceBeginAndSlog("StartActivityManagerReadyPhase");
 9 1649            mSystemServiceManager.startBootPhase(
10 1650                    SystemService.PHASE_ACTIVITY_MANAGER_READY);
11 1651            traceEnd();
12 1652            traceBeginAndSlog("StartObservingNativeCrashes");
13 1653            try {
14 1654                mActivityManagerService.startObservingNativeCrashes();
15 1655            } catch (Throwable e) {
16 1656                reportWtf("observing native crashes", e);
17 1657            }
18 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里的这三个方法

 1 void kill(String reason, boolean noisy) {
 2     if (!killedByAm) {
 3         if (noisy) {
 4             Slog.i(TAG, "Killing " + toShortString() + " (adj " + setAdj + "): " + reason);
 5         }
 6         //调用该方法,则会输出EventLog, 最后一个参数reason代表是通过何在方法触发kill
 7         EventLog.writeEvent(EventLogTags.AM_KILL, userId, pid, processName, setAdj, reason);
 8         Process.killProcessQuiet(pid);
 9         Process.killProcessGroup(info.uid, pid);
10         if (!persistent) {
11             killed = true;
12             killedByAm = true;
13         }
14     }
15 }

 

 除此之外,lmk也会直接在kernel里杀进程

 

 

 

 

 

 

 

 

 

 

 createSystemContext
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!