• 前序
    • 一个人知道自己为什么而活,便能忍受任何一种生活

参考博客

  本文中的所有内容大部分来源于网络资料,如有侵权请联系本人修改或删除,请大家多多支持原创!非常感谢!

ActivityManagerService

  Android系统非常庞大、错综复杂,其底层是采用Linux作为基底,上层采用包含虚拟机的Java层以及Native层,通过系统调用(Syscall)连接系统的内核空间与用户空间。用户空间主要采用C++和Java代码,通过JNI技术打通用户空间的Java层和Native层(C/C++)。Google官方提供了一张经典的四层架构图,从下往上依次分为Linux内核、系统库和Android运行时环境、框架层以及应用层这4层架构,其中每一层都包含了大量的子模块或子系统。

Android 架构

平台架构.png

  Android系统启动过程由上图从下网上的一个过程:Loader -> Kernel -> Native -> Framework -> App,接来写简要说说每个过程:

  • Loader层
    • Boot ROM:当手机处于关机状态时,长按Power键开机,引导芯片开始从固化在ROM里的预设出代码开始执行,然后加载引导程序到RAM;
    • Boot Loader:这是启动Android系统之前的引导程序,主要是检查RAM,初始化硬件参数等功能。
  • Kernel层
    • Kernel层是指Android内核层,到这里才刚刚开始进入Android系统。启动Kernel的swapper进程(pid=0):该进程又称为idle进程,系统初始化过程Kernel由无到有开创的第一个进程,用于初始化进程管理、内存管理,加载Display,Camera Driver, Binder Driver等相关工作;启动kthreadd进程(pid=2):是Linux系统的内核进程,会创建内核工作线程kworder,软中断线程ksoftirqd,thermal等内核守护进程。kthreadd进程是所有内核进程的鼻祖。
  • Native层
    • 这里的Native层主要包括init孵化来的用户空间的守护进程、HAL层以及开机动画等。启动init进程(pid=1),是Linux系统的用户进程,init进程是所有用户进程的鼻祖。
    • init进程会孵化出ueventd、logd、healthd、installd、add、lmkd等用户守护进程;init进程还启动servicemanager(binder服务管家)、bootanim(开机动画)等重要服务。init进程孵化出Zygote进程,Zygote进程是Android系统的第一个Java进程(即虚拟机进程),Zygote是所有Java进程的父进程,Zygote进程本身是由init进程孵化而来的。
  • Framework层
    • Zygote进程,是由init进程通过解析init.rc文件后fork生成的,Zygote进程主要包含:加载
      • ZygoteInit类,注册Zygote Socket服务端套接字
      • 加载虚拟机preloadClasses
      • preloadResource
    • System Server进程,是由Zygote进程fork而来,System Server是Zygote孵化的第一个进程,System Server负责启动和管理整个Java Framework,包括ActivityManager,PowerManager等服务。
    • Media Server进程,是由init进程fork而来,负责启动和管理整个C++ framework,包含AudioFlinger,Camera Service等服务
  • App层
    • Zygote进程孵化出的第一个App进程是Launcher,这是用户看到的桌面App
    • Zygote进程还会创建Browser, Phone,Email等App进程,每个App至少运行在一个进程上。所有的App进程都是由Zygote进程fork生成的。
  • Syscall && JNI
    • Native 与 Kernel 之间有一层系统调用(SysCall)层,见Linux系统调用(Syscall)原理
    • Java层与Native(C/C++)层之间的纽带JNI

启动过程

  • frameworks/base/services/java/com/android/server/SystemServer.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
//Line 1053
/**
* Starts the small tangle of critical services that are needed to get the system off the
* ground. These services have complex mutual dependencies which is why we initialize them all
* in one place here. Unless your service is also entwined in these dependencies, it should be
* initialized in one of the other functions.
*/
private void startBootstrapServices(@NonNull TimingsTraceAndSlog t) {
// more ...
// Activity manager runs the show.
t.traceBegin("StartActivityManager");
// TODO: Might need to move after migration to WM.
ActivityTaskManagerService atm = mSystemServiceManager.startService(
ActivityTaskManagerService.Lifecycle.class).getService();
mActivityManagerService = ActivityManagerService.Lifecycle.startService(
mSystemServiceManager, atm);
mActivityManagerService.setSystemServiceManager(mSystemServiceManager);
mActivityManagerService.setInstaller(installer);
mWindowManagerGlobalLock = atm.getGlobalLock();
t.traceEnd();
//more ...
}

  ActivityManagerService由SystemServer进程中启动。startBootstrapServices启动一些基础必要的系统服务,为后续系统正常运行做准备。在Android系统的启动过程中,各个系统服务需要按照一定的顺序进行初始化和启动。像源码中,会有t.traceBegin();和 t.traceEnd();这样对于服务启动的时间跟踪,测量和记录各个阶段的时间消耗,用于性能分析,调优和优化等。ActivityTaskManagerService(ATMS)是Android 10新增加的系统服务类,承担了ActivityManagerService(AMS)的部分工作(activies、task、stacks、displays相关),比如将Activity的启动相关的调用转移到了ATMS中。

  • ATMS的启动过程
  • frameworks/base/services/core/java/com/android/server/SystemServiceManager.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70

// Services that should receive lifecycle events.
private List<SystemService> mServices;
/**
* Creates and starts a system service. The class must be a subclass of
* {@link com.android.server.SystemService}.
*
* @param serviceClass A Java class that implements the SystemService interface.
* @return The service instance, never null.
* @throws RuntimeException if the service fails to start.
*/
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 servicSystemServicee " + 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) {
// Check if already started
String className = service.getClass().getName();
if (mServiceClassnames.contains(className)) {
Slog.i(TAG, "Not starting an already started service " + className);
return;
}
mServiceClassnames.add(className);

// 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");
}

  在SystemServiceManager.startService内部通过Cpnstructor构造器创建并且初始化ActivityTaskManagerService.Lifecycle实例,Lifecycle内部会创建ATMS实例,最终调用Lifecyle的onStart方法。内部类Lifecyle继承自SystemService,在其构造函数中创建了ActivityTaskManagerService对象,并在onStart中调用SystemService的publichBinderService将ATMS注册到ServiceManager中并调用ATMS的start方法,startService方法返回Lifecyle实例并通过getService()获取到了ATMS实例,

  • frameworks/base/services/core/java/com/android/server/wm/ActivityTaskManagerService.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
public static final class Lifecycle extends SystemService {
private final ActivityTaskManagerService mService;

public Lifecycle(Context context) {
super(context);
mService = new ActivityTaskManagerService(context);
}
@Override
public void onStart() {
publishBinderService(Context.ACTIVITY_TASK_SERVICE, mService);
mService.start();
}

@Override
public void onUserUnlocked(@NonNull TargetUser user) {
synchronized (mService.getGlobalLock()) {
mService.mTaskSupervisor.onUserUnlocked(user.getUserIdentifier());
}
}

@Override
public void onUserStopped(@NonNull TargetUser user) {
synchronized (mService.getGlobalLock()) {
mService.mTaskSupervisor.mLaunchParamsPersister
.onCleanupUser(user.getUserIdentifier());
}
}

public ActivityTaskManagerService getService() {
return mService;
}
}

  同样ActivityManager也有一个Lifecycle内部类调用其startService方法传递之前的ATMS实例atm以及SystemServiceManager实例,其后续流程跟ATMS类似,最终会启动ActivityManagerService。

  • frameworks/base/services/core/java/com/android/server/am/ActivityManagerService.java
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    // frameworks/base/services/java/com/android/server/SystemServer.java
    // line 1153
    // mActivityManagerService = ActivityManagerService.Lifecycle.startService(mSystemServiceManager, atm);
    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();
    }

    @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();
    } else if (phase == PHASE_ACTIVITY_MANAGER_READY) {
    mService.startBroadcastObservers();
    } else if (phase == PHASE_THIRD_PARTY_APPS_CAN_START) {
    mService.mPackageWatchdog.onPackagesReady();
    }
    }

    @Override
    public void onUserStopped(@NonNull TargetUser user) {
    mService.mBatteryStatsService.onCleanupUser(user.getUserIdentifier());
    }

    public ActivityManagerService getService() {
    return mService;
    }
    }

  ssm调用startService,同样反射调用ActivityManagerService构造方法,这里会调用ActivityTaskManagerService的initialize初始化安徽念书方法,传入Diplay线程的Looper。

  • frameworks/base/services/core/java/com/android/server/am/ActivityManagerService.java
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    64
    65
    66
    67
    68
    69
    70
    71
    72
    73
    74
    75
    76
    77
    78
    79
    80
    81
    82
    83
    84
    85
    86
    87
    88
    89
    90
    91
    92
    93
    94
    95
    96
    97
    98
    99
    100
    101
    102
    103
    104
    105
    106
    107
    108
    109
    110
    111
    112
    113
    114
    115
    116
    117
    118
    119
    120
    121
    122
    123
    124
    125
    126
    127
    128
    129
    130
    131
    132
    133
    134
    135
    136
    137
    138
    139
    140
    141
    142
    143
    144
    145
    146
    147
    148
    149
    150
    151
    152
    153
    154
    155
    156
    157
    158
    // 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, ActivityTaskManagerService atm) {
    LockGuard.installLock(this, LockGuard.INDEX_ACTIVITY);
    mInjector = new Injector(systemContext);
    //系统上下文
    mContext = systemContext;
    mFactoryTest = FactoryTest.getMode();
    // 标记当前进程的ActivityThread,当前进程也为AMS需要管理的一部分
    mSystemThread = ActivityThread.currentActivityThread();
    mUiContext = mSystemThread.getSystemUiContext();

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

    // 创建名为“ActivityManager”的线程,并指定优先级为前台
    // 这条线程是AMS主要工作线程
    mHandlerThread = new ServiceThread(TAG,
    THREAD_PRIORITY_FOREGROUND, false /*allowIo*/);
    mHandlerThread.start();
    mHandler = new MainHandler(mHandlerThread.getLooper());
    mUiHandler = mInjector.getUiHandler(this);

    // 创建名为“ActivityManger:procStart”的线程,并指定优先级为前台
    // 这条线程处理进程启动相关
    mProcStartHandlerThread = new ServiceThread(TAG + ":procStart",
    THREAD_PRIORITY_FOREGROUND, false /* allowIo */);
    mProcStartHandlerThread.start();
    mProcStartHandler = new ProcStartHandler(this, mProcStartHandlerThread.getLooper());

    //初始化一些常量
    mConstants = new ActivityManagerConstants(mContext, this, mHandler);
    final ActiveUids activeUids = new ActiveUids(this, true /* postChangesToAtm */);
    mPlatformCompat = (PlatformCompat) ServiceManager.getService(
    Context.PLATFORM_COMPAT_SERVICE);
    //管理进程相关
    mProcessList = mInjector.getProcessList(this);
    mProcessList.init(this, activeUids, mPlatformCompat);
    //低内存检测,内部通过一个线程接收内核PSI机制epoll过来的地内存通知
    mAppProfiler = new AppProfiler(this, BackgroundThread.getHandler().getLooper(),
    new LowMemDetector(this));
    mPhantomProcessList = new PhantomProcessList(this);
    //进程优先级(oom_adj)相关的类
    mOomAdjuster = new OomAdjuster(this, mProcessList, activeUids);

    //广播政策相关的参数
    // Broadcast policy parameters
    final BroadcastConstants foreConstants = new BroadcastConstants(
    Settings.Global.BROADCAST_FG_CONSTANTS);

    //前台广播 10S
    foreConstants.TIMEOUT = BROADCAST_FG_TIMEOUT;

    final BroadcastConstants backConstants = new BroadcastConstants(
    Settings.Global.BROADCAST_BG_CONSTANTS);
    //后台广播60S
    backConstants.TIMEOUT = BROADCAST_BG_TIMEOUT;

    final BroadcastConstants offloadConstants = new BroadcastConstants(
    Settings.Global.BROADCAST_OFFLOAD_CONSTANTS);
    //延时广播 60S
    offloadConstants.TIMEOUT = BROADCAST_BG_TIMEOUT;
    // by default, no "slow" policy in this queue
    offloadConstants.SLOW_TIME = Integer.MAX_VALUE;

    mEnableOffloadQueue = SystemProperties.getBoolean(
    "persist.device_config.activity_manager_native_boot.offload_queue_enabled", true);
    mEnableModernQueue = foreConstants.MODERN_QUEUE_ENABLED;

    if (mEnableModernQueue) {
    mBroadcastQueues = new BroadcastQueue[1];
    mBroadcastQueues[0] = new BroadcastQueueModernImpl(this, mHandler,
    foreConstants, backConstants);
    } else {
    //为三种广播创建对应的队列
    mBroadcastQueues = new BroadcastQueue[4];
    mBroadcastQueues[BROADCAST_QUEUE_FG] = new BroadcastQueueImpl(this, mHandler,
    "foreground", foreConstants, false, ProcessList.SCHED_GROUP_DEFAULT);
    mBroadcastQueues[BROADCAST_QUEUE_BG] = new BroadcastQueueImpl(this, mHandler,
    "background", backConstants, true, ProcessList.SCHED_GROUP_BACKGROUND);
    mBroadcastQueues[BROADCAST_QUEUE_BG_OFFLOAD] = new BroadcastQueueImpl(this, mHandler,
    "offload_bg", offloadConstants, true, ProcessList.SCHED_GROUP_BACKGROUND);
    mBroadcastQueues[BROADCAST_QUEUE_FG_OFFLOAD] = new BroadcastQueueImpl(this, mHandler,
    "offload_fg", foreConstants, true, ProcessList.SCHED_GROUP_BACKGROUND);
    }
    //管理Service组件
    mServices = new ActiveServices(this);
    //管理ContentProvider组件
    mCpHelper = new ContentProviderHelper(this, true);
    mPackageWatchdog = PackageWatchdog.getInstance(mUiContext);
    mAppErrors = new AppErrors(mUiContext, this, mPackageWatchdog);
    mUidObserverController = new UidObserverController(mUiHandler);

    //创建/data/system目录
    final File systemDir = SystemServiceManager.ensureSystemDir();

    // TODO: Move creation of battery stats service outside of activity manager service.
    // 电池状态统计服务的初始化
    mBatteryStatsService = BatteryStatsService.create(systemContext, systemDir,
    BackgroundThread.getHandler(), this);
    mOnBattery = DEBUG_POWER ? true
    : mBatteryStatsService.getActiveStatistics().getIsOnBattery();
    mOomAdjProfiler.batteryPowerChanged(mOnBattery);

    //进程状态统计服务初始化
    mProcessStats = new ProcessStatsService(this, new File(systemDir, "procstats"));

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

    mUgmInternal = LocalServices.getService(UriGrantsManagerInternal.class);

    mUserController = new UserController(this);
    mInjector.mUserController = mUserController;

    mPendingIntentController = new PendingIntentController(
    mHandlerThread.getLooper(), mUserController, mConstants);

    mAppRestrictionController = new AppRestrictionController(mContext, this);

    mUseFifoUiScheduling = SystemProperties.getInt("sys.use_fifo_ui", 0) != 0;

    mTrackingAssociations = "1".equals(SystemProperties.get("debug.track-associations"));
    mIntentFirewall = new IntentFirewall(new IntentFirewallInterface(), mHandler);

    //初始化ATMS
    mActivityTaskManager = atm;
    mActivityTaskManager.initialize(mIntentFirewall, mPendingIntentController,
    DisplayThread.get().getLooper());
    mAtmInternal = LocalServices.getService(ActivityTaskManagerInternal.class);

    //HiddenApi黑名单列表
    mHiddenApiBlacklist = new HiddenApiSettings(mHandler, mContext);

    //监听AMS和其工作线程的状态,例如阻塞、死锁等
    Watchdog.getInstance().addMonitor(this);
    Watchdog.getInstance().addThread(mHandler);

    // bind background threads 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(OOM_ADJ_REASON_SYSTEM_INIT);
    try {
    Process.setThreadGroupAndCpuset(BackgroundThread.get().getThreadId(),
    Process.THREAD_GROUP_SYSTEM);
    Process.setThreadGroupAndCpuset(
    mOomAdjuster.mCachedAppOptimizer.mCachedAppOptimizerThread.getThreadId(),
    Process.THREAD_GROUP_SYSTEM);
    } catch (Exception e) {
    Slog.w(TAG, "Setting background thread cpuset failed");
    }

    mInternal = new LocalService();
    mPendingStartActivityUids = new PendingStartActivityUids();
    mTraceErrorLogger = new TraceErrorLogger();
    mComponentAliasResolver = new ComponentAliasResolver(this);
    }

  可以看到AMS首先创建了两条线程,其中一条作为自己的主要工作线程,接着围绕四大组件的管理做初始化工作。对于Activity的管理工作全部转移到ATMS中,因此这里了调用了ATMS的initialize方法初始化ATMS。

  对于Service,创建了ActiveServie类管理。并且可以在frameworks/base/services/core/java/com/android/server/am/ActivityManagerConstants.java看到Service的超时时间。

  对于ContentProvider,创建了ContentProviderHelper来管理,在SystemServer中对应的数据结构是ContentProciderRecord。

  对于广播Brodcast,创建了三个广播队列来分别管理三种广播类型。除了四大组件,初始化中还涉及一些性能相关,例如:

  • 初始化ProcessList

  • 创建LowMemDetextor用于检测低内存

  • 创建OomAdjuster用于调整进程的优先级等级

  • 创建BatteryStatsService和ProcessStatsService用于管理电量状态和进程状态

  • 创建HiddenApiSettings用于管理一些需要对开发者隐藏的HiddenApi

  • frameworks/base/services/core/java/com/android/server/am/ActivityManagerService.java

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    private void start() {
    mBatteryStatsService.publish();
    mAppOpsService.publish();
    mProcessStats.publish();
    Slog.d("AppOps", "AppOpsService published");
    //将LocalService添加到本地服务列表
    LocalServices.addService(ActivityManagerInternal.class, mInternal);
    //添加管理
    LocalManagerRegistry.addManager(ActivityManagerLocal.class,
    (ActivityManagerLocal) mInternal);
    //通知UGM,AMS已经启动,可以获取到AMS
    mActivityTaskManager.onActivityManagerInternalAdded();
    //通知PendingIntentController,AMS已经启动,可以获取到AMS
    mPendingIntentController.onActivityManagerInternalAdded();
    mAppProfiler.onActivityManagerInternalAdded();
    CriticalEventLog.init();
    }

  initialize()方法会初始化一些对象实例,比如ActivityTaskSupervisor、ActivityStartController等,会涉及到Activity的启动以及Activity栈的一些逻辑。ActivityTaskSupervisor负责管理ActivityStack,ActivityStartController创建将自身ATMS传入,主要负责Activity启动相关工作。例如在startActivityAsUser通过getActivityStartController().obtainStarter(…)获取到ActivityStarter并执行后续的启动工作。

  • frameworks/base/services/core/java/com/android/server/wm/ActivityTaskManagerService.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
public void initialize(IntentFirewall intentFirewall, PendingIntentController intentController,
Looper looper) {
mH = new H(looper);
mUiHandler = new UiHandler();
mIntentFirewall = intentFirewall;
final File systemDir = SystemServiceManager.ensureSystemDir();
mAppWarnings = createAppWarnings(mUiContext, mH, mUiHandler, systemDir);
mCompatModePackages = new CompatModePackages(this, systemDir, mH);
mPendingIntentController = intentController;
mTaskSupervisor = createTaskSupervisor();
mActivityClientController = new ActivityClientController(this);

mTaskChangeNotificationController =
new TaskChangeNotificationController(mTaskSupervisor, mH);
mLockTaskController = new LockTaskController(mContext, mTaskSupervisor, mH,
mTaskChangeNotificationController);
mActivityStartController = new ActivityStartController(this);
setRecentTasks(new RecentTasks(this, mTaskSupervisor));
mVrController = new VrController(mGlobalLock);
mKeyguardController = mTaskSupervisor.getKeyguardController();
mPackageConfigPersister = new PackageConfigPersister(mTaskSupervisor.mPersisterQueue, this);
}

  ActiivtyManagerService在启动应用时会检查应用的进程是否存在,若不存在,AMS会请求Zygote进程创建需要的应用程序进程。

与ActivityManagerService相关的数据结构类

ActivityRecord

  • frameworks/base/services/core/java/com/android/server/wm/ActivityRecord.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
final class ActivityRecord extends WindowToken implements WindowManagerService.AppFreezeListener {
private static final String TAG = TAG_WITH_CLASS_NAME ? "ActivityRecord" : TAG_ATM;
private static final String TAG_ADD_REMOVE = TAG + POSTFIX_ADD_REMOVE;
private static final String TAG_APP = TAG + POSTFIX_APP;
private static final String TAG_CONFIGURATION = TAG + POSTFIX_CONFIGURATION;
private static final String TAG_CONTAINERS = TAG + POSTFIX_CONTAINERS;
private static final String TAG_FOCUS = TAG + POSTFIX_FOCUS;
private static final String TAG_PAUSE = TAG + POSTFIX_PAUSE;
private static final String TAG_RESULTS = TAG + POSTFIX_RESULTS;
private static final String TAG_SAVED_STATE = TAG + POSTFIX_SAVED_STATE;
private static final String TAG_STATES = TAG + POSTFIX_STATES;
private static final String TAG_SWITCH = TAG + POSTFIX_SWITCH;
private static final String TAG_TRANSITION = TAG + POSTFIX_TRANSITION;
private static final String TAG_USER_LEAVING = TAG + POSTFIX_USER_LEAVING;
private static final String TAG_VISIBILITY = TAG + POSTFIX_VISIBILITY;

private static final String ATTR_ID = "id";
private static final String TAG_INTENT = "intent";
private static final String ATTR_USERID = "user_id";
private static final String TAG_PERSISTABLEBUNDLE = "persistable_bundle";
private static final String ATTR_LAUNCHEDFROMUID = "launched_from_uid";
private static final String ATTR_LAUNCHEDFROMPACKAGE = "launched_from_package";
private static final String ATTR_LAUNCHEDFROMFEATURE = "launched_from_feature";
private static final String ATTR_RESOLVEDTYPE = "resolved_type";
private static final String ATTR_COMPONENTSPECIFIED = "component_specified";
static final String ACTIVITY_ICON_SUFFIX = "_activity_icon_";

// How many activities have to be scheduled to stop to force a stop pass.
private static final int MAX_STOPPING_TO_FORCE = 3;

static final int STARTING_WINDOW_TYPE_NONE = 0;
static final int STARTING_WINDOW_TYPE_SNAPSHOT = 1;
static final int STARTING_WINDOW_TYPE_SPLASH_SCREEN = 2;

static final int INVALID_PID = -1;

// How long we wait until giving up on the last activity to pause. This
// is short because it directly impacts the responsiveness of starting the
// next activity.
private static final int PAUSE_TIMEOUT = 500;

// Ticks during which we check progress while waiting for an app to launch.
private static final int LAUNCH_TICK = 500;

// How long we wait for the activity to tell us it has stopped before
// giving up. This is a good amount of time because we really need this
// from the application in order to get its saved state. Once the stop
// is complete we may start destroying client resources triggering
// crashes if the UI thread was hung. We put this timeout one second behind
// the ANR timeout so these situations will generate ANR instead of
// Surface lost or other errors.
private static final int STOP_TIMEOUT = 11 * 1000;

// How long we wait until giving up on an activity telling us it has
// finished destroying itself.
private static final int DESTROY_TIMEOUT = 10 * 1000;

// Rounding tolerance to be used in aspect ratio computations
private static final float ASPECT_RATIO_ROUNDING_TOLERANCE = 0.005f;

final ActivityTaskManagerService mAtmService;
@NonNull
final ActivityInfo info; // activity info provided by developer in AndroidManifest
// Which user is this running for?
final int mUserId;
// The package implementing intent's component
// TODO: rename to mPackageName
final String packageName;
// the intent component, or target of an alias.
final ComponentName mActivityComponent;
// Input application handle used by the input dispatcher.
private InputApplicationHandle mInputApplicationHandle;

final int launchedFromPid; // always the pid who started the activity.
final int launchedFromUid; // always the uid who started the activity.
final String launchedFromPackage; // always the package who started the activity.
@Nullable
final String launchedFromFeatureId; // always the feature in launchedFromPackage
private final int mLaunchSourceType; // original launch source type
final Intent intent; // the original intent that generated us
final String shortComponentName; // the short component name of the intent
final String resolvedType; // as per original caller;
final String processName; // process where this component wants to run
final String taskAffinity; // as per ActivityInfo.taskAffinity
final boolean stateNotNeeded; // As per ActivityInfo.flags
@VisibleForTesting
int mHandoverLaunchDisplayId = INVALID_DISPLAY; // Handover launch display id to next activity.
@VisibleForTesting
TaskDisplayArea mHandoverTaskDisplayArea; // Handover launch task display area.
private final boolean componentSpecified; // did caller specify an explicit component?
final boolean rootVoiceInteraction; // was this the root activity of a voice interaction?

private CharSequence nonLocalizedLabel; // the label information from the package mgr.
private int labelRes; // the label information from the package mgr.
private int icon; // resource identifier of activity's icon.
private int theme; // resource identifier of activity's theme.
private Task task; // the task this is in.
private long createTime = System.currentTimeMillis();
long lastVisibleTime; // last time this activity became visible
long pauseTime; // last time we started pausing the activity
long launchTickTime; // base time for launch tick messages
long topResumedStateLossTime; // last time we reported top resumed state loss to an activity
// Last configuration reported to the activity in the client process.
private MergedConfiguration mLastReportedConfiguration;
private int mLastReportedDisplayId;
boolean mLastReportedMultiWindowMode;
boolean mLastReportedPictureInPictureMode;
ActivityRecord resultTo; // who started this entry, so will get our reply
final String resultWho; // additional identifier for use by resultTo.
final int requestCode; // code given by requester (resultTo)
ArrayList<ResultInfo> results; // pending ActivityResult objs we have received
HashSet<WeakReference<PendingIntentRecord>> pendingResults; // all pending intents for this act
ArrayList<ReferrerIntent> newIntents; // any pending new intents for single-top mode
Intent mLastNewIntent; // the last new intent we delivered to client
/** The most recently given options. */
private ActivityOptions mPendingOptions;
/** Non-null if {@link #mPendingOptions} specifies the remote animation. */
RemoteAnimationAdapter mPendingRemoteAnimation;
private RemoteTransition mPendingRemoteTransition;
ActivityOptions returningOptions; // options that are coming back via convertToTranslucent
AppTimeTracker appTimeTracker; // set if we are tracking the time in this app/task/activity
@GuardedBy("this")
ActivityServiceConnectionsHolder mServiceConnectionsHolder; // Service connections.
/** @see android.content.Context#BIND_ADJUST_WITH_ACTIVITY */
volatile boolean mVisibleForServiceConnection;
UriPermissionOwner uriPermissions; // current special URI access perms.
WindowProcessController app; // if non-null, hosting application
private State mState; // current state we are in
private Bundle mIcicle; // last saved activity state
private PersistableBundle mPersistentState; // last persistently saved activity state
private boolean mHaveState = true; // Indicates whether the last saved state of activity is
// preserved. This starts out 'true', since the initial state
// of an activity is that we have everything, and we should
// never consider it lacking in state to be removed if it
// dies. After an activity is launched it follows the value
// of #mIcicle.
boolean launchFailed; // set if a launched failed, to abort on 2nd try
boolean delayedResume; // not yet resumed because of stopped app switches?
boolean finishing; // activity in pending finish list?
boolean deferRelaunchUntilPaused; // relaunch of activity is being deferred until pause is
// completed
boolean preserveWindowOnDeferredRelaunch; // activity windows are preserved on deferred relaunch
int configChangeFlags; // which config values have changed
private boolean keysPaused; // has key dispatching been paused for it?
int launchMode; // the launch mode activity attribute.
int lockTaskLaunchMode; // the lockTaskMode manifest attribute, subject to override
private boolean mVisible; // Should this token's windows be visible?
boolean visibleIgnoringKeyguard; // is this activity visible, ignoring the fact that Keyguard
// might hide this activity?
// True if the visible state of this token was forced to true due to a transferred starting
// window.
private boolean mVisibleSetFromTransferredStartingWindow;
// TODO: figure out how to consolidate with the same variable in ActivityRecord.
private boolean mDeferHidingClient; // If true we told WM to defer reporting to the client
// process that it is hidden.
private boolean mLastDeferHidingClient; // If true we will defer setting mClientVisible to false
// and reporting to the client that it is hidden.
boolean nowVisible; // is this activity's window visible?
boolean mClientVisibilityDeferred;// was the visibility change message to client deferred?
boolean idle; // has the activity gone idle?
boolean hasBeenLaunched;// has this activity ever been launched?
boolean frozenBeforeDestroy;// has been frozen but not yet destroyed.
boolean immersive; // immersive mode (don't interrupt if possible)
boolean forceNewConfig; // force re-create with new config next time
boolean supportsEnterPipOnTaskSwitch; // This flag is set by the system to indicate that the
// activity can enter picture in picture while pausing (only when switching to another task)
PictureInPictureParams pictureInPictureArgs = new PictureInPictureParams.Builder().build();
// The PiP params used when deferring the entering of picture-in-picture.
boolean shouldDockBigOverlays;
int launchCount; // count of launches since last state
long lastLaunchTime; // time of last launch of this activity
ComponentName requestedVrComponent; // the requested component for handling VR mode.

/** Whether this activity is reachable from hierarchy. */
volatile boolean inHistory;
final ActivityTaskSupervisor mTaskSupervisor;
final RootWindowContainer mRootWindowContainer;
// The token of the TaskFragment that this activity was requested to be launched into.
IBinder mRequestedLaunchingTaskFragmentToken;

// Tracking splash screen status from previous activity
boolean mSplashScreenStyleSolidColor = false;

Drawable mEnterpriseThumbnailDrawable;

boolean mPauseSchedulePendingForPip = false;

// Gets set to indicate that the activity is currently being auto-pipped.
boolean mAutoEnteringPip = false;

private void updateEnterpriseThumbnailDrawable(Context context) {
DevicePolicyManager dpm = context.getSystemService(DevicePolicyManager.class);
mEnterpriseThumbnailDrawable = dpm.getResources().getDrawable(
WORK_PROFILE_ICON, OUTLINE, PROFILE_SWITCH_ANIMATION,
() -> context.getDrawable(R.drawable.ic_corp_badge));
}

static final int LAUNCH_SOURCE_TYPE_SYSTEM = 1;
static final int LAUNCH_SOURCE_TYPE_HOME = 2;
static final int LAUNCH_SOURCE_TYPE_SYSTEMUI = 3;
static final int LAUNCH_SOURCE_TYPE_APPLICATION = 4;

enum State {
INITIALIZING,
STARTED,
RESUMED,
PAUSING,
PAUSED,
STOPPING,
STOPPED,
FINISHING,
DESTROYING,
DESTROYED,
RESTARTING_PROCESS
}
//more ....
}
mAtmService ActivityTaskManagerService ATMS的引用
appToken Token(IBinder) IBinder对象,用于WMS关联Window与Activity
launchedFromPackage String 启动Activity的包名
taskAffinity String Activity希望归属的栈
intent Intent 当前启动Activity的Intent对象
aInfo ActivityInfo 由AndroidManifest解析出来的Activity信息,包括launchMode、icon、theme、taskAffinity等
task TaskRecord 当前所属TaskRecord对象
appInfo ApplicationInfo 当前所属Application信息
state ActivityState 当前 Activity 的状态
supervisor ActivityStackSupervisor Android中管理Display与ActivityStack的类
icon int Activity的图标资源标识符,随ActivityInfo传入
theme int Activity的主题资源标识符,随ActivityInfo传入
名 称 类 型 说 明

  可以看到,TaskRecord内部存储了任务栈的所有信息,包括任务栈的唯一标识符、任务栈的倾向性、任务栈中的ActivityRecord、ActivityStack和ATMS应用等。从mActivities集合中了解TaskRecord与ActivityRecord是包含与被包含的关系,这里TaskRecord又持有一个ActivityStack的引用,通常在开发App中必然会用到启动模式和Flag,其中singleInstance启动模式或者FLAG_ACTIVITY_NEW_TASK都可以在启动Activity时创建一个新的任务栈。而一个任务栈就对应一个TaskRecord对象,那么存在一个问题就是如何管理这么多TaskRecoed?ActivityStack就是TaskRecord的管理者。

Launch Mode

  • standerd:默认模式,每次启动Activity都会创建一个新的Activity实例
  • singleTop:如果要启动的Activity已经在栈顶,则不会重新创建Activity,同时该Activity的onNewIntent方法会被调用(如果需要传递新的intent必须使用setIntent进行更新)
  • singleTask:如果要启动的Activity已经存在于它想要归属的栈中,那么不会创建该Activity实例,将栈中位于该Activity上的所有的Activity出栈,同时该Activity的onNewIntent方法会被调用。如果要启动的Activity不存在于它想要归属的栈中,并且该栈存在,则会重新创建该Activity的实例。如果要启动的Activity想要归属的栈不存在,则首先要创建一个新栈,然后创建该Activity实例并压入到新栈中。
  • singleInstancee:和singleTask基本类似,不同的是启动Activity时,首先要创建一个新栈,然后创建该Activity实例并压入到新栈中,此栈只会存在这一个Activity实例

Intent的FLAG

  如果FLAG和App的LaunchMode冲突,会执行Flag,对生命周期和Task/Back Stack有影响的Intent Flag主要有

  • FLAG_ACTIVITY_NEW_TASK

    • 会产生与“singleTask”相同的行为
    • 在新任务中启动Activity。如果已有包含该Activity的任务,则该任务会转到前台并恢复其最后状态,同时该Activity会在onNewIntent()中收到新Intent
  • FLAG_ACTIVITY_SINGLE_TOP

    • 会产生与“singleTop”相同的行为
    • 如果正在启动的Activity是当前Activity(位于返回栈的顶部),则现有实例会接收对onNewIntent()的调用,而不是创建Activity的新实例
  • FLAG_ACTIVITY_CLEAR_TOP

    • 如果正在启动的Activity已经在担负前任务中运行,则会销毁当前任务顶部的所有Activity,并通过onNewIntent()将此Intent传递Activity已恢复的实例(现在位于顶部),而不是启动该Activity的新实例
    • 如果指定Activity的启动模式为“standard”,则该Activity也会从堆栈中删除,并在其位置启动一个新实例,以便处理传入的Intent。这是因为启动模式为“standard”时,将始终为新Intent创建新实例。