当前位置: 首页 > news >正文

Android ActivityManagerService总结(一)AMS启动

一. 概述

        ActivityManagerService是Android系统中一个特别重要的系统服务,也是我们上层APP打交道最多的系统服务之一。ActivityManagerService(以下简称AMS) 主要负责四大组件的启动、切换、调度以及应用进程的管理和调度工作。所有的APP应用都需要与AMS打交道.  符合C/S通信模式.

Client:由ActivityManager封装一部分服务接口供Client调用
Server:由ActivityManagerService实现,提供Server端的系统服务

二. AMS启动过程

AMS是在SystemServer进程中fork出来的, 所以先到SystemServer中查看初始化

    public static void main(String[] args) {new SystemServer().run();}

继续看run方法

private void run() {// Start services.try {traceBeginAndSlog("StartServices");//在startBootstrapServices()中去启动了AMSstartBootstrapServices();startCoreServices();startOtherServices();SystemServerInitThreadPool.shutdown();} catch (Throwable ex) {Slog.e("System", "******************************************");Slog.e("System", "************ Failure starting system services", ex);throw ex;} finally {traceEnd();}
}

调用startBootStrapServices()方法

 private void startBootstrapServices() {
.....   //启动AMSmActivityManagerService = ActivityManagerService.Lifecycle.startService(mSystemServiceManager, atm);// Set up the Application instance for the system process and get started.//为系统进程设置应用程序实例并开始操作traceBeginAndSlog("SetSystemProcess");mActivityManagerService.setSystemProcess();traceEnd();
....
}public static ActivityManagerService startService(SystemServiceManager ssm, ActivityTaskManagerService atm) {sAtm = atm;return 
//传入的是ActivityManagerService.Lifecycle.class对象
ssm.startService(ActivityManagerService.Lifecycle.class).getService();
}

AMS是通过SystemServiceManager.startService去启动的,参数是
ActivityManagerService.Lifecycle.class, 首先看看startService方法

public <T extends SystemService> T startService(Class<T> serviceClass) {....    final T service;try {//获取AMS.Lifecycle类中 带context参数的构造方法Constructor<T> constructor = serviceClass.getConstructor(Context.class);//通过构造器的newInstance方法//实际上就是 new一个 AMSEx对象 而 AMSEx 是继承 AMSservice = constructor.newInstance(mContext);....startService(service);return service;
}

用传入进来的ActivityManagerService.Lifecycle.class作为参数, 通过反射方式创建对应的service服务.  所以创建的是Lifecycle的实例, 然后通过startService来启动服务.

那AMS的 Lifecycle的实例是什么呢? 继续看源码,发现它是AMS中的一个静态内部类,并且继承于SystemService

public static final class Lifecycle extends SystemService {private final ActivityManagerService mService;private static ActivityTaskManagerService sAtm;public Lifecycle(Context context) {super(context);mService = new ActivityManagerServiceEx(context, sAtm);}
....}

在Lifecycle的构造方法中, 通过new 一个 AMSEx对象(AMSEx是继承AMS)赋值给mService 

实质上还是创建了AMS服务对象,然后通过 startService(service)方法启动AMS服务.

接着继续调用frameworks/base/services/core/java/com/android/server/SystemServiceManager.java中的

public void startService(@NonNull final SystemService service) {// Register it.mServices.add(service);// Start it.long time = SystemClock.elapsedRealtime();try {//走到这里,就执行到AMS中的onStart()方法了, 服务真正的启动起来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");}

在上面 new ActivityManagerServiceEx(context, sAtm)这句代码时, 先会执行AMS的构造方法

看看初始化的时候,做了什么事情

        // Set up the Application instance for the system process and get started.
        traceBeginAndSlog("SetSystemProcess");
        mActivityManagerService.setSystemProcess();
        traceEnd();

再看service.onStart()方法//走到这里,就执行到AMS中的onStart()方法了, 服务真正的启动起来

 private void start() {removeAllProcessGroups();mProcessCpuThread.start();mBatteryStatsService.publish();mAppOpsService.publish(mContext);Slog.d("AppOps", "AppOpsService published");LocalServices.addService(ActivityManagerInternal.class, new LocalService());mActivityTaskManager.onActivityManagerInternalAdded();mUgmInternal.onActivityManagerInternalAdded();mPendingIntentController.onActivityManagerInternalAdded();// Wait for the synchronized block started in mProcessCpuThread,// so that any other access to mProcessCpuTracker from main thread// will be blocked during mProcessCpuTracker initialization.try {
//等待mProcessCpuThread完成初始化后, 释放锁,初始化期间禁止访问mProcessCpuInitLatch.await();} catch (InterruptedException e) {Slog.wtf(TAG, "Interrupted wait during start", e);Thread.currentThread().interrupt();throw new IllegalStateException("Interrupted wait during start");}}

再回过头来看看在startBootstrapServices()方法中的

mActivityManagerService.setSystemProcess()
public void setSystemProcess() {try {ServiceManager.addService(Context.ACTIVITY_SERVICE, this, /* allowIsolated= */ true,DUMP_FLAG_PRIORITY_CRITICAL | DUMP_FLAG_PRIORITY_NORMAL | DUMP_FLAG_PROTO);ServiceManager.addService(ProcessStats.SERVICE_NAME, mProcessStats);ServiceManager.addService("meminfo", new MemBinder(this), /* allowIsolated= */ false,DUMP_FLAG_PRIORITY_HIGH);ServiceManager.addService("gfxinfo", new GraphicsBinder(this));ServiceManager.addService("dbinfo", new DbBinder(this));if (MONITOR_CPU_USAGE) {ServiceManager.addService("cpuinfo", new CpuBinder(this),/* allowIsolated= */ false, DUMP_FLAG_PRIORITY_CRITICAL);}ServiceManager.addService("permission", new PermissionController(this));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 = 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);mPidsSelfLocked.put(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);}

 看看这里面做的工作:

1. 注册服务。首先将ActivityManagerService注册到ServiceManager中,其次将几个与系统性能调试相关的服务(meminfo内存信息, cpuinfo CPU信息, permission 权限信息, processinfo进程信息等)注册到ServiceManager。

2. 查询并处理ApplicationInfo。首先调用PackageManagerService的接口,查询包名为android的应用程序的ApplicationInfo信息,对应于framework-res.apk。然后以该信息为参数调用ActivityThread上的installSystemApplicationInfo方法。

3. 创建并处理ProcessRecord。调用ActivityManagerService上的newProcessRecordLocked,创建一个ProcessRecord类型的对象,并保存该对象的信息。

三. 时序图

总结一下AMS启动时序图

 


 

http://www.xdnf.cn/news/809389.html

相关文章:

  • 智慧档案室一体化建设方案
  • Linux makefile详解
  • .NET Framework 3.5 SP1 最终文件下载及离线安装
  • 一站式Shell编程攻略:从入门到精通
  • java中用中国网建提供的SMS短信平台发送短信
  • 计算机网络基础知识(非常详细)从零基础入门到精通,看完这一篇就够了
  • 亚马逊开店详细教程(3)- 分配存款方式
  • Tomcat的webapps文件夹
  • FormulaR1C1是EXCEL中单元格公式输入方法
  • 40个在线杀毒网站
  • kb931125—rootsupd_kb931125-rootsupd补丁下载
  • 创业投资——IDG技术创业投资基金
  • JAVA安装教程
  • (转)FPE修改全教程1
  • VUE实现下一页的功能
  • java response.write_response.write()区别response.getWrite().write()
  • 简单卷、跨区卷、带区卷、镜像卷和 RAID-5 卷 区别
  • BitCome比特彗星v1.82豪华版(bt下载)
  • 外贸干货|最完整的外贸出口流程,收藏起来耐心看完!
  • 固态硬盘如何4K对齐?扇区大小,簇大小的影响_固态硬盘扇区
  • 自定义Android应用字体的完整指南
  • 香农编码,哈夫曼编码与费诺编码的比较
  • 嵌入式开发对学历门槛要求高吗?
  • X Window系统(X Window System,也常称为X11或X,天窗口系统)是一种以位图方式显示的软件窗口系统。
  • 一文读懂DDR内存基础知识|值得收藏
  • js中cloneNode()的使用 两个例子
  • API函数大全
  • 【收藏】法律人办案必备检索网站最新汇总!附检索技巧
  • JDK1.6到JDK1.8方法区的变化(大坑)
  • 字符串匹配-KMP算法(通俗易懂)