目录
  1. 1. 简介
  2. 2. AMS 相关类介绍
    1. 2.1. ProcessRecord
      1. 2.1.1. 数据结构
        1. 2.1.1.1. 第一类数据:描述身份
        2. 2.1.1.2. 第二类数据:描述进程中的组件
        3. 2.1.1.3. 第三类数据:描述进程状态
        4. 2.1.1.4. 第四类数据:描述进程的共享内存
        5. 2.1.1.5. 第五类数据:描述进程的时间
        6. 2.1.1.6. 第六类数据:描述 Crash、ANR
        7. 2.1.1.7. 第七类数据:和 Instrumentation 相关的数据
        8. 2.1.1.8. 第八类数据:电源信息和调试信息
        9. 2.1.1.9. 第九类数据:其他
    2. 2.2. 容器
      1. 2.2.1. ProcessRecord容器
        1. 2.2.1.1. 永久性容器
        2. 2.2.1.2. 临时性容器
        3. 2.2.1.3. 特殊容器
      2. 2.2.2. 组件记录表容器
        1. 2.2.2.1. activity 记录
        2. 2.2.2.2. service 记录
        3. 2.2.2.3. BroadcastReceive 记录
        4. 2.2.2.4. ContentProvider 记录
  3. 3. Activity 管理相关类介绍
    1. 3.1. ActivityRecord
    2. 3.2. TaskRecord
    3. 3.3. ActivityStarter
    4. 3.4. ActivityStack
    5. 3.5. ActivityStackSupervisor
  4. 4. Activity 启动过程
    1. 4.1. Launcher 请求 AMS 阶段
    2. 4.2. AMS到ApplicationThread阶段
    3. 4.3. ApplicationThread到Activity阶段
  5. 5. ActivityManagerService 启动过程
    1. 5.1. SystemServer
    2. 5.2. startBootstrapServices
    3. 5.3. startService
    4. 5.4. ActivityManagerService.Lifecycle
    5. 5.5. AMS Constructor
    6. 5.6. ActivityManagerService.Lifecycle.start
    7. 5.7. setSystemProcess
    8. 5.8. 总结
重拾Android-【吃透源码系列】之AMS

ActivityManagerService 是 Android 系统中一个非常重要的系统服务,也是上层APP打交道最多的系统服务之一。ActivityManagerService(以下简称 AMS)主要负责四大组件的启动、切换、调度以及应用进程的管理和调度工作。

简介

Activity Manager 的组成主要分为以下几部分:

1、服务代理:由 ActivityManagerProxy 实现,用于与Server端提供的系统服务进行进程间通信。

2、服务中枢:ActivityManagerNative 继承自 Binder 并实现 ActivityManager,它提供了服务接口和 Binder 接口的相互转化功能,并在内部存储服务代理对象,并提供了 getDefault 方法返回服务代理。

3、Client:由 ActivityManager 封装一部分服务接口供 Client 使用。ActivityManager 内部通过调用 ActivityManagerNative 的 getDefault 方法,可以得到一个 ActivityManagerProxy 对象的引用,进而通过该代理对象调用远程服务的方法。

4、Server:由 ActivityManagerService 实现,提供 Server 端系统服务。

AMS 是什么?

从 Java 角度看,AMS 就是一个 Java 对象,实现了 IBinder 接口,所以它是一个用于进程之间通信的接口,这个对象初始化是在 SystemServer.java 的 run() 方法里,创建 SystemServiceManager 管理类,并传入服务名(ActivityManagerService.Lifecycle.class)参数,通过反射开启服务 startService() 。

   public Lifecycle(Context context) {
       super(context);
       mService = new ActivityManagerService(context);
   }

AMS 是一个服务,用来管理 Activity,并且是一个系统级服务,执掌 包管理服务电池管理服务震动管理服务等等

AMS 是一个 Binder,实现了 IBinder 接口,意味着不但可以用于进程间通信,还是一个线程,因为 Binder 就是一个线程。

如果启动一个最简单的 Hello World 应用程序,不另外启动其他线程,那么 APP 启动后至少要启动四个线程:

1、main 线程:程序的主线程,也叫UI线程,因为 Android 的组件是非线程安全的,所以只允许 UI/MAIN 线程来操作

2、GC 线程:JVM中的垃圾回收机制,每个 Java 程序均有各自的专门负责垃圾回收的线程

3、Binder1 线程:即 ApplicationThread,该类实现 IBinder 接口,用于进程之间通信,具体来说,就是应用程序和 AMS 通信的工具

4、Binder2 线程:即 ViewRoot.W 对象,它继承 IWindow.Stub,实现了 IBinder 接口,具体来说,就是应用程序和 WMS 通信的工具

public class ActivityManagerService extends IActivityManager.Stub
        implements Watchdog.Monitor, BatteryStatsImpl.BatteryCallback {   
}

AMS 相关类介绍

ProcessRecord

ProcessRecord 进程记录表:Android 系统中用于描述进程的数据结构对象。
官方注解:

 /**
  * Full information about a particular process that
  * is currently running.
  */

数据结构

第一类数据:描述身份

  • 1.ApplicationInfo info: AndroidManifest.xml中定义的Application信息

  • 2.boolean isolated: 是不是isolated进程

  • 3.int uid: 进程uid

  • 4.int userId: android做的多用户系统id

  • 5.String processName: 进程名字,默认情况下是包名

  • 6.UidRecord uidRecord: 记录已经使用的uid

  • 7.IApplicationThread thread: 这个很重要,它是ApplicationThread的客户端,AMS就是通过这个对象给apk进程发送异步消息的(管理四大组件的消息),

  • 8.int pid: 进程的pid

  • 9.String procStatFile: proc目录下每一个进程都有一个以pid命名的目录文件,这个目录下记载着进程的详细信息,这个目录及目录下的文件是内核创建的, proc是内核文件系统,proc就是process的缩写,涉及的目的就是导出进程内核信息

  • 10.int[] gids: 该进程启动时使用的gids

  • 11.CompatibilityInfo compat: 兼容性信息

  • 12.String requiredAbi: abi信息

  • 13.String instructionSet: 指令集信息

第二类数据:描述进程中的组件

  • 1.pkgList: 进程中运行的包

  • 2.ArraySet pkgDeps: 进程运行依赖的包

  • 3.ArrayList activities: 进程启动的所有 Activity 组件记录表

  • 4.ArraySet services: 进程启动的所有 Service 组件记录表

  • 5.ArraySet executingServices: 官方注解:services that are currently executing code (need to remain foreground).

【正在运行(executing)定义:系统控制组件通过发送消息给 apk 进程,apk 进程处理消息,上报消息完成。这被定义为一个完成的执行过程,因此这里定义的是发送消息到上报完成这段时间

  • 6.ArraySet connections: 绑定 Service 的客户端记录表

  • 7.ArraySet receivers: 进程启动的所有 Broadcast 组件记录表

  • 8.ContentProviderRecord pubProviders: 发布的 ContentProvider 组件记录对象。

【ContentProvider 需要安装(apk 进程加载 ContentProvider 子类、初始化、创建数据库等操作)然后把自己发布(将自己的 binder 客户端端注册到 AMS 中)到系统 AMS 中后,才可使用。】

  • 9.ArrayList conProviders: 使用 ContentProvider 的客户端记录表

  • 10.BroadcastRecord curReceiver: 当前进程正在执行的广播

第三类数据:描述进程状态

(下面不翻译,直接看官方注释)

  • 1.int maxAdj: // Maximum OOM adjustment for this process(为当前进程最大 OOM 调节数值)

  • 2.int curRawAdj: // Current OOM unlimited adjustment for this process

  • 3.int setRawAdj: // Last set OOM unlimited adjustment for this process

  • 4.int curAdj: // Current OOM adjustment for this process

  • 5.int setAdj: // Last set OOM adjustment for this process

  • 6.int verifiedAdj: // The last adjustment that was verified as actually being set

  • 7.int curSchedGroup: // Currently desired scheduling class

  • 8.int setSchedGroup: // Last set to background scheduling class

  • 9.int curProcState = PROCESS_STATE_NONEXISTENT: // Currently computed process state

  • 10.int repProcState = PROCESS_STATE_NONEXISTENT: // Last reported process state

  • 11.int setProcState = PROCESS_STATE_NONEXISTENT: // Last set process state in process tracker

  • 12.int pssProcState = PROCESS_STATE_NONEXISTENT: // Currently requesting pss for

  • 13.ProcessState baseProcessTracker: 进程状态检测器

  • 14.int adjSeq: // Sequence id for identifying oom_adj assignment cycles

  • 15.int lruSeq: // Sequence id for identifying LRU update cycles

  • 16.IBinder forcingToForeground: 强制将进程的状态设置为前台运行的IBinder,IBinder代表的是组件的ID,这个是整个android系统唯一【Android 9.0源码 Deprecated】

第四类数据:描述进程的共享内存

VSS- Virtual Set Size 虚拟耗用内存(包含共享库占用的内存)

RSS- Resident Set Size 实际使用物理内存(包含共享库占用的内存)

PSS- Proportional Set Size 实际使用的物理内存(比例分配共享库占用的内存)

USS- Unique Set Size 进程独自占用的物理内存(不包含共享库占用的内存)

一般来说内存占用大小有如下规律:VSS >= RSS >= PSS >= USS

  • 1.long initialIdlePss: // Initial memory pss of process for idle maintenance.【初始化空闲维护的进程的 PSS 】

  • 2.long lastPss: // Last computed memory pss.

  • 3.long lastSwapPss: // Last computed SwapPss.

  • 4.long lastCachedPss: // Last computed pss when in cached state.

  • 5.long lastCachedSwapPss: // Last computed SwapPss when in cached state.

第五类数据:描述进程的时间

  • 1.long lastActivityTime: // For managing the LRU list.【上次使用时间:用于管理LRU列表】

  • 2.long lastPssTime: // Last time we retrieved PSS data

  • 3.long nextPssTime: // Next time we want to request PSS data

  • 4.long lastStateTime: // Last time setProcState changed

  • 5.long lastWakeTime: 持有wakelock的时长【Android 9.0源码 Deprecated】

  • 6.long lastCpuTime // How long proc has run CPU at last check

  • 7.long curCpuTime: // How long proc has run CPU most recently

  • 8.long lastRequestedGc: // When we last asked the app to do a gc

  • 9.long lastLowMemory: // When we last told the app that memory is low

  • 10.long lastProviderTime: // The last time someone else was using a provider in this process.

  • 11.long interactionEventTime: // The time we sent the last interaction event

  • 12.long fgInteractionTime: // When we became foreground for interaction purposes

第六类数据:描述 Crash、ANR

  • 1.IBinder.DeathRecipient deathRecipient: // Who is watching for the death.【apk进程退出运行的话,会触发这个对象的binderDied()方法,来回收系统资源】

  • 2.boolean crashing: // are we in the process of crashing?【进程是否已经 crash】

  • 3.Dialog crashDialog: // dialog being displayed due to crash.【crash对话框】

  • 4.boolean forceCrashReport: // suppress normal auto-dismiss of crash dialog & report UI?【强制crash对话框显示】

  • 5.boolean notResponding: // does the app have a not responding dialog?【是否处于ANR状态】

  • 6.Dialog anrDialog: // dialog being displayed due to app not resp.【ANR显示对话框】

  • 7.Runnable crashHandler: // Optional local handler to be invoked in the process crash.【crash回调】

  • 8.ActivityManager.ProcessErrorStateInfo crashingReport: // These reports are generated & stored when an app gets into an error condition. They will be “null” when all is OK.【crash报告的进程状态】

  • 9.ActivityManager.ProcessErrorStateInfo notRespondingReport: // These reports are generated & stored when an app gets into an error condition. They will be “null” when all is OK.【ANR报告的进程状态】

  • 10.String waitingToKill: // Process is waiting to be killed when in the bg, and reason【后台进程被kill原因】

  • 11.ComponentName errorReportReceiver: // Who will be notified of the error. This is usually an activity in the app that installed the package.【接收error信息的组件】

第七类数据:和 Instrumentation 相关的数据

Instrumentation 具有跟踪 application 及 activity 生命周期的功能,用于 android 应用测试框架中,被做为基类使用。

  • 1.ComponentName instrumentationClass: AndroidManifest.xml中定义的instrumentation信息

  • 2.ApplicationInfo instrumentationInfo: instrumentation应用信息

  • 3.String instrumentationProfileFile: instrumentation配置文件

  • 4.IInstrumentationWatcher instrumentationWatcher: instrumentation监测器

  • 5.IUiAutomationConnection instrumentationUiAutomationConnection: UiAutomation连接器

  • 6.ComponentName instrumentationResultClass: 返回结果组件

第八类数据:电源信息和调试信息

  • 1.BatteryStatsImpl mBatteryStats: 电量信息

  • 2.BatteryStatsImpl.Uid.Proc curProcBatteryStats: 当前进程电量信息

  • 3.boolean debugging: 处于调试中

  • 4.boolean waitedForDebugger: 等待调试

  • 5.Dialog waitDialog: 等待对话框

  • 6.String adjType: adj类型(或者说标示)

  • 7.int adjTypeCode: adj类型码(也是一种标示)

  • 8.Object adjSource: 改变adj的组件记录表

  • 9.int adjSourceProcState: 影响adj的进程状态

  • 10.Object adjTarget: 改变adj的组件

  • 11.String shortStringName: 进程记录表的字符串显示

  • 12.String stringName: 进程记录表的字符串显示

第九类数据:其他

  • 1、进程声明周期相关

    • boolean starting:进程是否正在启动
    • boolean removed:进程系统资源是否已经清理
    • boolean killedByAm:进程是否被 AMS 杀掉
    • boolean killed:进程是否被杀掉
    • boolean persistent:是否是常驻内存进程
  • 2、组件状态影响进程行为相关

    • boolean empty:空进程,不含有任何组件的进程
    • boolean cached:缓存进程
    • boolean bad:60s内连续crash两次的进程被定义为bad进程
    • boolean hasClientActivities:进程有Activity绑定其他Service
    • boolean hasStartedServices:进程中包含启动了的Service
    • boolean foregroundServices:进程中包含前台运行的Service
    • boolean foregroundActivities:进程中包含前台运行的Activity
    • boolean repForegroundActivities:
    • boolean systemNoUi:系统进程,没有显示UI
    • boolean hasShownUi:重进程启动开始,是否已经显示UI
    • boolean pendingUiClean:是否想要清除显示UI中的资源
    • boolean hasAboveClient:进程中有组件使用BIND_ABOVE_CLIENT标志绑定其他Service
    • boolean treatLikeActivity:进程中有组件使用BIND_TREAT_LIKE_ACTIVITY标志绑定其他Service
    • boolean execServicesFg:前台执行Service
    • boolean setIsForeground:设置运行前台UI
  • 3、其他相关

    • boolean serviceb:进程存在service B list中
    • boolean serviceHighRam:由于内存原因,进程强制存在service B list中
    • boolean notCachedSinceIdle:进程自从上次空闲,是否属于缓存进程
    • boolean procStateChanged:进程状态改变
    • boolean reportedInteraction:是否报告交互事件
    • boolean unlocked:解锁状态下进程启动
    • boolean usingWrapper:zygote是否使用了wrapper启动apk进程
    • boolean reportLowMemory:报告低内存
    • boolean inFullBackup:进程中存在backup组件在运行
    • boolean whitelistManager:和电源管理相关

容器

进程主要占用的资源主要分为:ProcessRecord 容器组件记录表容器

ProcessRecord容器

永久性容器

  • 1.mProcessNames: 根据进程名字检索进程记录表

  • 2.mPidsSelfLocked: 根据进程pid检索进程记录表

  • 3.mLruProcesses: lru 进程记录表容器,这个容器使用的是最近最少使用算法对进程记录表进行排序,越是处于上层的越是最近使用的,对于系统来说就是最重要的,在内存吃紧回收进程时,越不容易被回收,实现起来也很简单

临时性容器

  • 1.mPersistentStartingProcesses: 常驻内存进程启动时容器

  • 2.mProcessesOnHold: 进程启动挂起容器

  • 3.mProcessesToGc: 将要执行gc回收的进程容器

  • 4.mPendingPssProcesses: 将要计算Pss数据的进程容器

特殊容器

  • 1.mRemovedProcesses: 已经移除的进程容器

组件记录表容器

组件运行才是进程存在的意义,由于android系统进程间的无缝结合,所以系统需要控制到组件级别,所有的组件信息都需要映射到系统,一个ActivityRecord记录对应一个Activity的信息,一个ServiceRecord记录对应一个Service的信息,一个ConnectionRecord记录对应一个bind service的客户端信息,一个ReceiverList对应处理同一事件的一组广播,一个ContentProviderRecord记录对应一个ContentProvider信息,一个ContentProviderConnection对应一个进程中的所有ContentProvider客户端。

activity 记录

  • activities: ActivityRecord的容器,进程启动的所有的activity组件记录表

service 记录

  • services: ServiceRecord的容器,进程启动的所有的service组件记录表

  • executingServices: 正在运行(executing)的ServiceRecord是怎么定义的?首先需要明确的是系统是怎么控制组件的?发送消息给apk进程,apk进程处理消息,上报消息完成,这被定义为一个完整的执行过程,因此正在执行(executing)被定义为发送消息到上报完成这段时间

  • 3.connections: ConnectionRecord容器,绑定service的客户端记录表

BroadcastReceive 记录

  • receivers: ReceiverList容器,广播接收器的记录表

ContentProvider 记录

  • pubProviders: 名字到ContentProviderRecord的映射容器,pub是publish(发布)的意思,ContentProvider需要安装然后把自己发布到系统(AMS)中后,才能使用,安装指的是apk进程加载ContentProvider子类、初始化、创建数据库等过程,发布是将ContentProvider的binder客户端注册到AMS中

  • conProviders: ContentProviderConnection容器,使用ContentProvider的客户端记录表

Activity 管理相关类介绍

ActivityRecord

官方注释如下:

/**
 * An entry in the history stack, representing an activity.
 */

历史栈帧中的条目,代表一个 activity

final class ActivityRecord extends ConfigurationContainer implements AppWindowContainerListener {

... ...

final ActivityManagerService service; // owner
final IApplicationToken.Stub appToken; // window manager token
AppWindowContainerController mWindowContainerController;
final ActivityInfo info; // all about me
// TODO: This is duplicated state already contained in info.applicationInfo - remove
ApplicationInfo appInfo; // information about activity's app

... ...

//ActivityRecord所在的TaskRecord
private TaskRecord task; // the task this is in.

... ...

//构造方法,需要传递大量信息
ActivityRecord(ActivityManagerService _service, ProcessRecord _caller, int _launchedFromPid,
int _launchedFromUid, String _launchedFromPackage, Intent _intent, String _resolvedType,
ActivityInfo aInfo, Configuration _configuration,
ActivityRecord _resultTo, String _resultWho, int _reqCode,
boolean _componentSpecified, boolean _rootVoiceInteraction,
ActivityStackSupervisor supervisor, ActivityOptions options,
ActivityRecord sourceRecord) {

}
}

ActivityRecord 中包含 Activity 的所有信息。其成员变量 task 表示其所在的 TaskRecord,两者关系密不可分。

TaskRecord

内部维护着一个 ArrayList<ActivityRecord> 用来保存 ActivityRecord.

class TaskRecord extends ConfigurationContainer implements TaskWindowContainerListener {

...

final int taskId; // Unique identifier for this task. 任务ID

...

/** List of all activities in the task arranged in history order */
final ArrayList<ActivityRecord> mActivities; // 使用一个ArrayList来保存所有的 ActivityRecord

/** Current stack. Setter must always be used to update the value. */
private ActivityStack mStack; // TaskRecord所在的 ActivityStack

...

/**
* Don't use constructor directly. Use {@link #create(ActivityManagerService, int, ActivityInfo,
* Intent, TaskDescription)} instead.
*/
TaskRecord(ActivityManagerService service, int _taskId, ActivityInfo info, Intent _intent,
IVoiceInteractionSession _voiceSession, IVoiceInteractor _voiceInteractor) {
}

/**
* Don't use constructor directly. Use {@link #create(ActivityManagerService, int, ActivityInfo,
* Intent, IVoiceInteractionSession, IVoiceInteractor)} instead.
*/
TaskRecord(ActivityManagerService service, int _taskId, ActivityInfo info, Intent _intent,
TaskDescription _taskDescription) {
}

/**
* Don't use constructor directly. This is only used by XML parser.
*/
TaskRecord(ActivityManagerService service, int _taskId, Intent _intent,
Intent _affinityIntent, String _affinity, String _rootAffinity,
ComponentName _realActivity, ComponentName _origActivity, boolean _rootWasReset,
boolean _autoRemoveRecents, boolean _askedCompatMode, int _userId,
int _effectiveUid, String _lastDescription, ArrayList<ActivityRecord> activities,
long lastTimeMoved, boolean neverRelinquishIdentity,
TaskDescription _lastTaskDescription, int taskAffiliation, int prevTaskId,
int nextTaskId, int taskAffiliationColor, int callingUid, String callingPackage,
int resizeMode, boolean supportsPictureInPicture, boolean _realActivitySuspended,
boolean userSetupComplete, int minWidth, int minHeight) {
}

// 添加 Activity 入栈顶
void addActivityToTop(ActivityRecord r) {
addActivityAtIndex(mActivities.size(), r);
}

/**
* 添加 Activity 到指定索引位置
*/
void addActivityAtIndex(int index, ActivityRecord r) {

...

r.setTask(this); // 为 ActivityRecord 设置 TaskRecord,两者建立关系

...

index = Math.min(size, index);
mActivities.add(index, r); // 添加到mActivities

...
}
}

可以看到,TaskRecord 使用了一个 ArrayList 来保存所有的 ActivityRecord,同样 TaskRecord 中 mStack 表示其所在的 ActivityStack。startActviity() 时也会创建一个 TaskRecord。

ActivityStarter

/**
* Controller for interpreting how and then launching an activity.
*
* This class collects all the logic for determining how an intent and flags should be turned into
* an activity and associated task and stack.
*/
class ActivityStarter {
private int setTaskFromReuseOrCreateNewTask(
TaskRecord taskToAffiliate, ActivityStack topStack) {
mTargetStack = computeStackFocus(mStartActivity, true, mLaunchFlags, mOptions);

// Do no move the target stack to front yet, as we might bail if
// isLockTaskModeViolation fails below.

if (mReuseTask == null) {
//创建一个createTaskRecord,实际上是调用ActivityStack里面的 createTaskRecord()方法,ActivityStack下面会讲到
final TaskRecord task = mTargetStack.createTaskRecord(
mSupervisor.getNextTaskIdForUserLocked(mStartActivity.userId),
mNewTaskInfo != null ? mNewTaskInfo : mStartActivity.info,
mNewTaskIntent != null ? mNewTaskIntent : mIntent, mVoiceSession,
mVoiceInteractor, !mLaunchTaskBehind /* toTop */, mStartActivity, mSourceRecord,
mOptions);
addOrReparentStartingActivity(task, "setTaskFromReuseOrCreateNewTask - mReuseTask");
updateBounds(mStartActivity.getTask(), mLaunchParams.mBounds);

if (DEBUG_TASKS) Slog.v(TAG_TASKS, "Starting new activity " + mStartActivity
+ " in new task " + mStartActivity.getTask());
} else {
addOrReparentStartingActivity(mReuseTask, "setTaskFromReuseOrCreateNewTask");
}

...
}
}

ActivityStack

ActivityStack 内部维护了一个 ArrayList<TaskRecord> ,用来管理 TaskRecord

/**
* State and management of a single stack of activities.
*/
class ActivityStack<T extends StackWindowController> extends ConfigurationContainer
implements StackWindowListener {
/**
* The back history of all previous (and possibly still
* running) activities. It contains #TaskRecord objects.
*/
private final ArrayList<TaskRecord> mTaskHistory = new ArrayList<>(); // ArrayList 保存 TaskRecord

/** Run all ActivityStacks through this */
protected final ActivityStackSupervisor mStackSupervisor; // 持有一个 ActivityStackSupervisor,所有的运行中的 ActivityStacks 都通过它来进行管

...

TaskRecord createTaskRecord(int taskId, ActivityInfo info, Intent intent,
IVoiceInteractionSession voiceSession, IVoiceInteractor voiceInteractor,
boolean toTop) {
return createTaskRecord(taskId, info, intent, voiceSession, voiceInteractor, toTop,
null /*activity*/, null /*source*/, null /*options*/);
}

TaskRecord createTaskRecord(int taskId, ActivityInfo info, Intent intent,
IVoiceInteractionSession voiceSession, IVoiceInteractor voiceInteractor,
boolean toTop, ActivityRecord activity, ActivityRecord source,
ActivityOptions options) {
// 创建一个 task
final TaskRecord task = TaskRecord.create(
mService, taskId, info, intent, voiceSession, voiceInteractor);
// 将 task 添加到 ActivityStack 中
addTask(task, toTop, "createTaskRecord");

...

return task;
}

// 添加 task
void addTask(final TaskRecord task, final boolean toTop, String reason) {
addTask(task, toTop ? MAX_VALUE : 0, true /* schedulePictureInPictureModeChange */, reason);

...
}

// 添加 task 到指定位置
void addTask(final TaskRecord task, int position, boolean schedulePictureInPictureModeChange,
String reason) {
// 如果栈中存在,则先移除
mTaskHistory.remove(task);

...

// 添加 task 到 mTaskHistory
mTaskHistory.add(position, task);
//为TaskRecord设置ActivityStack
task.setStack(this);

...
}
}

可以看到,ActivityStack 使用了一个 ArrayList 来保存 TaskRecord 。 另外,ActivityStack 中还持有 ActivityStackSupervisor 对象,这个是用来管理ActivityStacks的。

ActivityStack 是由 ActivityStackSupervisor 来创建的,实际ActivityStackSupervisor 就是用来管理ActivityStack的。

ActivityStackSupervisor

ActivityStackSupervisor 是用来管理 ActivityStack的。

public class ActivityStackSupervisor extends ConfigurationContainer implements DisplayListener,
RecentTasks.Callbacks {

...

/** The stack containing the launcher app. Assumed to always be attached to
* Display.DEFAULT_DISPLAY.
*/
ActivityStack mHomeStack; // 管理的是 Launcher 相关的任务

/** The stack currently receiving input or launching the next activity. */
ActivityStack mFocusedStack; //管理非 Launcher相关的任务

//创建ActivityStack
ActivityStack createStack(int stackId, ActivityStackSupervisor.ActivityDisplay display, boolean onTop) {
switch (stackId) {
case PINNED_STACK_ID:
//PinnedActivityStack是ActivityStack的子类
return new PinnedActivityStack(display, stackId, this, mRecentTasks, onTop);
default:
//创建一个ActivityStack
return new ActivityStack(display, stackId, this, mRecentTasks, onTop);
}
}
}

ActivityStackSupervisor 内部有两个不同的 ActivityStack 对象:mHomeStack、mFocusedStack,用来管理不同的任务。ActivityStackSupervisor内部包含了创建ActivityStack对象的方法。 AMS初始化时会创建一个ActivityStackSupervisor对象。

ActivityStackSupervisor.png

Activity 启动过程

Activity启动1.png

Launcher 请求 AMS 阶段

Launcher请求AMS阶段.png

AMS到ApplicationThread阶段

AMS到ApplicationThread阶段.png

ApplicationThread到Activity阶段

ApplicationThread到Activity阶段.png

  • API 28重构之后

API28重构之后.png

ActivityManagerService 启动过程

SystemServer

AMS 是在 SystemServer 中被添加的,首先查阅 SystemServer.java 查看初始化:

/**
* The main entry point from zygote.
*/
public static void main(String[] args) {
new SystemServer().run();
}

查看 run 方法:


private void run() {
try {
...

// 初始化主循环线程(此线程)
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);

// 初始化本地服务。
System.loadLibrary("android_servers");

// 检查上次尝试是否关闭失败。
// 此调用可能不返回。
performPendingShutdown();

// 初始化系统上下文环境.
createSystemContext();

// 创建系统服务管理器
mSystemServiceManager = new SystemServiceManager(mSystemContext);
mSystemServiceManager.setStartInfo(mRuntimeRestart,
mRuntimeStartElapsedTime, mRuntimeStartUptime);
LocalServices.addService(SystemServiceManager.class, mSystemServiceManager);
// Prepare the thread pool for init tasks that can be parallelized
SystemServerInitThreadPool.get();
} finally {
traceEnd(); // InitBeforeStartServices
}

// 开启服务
try {
traceBeginAndSlog("StartServices");
startBootstrapServices();
startCoreServices();
startOtherServices();
SystemServerInitThreadPool.shutdown();
} catch (Throwable ex) {
Slog.e("System", "******************************************");
Slog.e("System", "************ Failure starting system services", ex);
throw ex;
} finally {
traceEnd();
}

...

// Loop forever.
Looper.loop();
throw new RuntimeException("Main thread loop unexpectedly exited");
}

startBootstrapServices

在 SystemServer 中,在 startBootstrapServices() 中启动 AMS

private void startBootstrapServices() {

...

// Activity manager runs the show.
traceBeginAndSlog("StartActivityManager");
// 启动 AMS
mActivityManagerService = mSystemServiceManager.startService(
ActivityManagerService.Lifecycle.class).getService();
mActivityManagerService.setSystemServiceManager(mSystemServiceManager);
mActivityManagerService.setInstaller(installer);
traceEnd();

...

// Now that the power manager has been started, let the activity manager
// initialize power management features.
traceBeginAndSlog("InitPowerManagement");
mActivityManagerService.initPowerManagement();
traceEnd();

...

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

...
}

startService

AMS 是通过 SystemServiceManager.startService 启动的,参数是 ActivityManagerService.Lifecycle.class,接下来看 startService 方法:

@SuppressWarnings("unchecked")
public SystemService startService(String className) {
final Class<SystemService> serviceClass;
try {
serviceClass = (Class<SystemService>)Class.forName(className);
} catch (ClassNotFoundException ex) {
Slog.i(TAG, "Starting " + className);
throw new RuntimeException("Failed to create service " + className
+ ": service class not found, usually indicates that the caller should "
+ "have called PackageManager.hasSystemFeature() to check whether the "
+ "feature is available on this device before trying to start the "
+ "services that implement it", ex);
}
return startService(serviceClass);
}
@SuppressWarnings("unchecked")
public <T extends SystemService> T startService(Class<T> serviceClass) {
try {
final String name = serviceClass.getName();
Slog.i(TAG, "Starting " + name);
Trace.traceBegin(Trace.TRACE_TAG_SYSTEM_SERVER, "StartService " + name);

// Create the service.
if (!SystemService.class.isAssignableFrom(serviceClass)) {
throw new RuntimeException("Failed to create " + name
+ ": service must extend " + SystemService.class.getName());
}
final T service;
try {
Constructor<T> constructor = serviceClass.getConstructor(Context.class);
service = constructor.newInstance(mContext);
} catch (InstantiationException ex) {
throw new RuntimeException("Failed to create service " + name
+ ": service could not be instantiated", ex);
} catch (IllegalAccessException ex) {
throw new RuntimeException("Failed to create service " + name
+ ": service must have a public constructor with a Context argument", ex);
} catch (NoSuchMethodException ex) {
throw new RuntimeException("Failed to create service " + name
+ ": service must have a public constructor with a Context argument", ex);
} catch (InvocationTargetException ex) {
throw new RuntimeException("Failed to create service " + name
+ ": service constructor threw an exception", ex);
}

startService(service);
return service;
} finally {
Trace.traceEnd(Trace.TRACE_TAG_SYSTEM_SERVER);
}
}
public void startService(@NonNull final SystemService service) {
// Register it.
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");
}

startService 是通过传进来的 class 参数然后反射创建对应的 service 服务。所以此处创建的是 Lifecycle 的实例,然后通过 startService 启动 AMS服务。

ActivityManagerService.Lifecycle

那么接下来查阅一下 ActivityManagerService.Lifecycle 这个类

public static final class Lifecycle extends SystemService {
private final ActivityManagerService mService;

public Lifecycle(Context context) {
super(context);
mService = new ActivityManagerService(context);
}

@Override
public void onStart() {
mService.start();
}

@Override
public void onBootPhase(int phase) {
mService.mBootPhase = phase;
if (phase == PHASE_SYSTEM_SERVICES_READY) {
mService.mBatteryStatsService.systemServicesReady();
mService.mServices.systemServicesReady();
}
}

@Override
public void onCleanupUser(int userId) {
mService.mBatteryStatsService.onCleanupUser(userId);
}

public ActivityManagerService getService() {
return mService;
}
}

AMS Constructor

再看 AMS 构造函数初始化

// Note: This method is invoked on the main thread but may need to attach various
// handlers to other threads. So take care to be explicit about the looper.
public ActivityManagerService(Context systemContext) {
LockGuard.installLock(this, LockGuard.INDEX_ACTIVITY);
mInjector = new Injector();
// 赋值 上下文环境
mContext = systemContext;

mFactoryTest = FactoryTest.getMode();
// 获取当前的 ActivityThread
mSystemThread = ActivityThread.currentActivityThread();
// 赋值 mUiContext
mUiContext = mSystemThread.getSystemUiContext();

Slog.i(TAG, "Memory class: " + ActivityManager.staticGetMemoryClass());

mPermissionReviewRequired = mContext.getResources().getBoolean(
com.android.internal.R.bool.config_permissionReviewRequired);

// 创建 Handler 线程 用来处理 Handler 消息
mHandlerThread = new ServiceThread(TAG,
THREAD_PRIORITY_FOREGROUND, false /*allowIo*/);
mHandlerThread.start();
mHandler = new MainHandler(mHandlerThread.getLooper());
mUiHandler = mInjector.getUiHandler(this);

mProcStartHandlerThread = new ServiceThread(TAG + ":procStart",
THREAD_PRIORITY_FOREGROUND, false /* allowIo */);
mProcStartHandlerThread.start();
mProcStartHandler = new Handler(mProcStartHandlerThread.getLooper());

// 管理AMS的一些常量,厂商定制系统就可能修改此处
mConstants = new ActivityManagerConstants(this, mHandler);

/* static; one-time init here */
if (sKillHandler == null) {
sKillThread = new ServiceThread(TAG + ":kill",
THREAD_PRIORITY_BACKGROUND, true /* allowIo */);
sKillThread.start();
sKillHandler = new KillHandler(sKillThread.getLooper());
}

// 初始化管理前台、后台广播的队列, 系统会优先遍历发送前台广播
mFgBroadcastQueue = new BroadcastQueue(this, mHandler,
"foreground", BROADCAST_FG_TIMEOUT, false);
mBgBroadcastQueue = new BroadcastQueue(this, mHandler,
"background", BROADCAST_BG_TIMEOUT, true);
mBroadcastQueues[0] = mFgBroadcastQueue;
mBroadcastQueues[1] = mBgBroadcastQueue;

// 初始化管理Service的 ActiveServices对象
mServices = new ActiveServices(this);
// 初始化 Provider 管理者
mProviderMap = new ProviderMap(this);
// 初始化APP错误日志的打印器
mAppErrors = new AppErrors(mUiContext, this);

// 创建电池统计服务,并输出指定目录
File dataDir = Environment.getDataDirectory();
File systemDir = new File(dataDir, "system");
systemDir.mkdirs();

mAppWarnings = new AppWarnings(this, mUiContext, mHandler, mUiHandler, systemDir);

// 创建进程统计分析服务,追踪统计哪些进程有滥用或者不良行为
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"));

mAppOpsService = mInjector.getAppOpsService(new File(systemDir, "appops.xml"), mHandler);

// 加载Uri的授权文件
mGrantFile = new AtomicFile(new File(systemDir, "urigrants.xml"), "uri-grants");

// 负责管理多用户
mUserController = new UserController(this);

// vr功能的控制器
mVrController = new VrController(this);

// 初始化OpenGL版本号
GL_ES_VERSION = SystemProperties.getInt("ro.opengles.version",
ConfigurationInfo.GL_ES_VERSION_UNDEFINED);

if (SystemProperties.getInt("sys.use_fifo_ui", 0) != 0) {
mUseFifoUiScheduling = true;
}

mTrackingAssociations = "1".equals(SystemProperties.get("debug.track-associations"));
mTempConfig.setToDefaults();
mTempConfig.setLocales(LocaleList.getDefault());
mConfigurationSeq = mTempConfig.seq = 1;
// 管理 ActivityStack ,该类记录着 activity 的状态信息,是 AMS 中的核心类
mStackSupervisor = createStackSupervisor();
mStackSupervisor.onConfigurationChanged(mTempConfig);
// 根据当前可见的 Activity 类型,控制 keyguard 遮挡、关闭和转换。keyGuard就是锁屏相关界面
mKeyguardController = mStackSupervisor.getKeyguardController();
mCompatModePackages = new CompatModePackages(this, systemDir, mHandler);
// Intent防火墙,Google定义了一组规则,来过滤 intent,如果触发,则 intent会被系统丢弃,且不会告知发送者
mIntentFirewall = new IntentFirewall(new IntentFirewallInterface(), mHandler);
mTaskChangeNotificationController =
new TaskChangeNotificationController(this, mStackSupervisor, mHandler);
// Activity 启动的处理类,这里管理 activity 启动中用到的intent信息和flag标识,也和stack、task有重要的干系
mActivityStartController = new ActivityStartController(this);
mRecentTasks = createRecentTasks();
mStackSupervisor.setRecentTasks(mRecentTasks);
mLockTaskController = new LockTaskController(mContext, mStackSupervisor, mHandler);
mLifecycleManager = new ClientLifecycleManager();

// 启动一个线程专门跟进 CPU 当前状态信息, AMS 对当前CPU的状态了如指掌,可以更加高效的安排其他工作
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();
} catch (Exception e) {
Slog.e(TAG, "Unexpected exception collecting process stats", e);
}
}
}
};

mHiddenApiBlacklist = new HiddenApiSettings(mHandler, mContext);

// 看门狗,监听进程。该类每分钟调用一次监视器,如果进程没有返回就直接杀掉
Watchdog.getInstance().addMonitor(this);
Watchdog.getInstance().addThread(mHandler);

// bind background thread to little cores
// this is expected to fail inside of framework tests because apps can't touch cpusets directly
// make sure we've already adjusted system_server's internal view of itself first
updateOomAdjLocked();
try {
Process.setThreadGroupAndCpuset(BackgroundThread.get().getThreadId(),
Process.THREAD_GROUP_BG_NONINTERACTIVE);
} catch (Exception e) {
Slog.w(TAG, "Setting background thread cpuset failed");
}

}

ActivityManagerService.Lifecycle.start

继续回到 ActivityManagerService.Lifecycle 这个类,查阅 start 方法

private void start() {
removeAllProcessGroups();
mProcessCpuThread.start();

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

setSystemProcess

在 AMS 启动完成后,再来看 setSystemProcess 方法

public void setSystemProcess() {
try {
// 注册服务
// 先将 ActivityManagerService 注册到 ServiceManager 中,
// 其次将几个与系统性能调试相关的几个服务也注册到 ServiceManager中
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
// 首先调用 PackageManagerService 的接口,查询包名为 android 的应用程序的 ApplicationInfo 信息,对应于framework-res.apk
// 然后以该信息为参数调用 ActivityThread 上的 installSystemApplicationInfo 方法。
ApplicationInfo info = mContext.getPackageManager().getApplicationInfo(
"android", STOCK_PM_FLAGS | MATCH_SYSTEM_ONLY);
mSystemThread.installSystemApplicationInfo(info, getClass().getClassLoader());

// 创建并处理 ProcessRecord
// 调用 AMS 内的 newProcessRecordLocked,创建一个 ProcessRecord 类型的对象,并保存该对象信息
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);
}

// Start watching app ops after we and the package manager are up and running.
mAppOpsService.startWatchingMode(AppOpsManager.OP_RUN_IN_BACKGROUND, null,
new IAppOpsCallback.Stub() {
@Override public void opChanged(int op, int uid, String packageName) {
if (op == AppOpsManager.OP_RUN_IN_BACKGROUND && packageName != null) {
if (mAppOpsService.checkOperation(op, uid, packageName)
!= AppOpsManager.MODE_ALLOWED) {
runInBackgroundDisabled(uid);
}
}
}
});
}

总结

  • 注册服务。首先将ActivityManagerService注册到ServiceManager中,其次将几个与系统性能调试相关的服务注册到ServiceManager。

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

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

打赏
  • 微信
  • 支付宝

评论