本系列共包含WMS、AMS、PMS三篇文章,此为第二篇。
本文撰写过程中参考了多篇文章,感谢作者不吝分享,已在文末注明出处。
为什么要研究AMS?
AMS
(ActivityManagerService
)是与APP关系最密切的系统服务,APP的启动、打开首页、页面之间跳转、Task管理都与AMS密不可分,学习AMS源码有助于于深刻理解Android页面生命周期。
带着问题学习
本文使用的Android源码是13.0版本。
在学习之前,先问自己几个与其相关的问题,带着这些问题开启本次的学习。
AMS
是如何启动的?AMS
如何与系统进行交互?- 从点击桌面应用icon,到APP的
Application.onCreate()
被调用,这中间发生了什么?又是如何进入到Activity.onCreate()
中的? - 系统如何管理不同的
Task
?
AMS的启动流程
Android系统启动流程
再来重温下Android系统启动的流程,主板通电后,引导芯片开始从ROM执行,加载引导程序(Bootloader
)到RAM,将boot.img
映像装载到RAM,它记录了一个Linux内核以及文件系统,自此Linux内核启动。
当内核完成系统设置后,首先在系统文件中寻找init.rc
,将其作为Init进程启动,过程中对init.rc
进行解析,zygote
就是配置在init.rc
当中的。
Zygote
是所有应用程序进程的父进程,它主要有以下几个职责:
- 通过
fork
方式创建SystemServer
进程、以及所有应用程序进程 - 启动ART虚拟机,因此在上一步创建的进程都可以得到一个ART的副本
- 启动结束后,
Zygote
变成守护进程,负责响应启动APP的请求
在第一步中,Zygote
启动SystemServer
进程,对应的代码就是SystemServer.java
,而AMS
就是在其中启动的。
SystemServer.java
在SystemServer
构建时,会启动三大类服务,AMS属于第一种即BootstrapServices
。
SystemServer.java
pivate void run() {
...
startBootstrapServices();
startCoreServices();
startOtherServices();
...
}
在startBootstrapServices()
中,调用ActivityManagerService.Lifecycle
的startService()
方法来创建AMS
的实例。函数的最后,通过mActivityManagerService.setSystemProcess()
将AMS
以activity
作为Key,注册到ServiceManager
中,以便其它应用通过Binder
来获取AMS代理。
private void startBootstrapServices() {
...
ActivityTaskManagerService atm = mSystemServiceManager.startService(ActivityTaskManagerService.Lifecycle.class).getService();
mActivityManagerService = ActivityManagerService.Lifecycle.startService(mSystemServiceManager, atm);
mActivityManagerService.setSystemServiceManager(mSystemServiceManager);
mActivityManagerService.setInstaller(installer);
...
mActivityManagerService.setSystemProcess();
Lifecycle
是AMS
的内部类,它持有AMS
、ATMS
的实例,在静态方法startService()
中通过SystemServiceManager.startService()
来创建自身的实例。
ActivityManagerService.java
public class ActivityManagerService {
...
public static final class Lifecycle extends SystemService {
private final ActivityManagerService mService;
private static ActivityTaskManagerService sAtm;
public Lifecycle(Context context) {
super(context);
mService = new ActivityManagerService(context, sAtm);
}
public static ActivityManagerService startService(
SystemServiceManager ssm, ActivityTaskManagerService atm) {
sAtm = atm;
return ssm.startService(ActivityManagerService.Lifecycle.class).getService();
}
...
以下是SystemServer
的代码,对传入的Lifecycle.class
使用反射,调用其构造函数,最终还是通过new ActivityManagerService(context, sAtm)
来生成AMS
。之所以要多此一举,是需要由SystemServer
对创建的服务进行统一管理的缘故。
SystemServer.java
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) {]
...
}
startService(service); // <--重点:启动服务
return service;
} finally {
Trace.traceEnd(Trace.TRACE_TAG_SYSTEM_SERVER);
}
}
在startService()
函数内部,依次调用到AMS
的构造函数和onStart()
函数。它的构造函数没有太复杂的逻辑,主要是初始化一系列成员变量,也包括ProcStatsService
、AppOpsService
、BatteryStatsService
等系统服务。
ActivityManagerService.java
// 构造函数,进行一系列初始化操作,无关代码已略去
public ActivityManagerService(Context systemContext, ActivityTaskManagerService atm) {
// 系统context,在ContextImpl.createSystemContext中创建,每个ActivityThread拥有一个
mContext = systemContext;
mUiContext = mSystemThread.getSystemUiContext();
// 后台Handler和UIHandler
mHandlerThread = new ServiceThread(TAG,
THREAD_PRIORITY_FOREGROUND, false /*allowIo*/);
mHandlerThread.start();
mHandler = new MainHandler(mHandlerThread.getLooper());
mUiHandler = mInjector.getUiHandler(this);
// 管理APP进程启动的Handler
mProcStartHandlerThread = new ServiceThread(TAG + ":procStart",
THREAD_PRIORITY_FOREGROUND, false /* allowIo */);
mProcStartHandlerThread.start();
mProcStartHandler = new Handler(mProcStartHandlerThread.getLooper());
// 广播策略,前后台超时时间等
mFgBroadcastQueue = new BroadcastQueue(this, mHandler,
"foreground", foreConstants, false);
mBgBroadcastQueue = new BroadcastQueue(this, mHandler,
"background", backConstants, true);
mOffloadBroadcastQueue = new BroadcastQueue(this, mHandler,
"offload", offloadConstants, true);
mBroadcastQueues[0] = mFgBroadcastQueue;
mBroadcastQueues[1] = mBgBroadcastQueue;
mBroadcastQueues[2] = mOffloadBroadcastQueue;
// 其它一系列系统服务
mBatteryStatsService = new BatteryStatsService(systemContext, systemDir,
BackgroundThread.get().getHandler());
mBatteryStatsService.getActiveStatistics().readLocked();
mBatteryStatsService.scheduleWriteToDisk();
mOnBattery = DEBUG_POWER ? true
: mBatteryStatsService.getActiveStatistics().getIsOnBattery();
mBatteryStatsService.getActiveStatistics().setCallback(this);
mOomAdjProfiler.batteryPowerChanged(mOnBattery);
mProcessStats = new ProcessStatsService(this, new File(systemDir, "procstats"));
mAppOpsService = mInjector.getAppOpsService(new File(systemDir, "appops.xml"), mHandler);
mUgmInternal = LocalServices.getService(UriGrantsManagerInternal.class);
mUserController = new UserController(this);
mPendingIntentController = new PendingIntentController(
mHandlerThread.getLooper(), mUserController);
if (SystemProperties.getInt("sys.use_fifo_ui", 0) != 0) {
mUseFifoUiScheduling = true;
}
mTrackingAssociations = "1".equals(SystemProperties.get("debug.track-associations"));
mIntentFirewall = new IntentFirewall(new IntentFirewallInterface(), mHandler);
mActivityTaskManager = atm;
mActivityTaskManager.initialize(mIntentFirewall, mPendingIntentController,
DisplayThread.get().getLooper());
mAtmInternal = LocalServices.getService(ActivityTaskManagerInternal.class);
mHiddenApiBlacklist = new HiddenApiSettings(mHandler, mContext);
}
onStart()
函数则会调用其自身的start()
函数,最重要的一行代码是LocalServices.addService(ActivityManagerInternal.class, new LocalService())
,它将AMI
注册到SystemServer
的本地服务,注册的Key
为ActivityManagerInternal.class
,value
则是LocalService
对象,它是AMS
的非静态内部类,自然持有外部引用。
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 {
mProcessCpuInitLatch.await();
} catch (InterruptedException e) {
Slog.wtf(TAG, "Interrupted wait during start", e);
Thread.currentThread().interrupt();
throw new IllegalStateException("Interrupted wait during start");
}
}
启动Launcher
在SystemServer.startOtherServices()
最后,会调用AMS.systemReady()
来完成启动流程,最终启动Launcher
。
private void startOtherServices() {
...
mActivityManagerService.systemReady(() -> {
...
startSystemUi(context, windowManagerF);
...
}
private static void startSystemUi(Context context, WindowManagerService windowManager) {
Intent intent = new Intent();
intent.setComponent(new ComponentName("com.android.systemui",
"com.android.systemui.SystemUIService"));
intent.addFlags(Intent.FLAG_DEBUG_TRIAGED_MISSING);
//Slog.d(TAG, "Starting service: " + intent);
context.startServiceAsUser(intent, UserHandle.SYSTEM);
windowManager.onSystemUiStarted();
}
AMS与APP进程
Zygote
承担了创建APP进程的职责,在Zygote
启动时,main()
函数里会创建一个Server
端的socket
,用来等待AMS
通知zygote
创建APP进程。在启动APP时,第一步就是检查它的进程是否存在,若不存在则创建一个。
Activity
在启动过程中会调用ActivityStackSupervisor.startSpecificActivityLocked()
函数,判断APP进程是否存在。
- 若进程存在,则调用
realStartActivityLocked()
- 若不存在,则通过
ATMS
的Handler
发送消息,调用ActivityManagerInternal::startProcess()
来启动进程。其内部是逐层调用到ZygoteProcess.zygoteSendArgsAndGetResult()
来fork
出子进程的
ActivityStackSupervisor.java
void startSpecificActivityLocked(ActivityRecord r, boolean andResume, boolean checkConfig) {
// Is this activity's application already running?
final WindowProcessController wpc =
mService.getProcessController(r.processName, r.info.applicationInfo.uid);
boolean knownToBeDead = false;
if (wpc != null && wpc.hasThread()) {
try {
// 进程存在
realStartActivityLocked(r, wpc, andResume, checkConfig);
return;
} catch (RemoteException e) {
Slog.w(TAG, "Exception when starting activity "
+ r.intent.getComponent().flattenToShortString(), e);
}
// If a dead object exception was thrown -- fall through to
// restart the application.
knownToBeDead = true;
}
// Suppress transition until the new activity becomes ready, otherwise the keyguard can
// appear for a short amount of time before the new process with the new activity had the
// ability to set its showWhenLocked flags.
if (getKeyguardController().isKeyguardLocked()) {
r.notifyUnknownVisibilityLaunched();
}
try {
if (Trace.isTagEnabled(TRACE_TAG_ACTIVITY_MANAGER)) {
Trace.traceBegin(TRACE_TAG_ACTIVITY_MANAGER, "dispatchingStartProcess:"
+ r.processName);
}
// Post message to start process to avoid possible deadlock of calling into AMS with the
// ATMS lock held.
// 进程不存在
final Message msg = PooledLambda.obtainMessage(
ActivityManagerInternal::startProcess, mService.mAmInternal, r.processName,
r.info.applicationInfo, knownToBeDead, "activity", r.intent.getComponent());
mService.mH.sendMessage(msg);
} finally {
Trace.traceEnd(TRACE_TAG_ACTIVITY_MANAGER);
}
}
ActivityThread.main()
创建新的APP进程后,执行ActivityThread.main()
静态方法,它会创建并启动主线程Looper
,同时创建一个ActivityThread
对象并执行attach()
。
ActivityThread.java
public static void main(String[] args) {
....
// 创建主线程Looper,并在下文启动
Looper.prepareMainLooper();
...
// 创建ActivityThread对象
ActivityThread thread = new ActivityThread();
thread.attach(false, startSeq);
if (sMainThreadHandler == null) {
sMainThreadHandler = thread.getHandler();
}
...
// 启动Looper
Looper.loop();
// 这一段代码不应该执行到
throw new RuntimeException("Main thread loop unexpectedly exited");
}
attach()
时启动APP的Application
,ActivityManager.getService()
返回的是IActivityManager
类型对象,其实现就是ServiceManager.getService("activity")
,也就是AMS
在APP侧的代理对象。
ActivityThread.java
private void attach(boolean system, long startSeq) {
sCurrentActivityThread = this;
mSystemThread = system;
if (!system) { // 用户APP
...
RuntimeInit.setApplicationObject(mAppThread.asBinder());
final IActivityManager mgr = ActivityManager.getService();
try {
mgr.attachApplication(mAppThread, startSeq); // <--重点:attachApplication
} catch (RemoteException ex) {
throw ex.rethrowFromSystemServer();
}
// Watch for getting close to heap limit.
BinderInternal.addGcWatcher(new Runnable() {
@Override public void run() {
if (!mSomeActivitiesChanged) {
return;
}
Runtime runtime = Runtime.getRuntime();
long dalvikMax = runtime.maxMemory();
long dalvikUsed = runtime.totalMemory() - runtime.freeMemory();
if (dalvikUsed > ((3*dalvikMax)/4)) {
if (DEBUG_MEMORY_TRIM) Slog.d(TAG, "Dalvik max=" + (dalvikMax/1024)
+ " total=" + (runtime.totalMemory()/1024)
+ " used=" + (dalvikUsed/1024));
mSomeActivitiesChanged = false;
try { // GC时释放后台Activity
ActivityTaskManager.getService().releaseSomeActivities(mAppThread);
} catch (RemoteException e) {
throw e.rethrowFromSystemServer();
}
}
}
});
} else { // 系统APP
// Don't set application object here -- if the system crashes,
// we can't display an alert, we just want to die die die.
android.ddm.DdmHandleAppName.setAppName("system_process",
UserHandle.myUserId());
try {
mInstrumentation = new Instrumentation();
mInstrumentation.basicInit(this);
ContextImpl context = ContextImpl.createAppContext(
this, getSystemContext().mPackageInfo);
mInitialApplication = context.mPackageInfo.makeApplication(true, null);
mInitialApplication.onCreate();
} catch (Exception e) {
throw new RuntimeException(
"Unable to instantiate Application():" + e.toString(), e);
}
}
...
}
AMS
在进行一系列操作(记录日志、组装ApplicationInfo
、初始化Application
的ContentProviders
等)后,又调用到ApplicationThread
的bindApplication()
函数,ApplicationThread
是ActivityThread
的非静态内部类,持有后者引用。ApplicationThread
发送BIND_APPLICATION
给Handler
,Handler
收到后进入ActivityThread.handleBindApplication()
,在这里进行大量的Application
初始化工作,如组装Process
信息、创建MQ、根据线程信息设置JVM等。
ActivityThread.java
private void handleBindApplication(AppBindData data) {
// 将APP名字设置给线程
// send up app name; do this *before* waiting for debugger
Process.setArgV0(data.processName);
android.ddm.DdmHandleAppName.setAppName(data.processName, UserHandle.myUserId());
VMRuntime.setProcessPackageName(data.appInfo.packageName);
// 设置APP的data目录
// Pass data directory path to ART. This is used for caching information and
// should be set before any application code is loaded.
VMRuntime.setProcessDataDirectory(data.appInfo.dataDir);
if (mProfiler.profileFd != null) {
mProfiler.startProfiling();
}
// 老版本AsyncTask实现,现在已经很少有Honeycomb了
// If the app is Honeycomb MR1 or earlier, switch its AsyncTask
// implementation to use the pool executor. Normally, we use the
// serialized executor as the default. This has to happen in the
// main thread so the main looper is set right.
if (data.appInfo.targetSdkVersion <= android.os.Build.VERSION_CODES.HONEYCOMB_MR1) {
AsyncTask.setDefaultExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
}
// ImageDecoder版本兼容
// Prior to P, internal calls to decode Bitmaps used BitmapFactory,
// which may scale up to account for density. In P, we switched to
// ImageDecoder, which skips the upscale to save memory. ImageDecoder
// needs to still scale up in older apps, in case they rely on the
// size of the Bitmap without considering its density.
ImageDecoder.sApiLevel = data.appInfo.targetSdkVersion;
// 生成Context对象
final ContextImpl appContext = ContextImpl.createAppContext(this, data.info);
updateLocaleListFromAppContext(appContext,
mResourcesManager.getConfiguration().getLocales());
...
// Instrumentation仪表盘,用于在Application创建过程中记录信息
try {
final ClassLoader cl = instrContext.getClassLoader();
mInstrumentation = (Instrumentation)
cl.loadClass(data.instrumentationName.getClassName()).newInstance();
} catch (Exception e) {
throw new RuntimeException(
"Unable to instantiate instrumentation "
+ data.instrumentationName + ": " + e.toString(), e);
}
final ComponentName component = new ComponentName(ii.packageName, ii.name);
mInstrumentation.init(this, instrContext, appContext, component,
data.instrumentationWatcher, data.instrumentationUiAutomationConnection);
if (mProfiler.profileFile != null && !ii.handleProfiling
&& mProfiler.profileFd == null) {
mProfiler.handlingProfiling = true;
final File file = new File(mProfiler.profileFile);
file.getParentFile().mkdirs();
Debug.startMethodTracing(file.toString(), 8 * 1024 * 1024);
}
} else {
mInstrumentation = new Instrumentation();
mInstrumentation.basicInit(this);
}
Application app;
final StrictMode.ThreadPolicy savedPolicy = StrictMode.allowThreadDiskWrites();
final StrictMode.ThreadPolicy writesAllowedPolicy = StrictMode.getThreadPolicy();
try {
// If the app is being launched for full backup or restore, bring it up in
// a restricted environment with the base application class.
app = data.info.makeApplication(data.restrictedBackupMode, null);
// Propagate autofill compat state
app.setAutofillOptions(data.autofillOptions);
// Propagate Content Capture options
app.setContentCaptureOptions(data.contentCaptureOptions);
mInitialApplication = app;
// don't bring up providers in restricted mode; they may depend on the
// app's custom Application class
if (!data.restrictedBackupMode) {
if (!ArrayUtils.isEmpty(data.providers)) {
installContentProviders(app, data.providers); // 安装ContentProviders
}
}
// Do this after providers, since instrumentation tests generally start their
// test thread at this point, and we don't want that racing.
try {
mInstrumentation.onCreate(data.instrumentationArgs);
}
catch (Exception e) {
throw new RuntimeException(
"Exception thrown in onCreate() of "
+ data.instrumentationName + ": " + e.toString(), e);
}
try {
mInstrumentation.callApplicationOnCreate(app); // <--重点:调用Application的onCreate()
}
在handleBindApplication()
的最后会调用Application.onCreate()
函数。AMS
执行完attachApplicationLocked()
后,会调用ATMS.attachApplication()
方法,后者调用ActivityStackSupervisor.realStartActivityLocked()
,通过ClientTransaction
与ClientLifecyleManager
等类的流转,最终调回到ActivityThread.handleLaunchActivity()
、performLaunchActivity()
,创建Activity
对象并执行attach()
、onCreate()
等函数,完成Activity
的创建和展示。
创建Activity
是通过反射来做的。
ActivityThread.java
public final class ActivityThread extends ClientTransactionHandler {
@Override
public Activity handleLaunchActivity(ActivityClientRecord r,
PendingTransactionActions pendingActions, Intent customIntent) {
final Activity a = performLaunchActivity(r, customIntent);
return a;
}
/** Core implementation of activity launch. */
private Activity performLaunchActivity(ActivityClientRecord r, Intent customIntent) {
ActivityInfo aInfo = r.activityInfo;
ContextImpl appContext = createBaseContextForActivity(r);
Activity activity = null;
try {
java.lang.ClassLoader cl = appContext.getClassLoader(); // <--重点:反射创建Activity对象
activity = mInstrumentation.newActivity(
cl, component.getClassName(), r.intent);
} catch (Exception e) {
if (!mInstrumentation.onException(activity, e)) {
throw new RuntimeException(
"Unable to instantiate activity " + component
+ ": " + e.toString(), e);
}
}
try {
// 由于bindApplication已经创建过application
// 所以此处返回,前文中创建的application
Application app = r.packageInfo.makeApplication(false, mInstrumentation);
if (activity != null) {
CharSequence title = r.activityInfo.loadLabel(appContext.getPackageManager());
Configuration config = new Configuration(mCompatConfiguration);
if (r.overrideConfig != null) {
config.updateFrom(r.overrideConfig);
}
// Activity resources must be initialized with the same loaders as the
// application context.
appContext.getResources().addLoaders(
app.getResources().getLoaders().toArray(new ResourcesLoader[0]));
// attach 方法
activity.attach(appContext, this, getInstrumentation(), r.token,
r.ident, app, r.intent, r.activityInfo, title, r.parent,
r.embeddedID, r.lastNonConfigurationInstances, config,
r.referrer, r.voiceInteractor, window, r.configCallback,
r.assistToken);
// 先设置主题
int theme = r.activityInfo.getThemeResource();
if (theme != 0) {
activity.setTheme(theme);
}
// 后执行onCreate方法
if (r.isPersistable()) {
mInstrumentation.callActivityOnCreate(activity, r.state, r.persistentState);
} else {
mInstrumentation.callActivityOnCreate(activity, r.state);
}
}
r.setState(ON_CREATE);
...
return activity;
}
}
至此,一个App的启动过程就讲完了。
- 从最初的通知
zygote
创建子进程,在子进程中执行ActivityThread
的main()
方法。 - 再到,将applicationThread对象传递给AMS,调用AMS的attachApplication方法。
- 再在AMS进程中调用bindApplicaiton让子进程创建application对象。
- 以及通过ClientLifecycleManager和ClientTransaction来执行,子进程中的handleLaunchActivity方法,最终调用performLaunchActivity方法来创建activity对象,执行activity的onCreate方法。
Application、Activity启动流程总结
从zygote
启动开始,到Activity
创建完成为止。
重要数据结构
AMS
涉及到的核心数据结构有ActivityRecord
、TaskRecord
和ActivityStack
,这几个数据结构构成了Activity体系的基本盘。
ActivityRecord
当Activity
启动时(ActivityStarter.startActivity()
)创建ActivityRecord
,它记录了Activity
的信息,每个Activity
都有一个ActivityRecord
。
成员名称 | 类型 | 说明 |
---|---|---|
mAtmervice | ActivityTaskManagerService | AMS 的引用 |
info | ActivityInfo | Activity 中代码和 AndroidManifes 设置的节点信息,比如 launchMode |
launchedFromPackage | String | 启动 Activity 的包名 |
taskAffinity | String | Activity 希望归属的栈 |
Task | TaskRecord | ActivityRecord 所在的 TaskRecord |
App | ProcessRecord | ActivityRecord 所在的应用程序进程 |
tate | ActivityState | 当前 Activity 的状态 |
icon | Int | Activity 的图标资源标识符 |
theme | Int | Activity 的主题资源标识符 |
ActivityRecord.java
private TaskRecord task; // the task this is in.
ActivityRecord
持有一个TaskRecord
的成员变量,是它自身所在的Task
对象,一个Activity
只能存在于一个Task
中。
TaskRecord
TaskRecord
用来描述Activity
的一个任务栈,从栈的维度记录相关信息,如标识符、倾向性(affinity
)、Activity
列表,其中有ActivityStack
类型的一个变量。
成员名称 | 类型 | 说明 |
---|---|---|
taskId | Int | 任务栈的唯一标识符 |
affinity | String | 任务栈的倾向性 |
intent | Intent | 启动这个任务栈的 Intent |
mActivities | ArrayList | 按照历史顺序排列的 Activity 记录 |
mStack | ActivityStack | 当前归属的 ActivityStack |
mService | ActivityTaskManagerService | AMS 的引用 |
ActivityStack
ActivityStack
是比较抽象的概念,它对ActivityRecord
、TaskRecord
进行管理,持有mTaskHistory
和mLRUActivities
两个列表。
ActivityStack.java
/**
* The back history of all previous (and possibly still
* running) activities. It contains #TaskRecord objects.
*/
private final ArrayList<TaskRecord> mTaskHistory = new ArrayList<>();
/**
* List of running activities, sorted by recent usage.
* The first entry in the list is the least recently used.
* It contains HistoryRecord objects.
*/
private final ArrayList<ActivityRecord> mLRUActivities = new ArrayList<>();
在AMS
的构造方法中,创建了ActivityStackSupervisor
,它用来管理多个ActivityStack
实例。
在 ActivityStack
中维护了很多 ArrayList
,这些ArrayList
中的元素类型主要有ActivityRecord
和 TaskRecord
, 如下所示:
ArrayList | 元素类型 | 说明 |
---|---|---|
mTaskHisttory | TaskRecord | 所有没有被销毁的 Activity 任务栈 |
mLRUActivities | ActivityRecord | 正在运行的 Activity ,列表中的第一个条目是最近最少使用的 Activity |
mNoAnimActivities | ActivityRecord | 不考虑转换动画的 Activity |
mValidateAppTokens | TaskGroup | 用于与窗口管理器验证应用令牌 |
Activity栈管理
Activity
任务栈模型由以上三个数据结构组成。