最近以Android-28为基础,梳理了一下Activity的启动过程,在此做一些学习笔记。方便需要时查阅。
此次主要关注"从Laucher点击一个app图标A ,到A 启动Application和Activity"的过程
一、Activity启动前的进程关系
- init进程:init是所有linux程序的起点,是Zygote的父进程。解析init.rc孵化出Zygote进程。
- Zygote进程:Zygote是所有Java进程的父进程,所有的App进程都是由Zygote进程fork生成的。
- SystemServer进程:System Server是Zygote孵化的第一个进程。SystemServer负责启动和管理整个Java framework,包含AMS,PMS等服务。
- Launcher:Zygote进程孵化的第一个App进程是Launcher
1.1、什么是init进程
Android是基于linux系统的,手机开机之后,linux内核进行加载。加载完成之后会启动init进程。
init进程会启动ServiceManager,孵化一些守护进程,并解析init.rc孵化Zygote进程。
1.2、Zygote进程
所有的App进程都是由Zygote进程fork生成的,包括SystemServer进程。
Zygote初始化后,会注册一个等待接受消息的socket,OS层会采用socket进行IPC通信。
1.3、为什么是Zygote来孵化进程,而不是新建进程呢?
每个应用程序都是运行在各自的Dalvik虚拟机中,应用程序每次运行都要重新初始化和启动虚拟机,这个过程会耗费很长时间。Zygote会把已经运行的虚拟机的代码和内存信息共享。起到一个预加载资源和类的作用,从而缩短启动时间。
二、Activity启动涉及到的一些类:
2.1、ActivityRecord
ActivityRecord是Activity在system_server进程中的镜像,Activity实例与ActivityRecord实例一一对应。ActivityRecord用来存储Activity的信息,如所在的进程名称,应用的包名,所在的任务栈的taskAffinity等。
/**
* An entry in the history stack, representing an activity.
*/
final class ActivityRecord {
final ComponentName realActivity; // the intent component, or target of an alias.
final String shortComponentName; // the short component name of the intent
final String packageName; // the package implementing intent's component
final String processName; // process where this component wants to run
final String taskAffinity; // as per ActivityInfo.taskAffinity
boolean fullscreen; // covers the full screen?
}
2.2、TaskRecord
TaskRecord表示任务栈,是真正的一个先进后出的栈结构,用于记录activity开启的先后顺序。其所存放的Activity是不支持重新排序的,只能根据压栈和出栈操作更改Activity的顺序。有了TaskRecord,Android系统才能知道当一个Activity退出时,接下来该显示哪一个Activity。
final class TaskRecord {
/** List of all activities in the task arranged in history order */
final ArrayList<ActivityRecord> mActivities;
}
2.3、ActivityStack
ActivityStack 是TaskRecord的一个分组,用于管理TaskRecord列表,列表中的TaskRecord可以重排顺序。
final class ActivityStack {
/**
* The back history of all previous (and possibly still
* running) activities. It contains #TaskRecord objects.
*/
private ArrayList<TaskRecord> mTaskHistory = new ArrayList<>();
}
2.3.1 TaskRecord、ActivityStack关系。
通常情况下,一个App对应一个ActivityStack,ActivityStatck中会有一个TaskRecord列表,通常列表中仅有一个TaskRecord,维护Activity栈。
一个Activity启动时,归属的TaskRecord,通常是启动它的Activity 对应的TaskRecord。
如ActivtiyA启动ActivityB,那么ActivityB会被保存在ActivityA所属的TaskRecord中。
当一个Activity的launchmode 设置了SingleIntance,那么它启动的时候就会新建一个TaskRecord,这时ActvityStack中就会存在多个TaskRecord 栈结构。
当设置了Intent.FLAG_ACTIVITY_NEW_TASK和taskAffinity时,可能会出现多个app共享同一个ActivityStack的情况。
taskAffinity 可以指定Activity需要宿主TaskRecord的名字,当ActivityManagerService发现启动了一个带有 FLAG_ACTIVITY_NEW_TASK 标签的 Activity 时,会先去查找当前AMS中是否存在activity需要的ActivityStack和TaskRecord,如果存在则直接将ActivityRecord添加到对应ActivityStack的TaskRecord中去,否则会先新建一个TaskRecord,然后将ActvityRecord添加到新建的TaskRecord中。
adb shell dumpsys activity 查看activity栈的请款
ACTIVITY MANAGER ACTIVITIES (dumpsys activity activities)
Display #0 (activities from top to bottom):
Stack #1:
TaskRecord{4212758 #173 A=com.sogou.iot.testtouch1 U=0 StackId=1 sz=2}
Intent { act=android.intent.action.MAIN cat=[android.intent.category.LAUNCHER] flg=0x10200000 cmp=com.sogou.iot.testtouch1/.MainActivity }
Hist #1: ActivityRecord{4c91dda u0 com.sogou.iot.testtouch1/.SecondActivity t173}
Intent { cmp=com.sogou.iot.testtouch1/.SecondActivity }
ProcessRecord{3fd8bbc 23189:com.sogou.iot.testtouch1/u0a79}
Hist #0: ActivityRecord{93a3d53 u0 com.sogou.iot.testtouch1/.MainActivity t173}
Intent { act=android.intent.action.MAIN cat=[android.intent.category.LAUNCHER] flg=0x10200000 cmp=com.sogou.iot.testtouch1/.MainActivity bnds=[433,77][644,372] }
ProcessRecord{3fd8bbc 23189:com.sogou.iot.testtouch1/u0a79}
Running activities (most recent first):
TaskRecord{4212758 #173 A=com.sogou.iot.testtouch1 U=0 StackId=1 sz=2}
Run #1: ActivityRecord{4c91dda u0 com.sogou.iot.testtouch1/.SecondActivity t173}
Run #0: ActivityRecord{93a3d53 u0 com.sogou.iot.testtouch1/.MainActivity t173}
mResumedActivity: ActivityRecord{4c91dda u0 com.sogou.iot.testtouch1/.SecondActivity t173}
Stack #0:
TaskRecord{db2272c #1 A=com.huawei.android.launcher U=0 StackId=0 sz=1}
Intent { act=android.intent.action.MAIN cat=[android.intent.category.HOME] flg=0x10000300 cmp=com.huawei.android.launcher/.unihome.UniHomeLauncher }
Hist #0: ActivityRecord{60dec4e u0 com.huawei.android.launcher/.unihome.UniHomeLauncher t1}
Intent { act=android.intent.action.MAIN cat=[android.intent.category.HOME] flg=0x10000300 cmp=com.huawei.android.launcher/.unihome.UniHomeLauncher }
ProcessRecord{c03fa2 1781:com.huawei.android.launcher/u0a50}
Running activities (most recent first):
TaskRecord{db2272c #1 A=com.huawei.android.launcher U=0 StackId=0 sz=1}
Run #0: ActivityRecord{60dec4e u0 com.huawei.android.launcher/.unihome.UniHomeLauncher t1}
Stack #0: 代表一个ActivityStack, id = 0 说明是Launcher相关的ActivitStack。
Stack #1: ActivityStack id = 1 ,代表常规App的ActvityStack,其中存在一个TaskRecord栈,栈中有两个ActivityRecord (MainActivity和SecondActivity),SecondeActivity在栈顶,处于Resume状态
2.4、ActivityStackSupervisor
ActivityStackSupervisor是ActivityStack的管理者。
内部管理了mHomeStack、mFocusedStack和mLastFocusedStack三个ActivityStack。
其中,mHomeStack管理的是Launcher相关的Activity栈,stackId为0;
mFocusedStack管理的是当前显示在前台Activity的Activity栈;
mLastFocusedStack管理的是上一次显示在前台Activity的Activity栈。
ActivityDisplay表示一个屏幕,Android支持三种屏幕:主屏幕,外接屏幕(HDMI等),虚拟屏幕(投屏)。一般情况下,即只有主屏幕时,ActivityStackSupervisor与ActivityDisplay都是系统唯一;
ActivityDisplay是ActivityStackSupervisor的内部类,它相当于一个工具类,封装了移除和添加ActivityStack的方法。
2.5 ActivityThread:
ActivityThread 运行在UI线程(主线程),App的真正入口。
2.6 ApplicationThread
ApplicationThread是一个Binder类,即可实现跨进程通信。主要用于接受从AMS传递过来的IPC消息,继而做相应处理。
private class ApplicationThread extends IApplicationThread.Stub{
}
2.7 IActivityManager
继承与IInterface接口,用于app进程向ActivityManagerService 单向IPC通信
2.8、Instrumentation
仪表盘,负责调用Activity和Application生命周期,测试用到这个类比较多。
三、具体的启动过程
3.1、流程概述
- Launcher:Launcher通知AMS要启动activity
- startActivitySafely->startActivity->Instrumentation.execStartActivity()(AMP.startActivity)->AMS.startActivity
- ActivitMapagerService:PackageManagerService的resoveIntent验证要启动activity是否匹配。
- 如果匹配,通过ApplicationThread发消息给Launcher所在的主线程,暂停当前Activity(Launcher);
- 暂停完,在该activity还不可见时,通知AMS,根据要启动的Activity配置ActivityStack。然后判断要启动的Activity进程是否存在?
- 存在:发送消息LAUNCH_ACTIVITY给需要启动的Activity主线程,执行handleLaunchActivity
- 不存在:通过socket向zygote请求创建进程。进程启动后,ActivityThread.attach
- 判断Application是否存在,若不存在,通过LoadApk.makeApplication创建一个。在主线程中通过thread.attach方法来关联ApplicationThread。
- 在通过ActivityStackSupervisor来获取当前需要显示的ActivityStack。
- 继续通过ApplicationThread来发送消息给主线程的Handler来启动Activity(handleLaunchActivity)
- handleLauchActivity:调用了performLauchActivity,里边Instrumentation生成了新的activity对象,继续调用activity生命周期。
3.2、流程跟踪
阶段一:Launcher通知AMS要启动新的Activity(在Launcher所在的进程执行)
- Activity.startActivity
- Activity.startActivityForResult
- Instrumentation.execStartActivity //交由Instrumentation代为发起请求
- ActivityManager.getService().startActivity //通过IActivityManagerSingleton.get()得到一个AMP代理对象
- ActivityManagerService.startActivity()
阶段二:AMS先校验一下Activity的正确性,如果正确的话,会暂存一下Activity的信息。然后AMS会通知Launcher程序pause Activity(在AMS所在进程执行)
- ActivityManagerService.startActivity
- ActivityManagerService.startActivityAsUser
- ActivityStackSupervisor.startActivityMayWait
- ActivityStarter.startActivityUnchecked
- ActivityStarter.startActivity
- ActivityStarter.startActivityUnchecked
- ActivityStack.startActivityLocked
- ActivityStackSupervisor.resumeFocusedStackTopActivityLocked
- ActivityStack.resumeTopActivityUncheckedLocked
- ActivityStack.resumeTopActivityInnerLocked
private boolean resumeTopActivityInnerLocked(ActivityRecord prev, ActivityOptions options){
if (mResumedActivity != null) {
if (DEBUG_STATES) Slog.d(TAG_STATES,
"resumeTopActivityLocked: Pausing " + mResumedActivity);
pausing |= startPausingLocked(userLeaving, false, next, false);
}
}
- ActivityStack.startPausingLocked
if (prev.app != null && prev.app.thread != null) {
mService.getLifecycleManager().scheduleTransaction(prev.app.thread, prev.appToken,
PauseActivityItem.obtain(prev.finishing, userLeaving,
prev.configChangeFlags, pauseImmediately)
);
}
PauseActivityItem 为暂停Activity的一个ClientTransactionItem 事务,AMS对Activity的操作都封装成了事务来完成。
public class PauseActivityItem extends ActivityLifecycleItem {
private static final String TAG = "PauseActivityItem";
private boolean mFinished;
private boolean mUserLeaving;
private int mConfigChanges;
private boolean mDontReport;
@Override
public void execute(ClientTransactionHandler client, IBinder token,
client.handlePauseActivity(token, mFinished, mUserLeaving, mConfigChanges, pendingActions,
"PAUSE_ACTIVITY_ITEM");
}
}
public abstract class ActivityLifecycleItem extends ClientTransactionItem {
@Retention(RetentionPolicy.SOURCE)
public @interface LifecycleState{}
public static final int UNDEFINED = -1;
public static final int PRE_ON_CREATE = 0;
public static final int ON_CREATE = 1;
public static final int ON_START = 2;
public static final int ON_RESUME = 3;
public static final int ON_PAUSE = 4;
public static final int ON_STOP = 5;
public static final int ON_DESTROY = 6;
public static final int ON_RESTART = 7;
}
public class ClientTransaction implements Parcelable, ObjectPoolItem {
/** Target client. */
private IApplicationThread mClient;
}
public void schedule() throws RemoteException {
mClient.scheduleTransaction(this);
}
mService.getLifecycleManager().scheduleTransaction,最终调用了IApplciationThread.scheduleTransaction()
此时完成 ActivityManagerService->ApplicationThread发消息,暂停Activity的过程。
阶段三: pause Launcher的Activity,并通知AMS已经paused(在Launcher所在进程执行)
上文知ActivityManagerService向ApplicationThread发送了一个PauseActivity的Transaction事务,相应的调用
- ApplicationThread.scheduleTransaction()
- ActivityThread.scheduleTransaction()
- ActivityThread 发送H.EXECUTE_TRANSACTION
- ActivityThread.H.handleMessage
- ActivityThread.handlePauseActivity
- IActivityManager.activityPaused
ApplicationThread的scheduleTransaction()方法,最终调用了ActivityThread的父类ClientTransactionHandler中的方法,发送了一个H.EXECUTE_TRANSACTION消息到主线程Handler
public abstract class ClientTransactionHandler {
// Schedule phase related logic and handlers.
/** Prepare and schedule transaction for execution. */
void scheduleTransaction(ClientTransaction transaction) {
transaction.preExecute(this);
sendMessage(ActivityThread.H.EXECUTE_TRANSACTION, transaction);
}
handleMessage 处理EXECUTE_TRANSACTION消息时 会调用TransactionExecutor.execuate()
public void handleMessage(Message msg) {
case EXECUTE_TRANSACTION:
final ClientTransaction transaction = (ClientTransaction) msg.obj;
mTransactionExecutor.execute(transaction);
break;
}
public class TransactionExecutor {
public void execute(ClientTransaction transaction) {
executeCallbacks(transaction);
executeLifecycleState(transaction);
}
private void executeLifecycleState(ClientTransaction transaction) {
final ActivityLifecycleItem lifecycleItem = transaction.getLifecycleStateRequest();
lifecycleItem.execute(mTransactionHandler, token, mPendingActions);
lifecycleItem.postExecute(mTransactionHandler, token, mPendingActions);
}
}
最终会调用ActivityThread的handlePauseActivity()方法
阶段四:检查activity所在进程是否存在,如果存在,就直接通知这个进程,在该进程中启动Activity;不存在的话,会调用Process.start创建一个新进程(执行在AMS进程)
- ActivityManagerService.activityPaused
@Override
public final void activityPaused(IBinder token) {
final long origId = Binder.clearCallingIdentity();
synchronized(this) {
ActivityStack stack = ActivityRecord.getStackLocked(token);
if (stack != null) {
stack.activityPausedLocked(token, false);
}
}
Binder.restoreCallingIdentity(origId);
}
- ActivityStack.activityPausedLocked
final void activityPausedLocked(IBinder token, boolean timeout) {
completePauseLocked(true /* resumeNext */, null /* resumingActivity */);
}
- ActivityStack.completePauseLocked
- ActivityStackSupervisor.resumeFocusedStackTopActivityLocked
- ActivityStack.resumeTopActivityUncheckedLocked
- ActivityStack.resumeTopActivityInnerLocked
- ActivityStack.startSpecificActivityLocked
- ActivityStack.startSpecificActivityLocked
经过一系列调用,最终代码又回到了 ActivityStackSupervisor 中的 startSpecificActivityLocked 方法。
void startSpecificActivityLocked(ActivityRecord r,
boolean andResume, boolean checkConfig) {
//注释一:根据进程名和uuid判断Activity所属的进程是否创建
// Is this activity's application already running?
ProcessRecord app = mService.getProcessRecordLocked(r.processName,
r.info.applicationInfo.uid, true);
if (app != null && app.thread != null) {
try {
if ((r.info.flags&ActivityInfo.FLAG_MULTIPROCESS) == 0
|| !"android".equals(r.info.packageName)) {
// Don't add this if it is a platform component that is marked
// to run in multiple processes, because this is actually
// part of the framework so doesn't make sense to track as a
// separate apk in the process.
app.addPackage(r.info.packageName, r.info.applicationInfo.longVersionCode,
mService.mProcessStats);
}
//注释二
realStartActivityLocked(r, app, 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.
}
//注释三 调用ActivityManagerService 启动activity所在进程
mService.startProcessLocked(r.processName, r.info.applicationInfo, true, 0,
"activity", r.intent.getComponent(), false, false, true);
}
- 注释一 根据进程名和 Application 的 uid,来判断目标进程是否已经创建,如果没有则代表进程未创建。
- 注释二 如果acitivity所在的进程已经存在,则尝试启动Activity
- 注释三 如果activity所在的进程不存在,则尝试调用ActivityManagerService来启动进程。
首次启动App,app进程为空,会尝试创建app进程,不会执行realStartActivityLocked
- ActivityManagerService.startProcessLocked
- Process.start //在这里创建了新进程,新的进程会导入ActivityThread类,并执行它的main函数
阶段五:进程创建后,执行ActivityThread.main()入口函数,
创建ActivityThread实例,执行ActivityThread.attach(),创建Application。IPC向ActivityManagerService发送 attachApplication消息,之后进入Loop循环。(执行在新创建的app进程)
- ActivityThread.main
- ActivityThread.attach(false) //声明不是系统进程
- ActivityManagerProxy.attachApplication
阶段六:处理新的应用进程发出的创建进程完成的通信请求,并通知新应用程序进程启动目标Activity组件(执行在AMS进程)
- ActivityManagerService.attachApplication //AMS绑定本地ApplicationThread对象,后续通过ApplicationThread(Binder)对象进行通信
- ActivityManagerService.attachApplicationLocked
private final boolean attachApplicationLocked(IApplicationThread thread,
int pid, int callingUid, long startSeq) {
// See if the top visible activity is waiting to run in this process...
if (normalMode) {
try {
if (mStackSupervisor.attachApplicationLocked(app)) {
didSomething = true;
}
} catch (Exception e) {
Slog.wtf(TAG, "Exception thrown launching activities in " + app, e);
badApp = true;
}
}
}
- ActivityStackSupervisor.attachApplicationLocked
boolean attachApplicationLocked(ProcessRecord app){
realStartActivityLocked(activity, app,top == activity /* andResume */, true /* checkConfig */)) {
}
- ActivityStackSupervisor.realStartActivityLocked //真正要启动Activity了!
final boolean realStartActivityLocked(ActivityRecord r, ProcessRecord app,
boolean andResume, boolean checkConfig) throws RemoteException {
// Create activity launch transaction.
final ClientTransaction clientTransaction = ClientTransaction.obtain(app.thread,
r.appToken);
clientTransaction.addCallback(LaunchActivityItem.obtain(new Intent(r.intent),
System.identityHashCode(r), r.info,
// TODO: Have this take the merged configuration instead of separate global
// and override configs.
mergedConfiguration.getGlobalConfiguration(),
mergedConfiguration.getOverrideConfiguration(), r.compat,
r.launchedFromPackage, task.voiceInteractor, app.repProcState, r.icicle,
r.persistentState, results, newIntents, mService.isNextTransitionForward(),
profilerInfo));
// Set desired final state.
final ActivityLifecycleItem lifecycleItem;
if (andResume) {
lifecycleItem = ResumeActivityItem.obtain(mService.isNextTransitionForward());
} else {
lifecycleItem = PauseActivityItem.obtain();
}
clientTransaction.setLifecycleStateRequest(lifecycleItem);
// Schedule transaction.
mService.getLifecycleManager().scheduleTransaction(clientTransaction);
}
realStartActivityLocked 创建了一个LaunchActivityItem的事务,通过ApplicationThread IPC发送给了新创建的app进程。
- ActivityThread.handleLaunchActivity
- ActivityThread.performLaunchActivity
/** Core implementation of activity launch. */
private Activity performLaunchActivity(ActivityClientRecord r, Intent customIntent) {
ActivityInfo aInfo = r.activityInfo;
//(1)为Activity创建Context
ContextImpl appContext = createBaseContextForActivity(r);
Activity activity = null;
//(2) 通过Instrumentation 创建Activity实例
activity = mInstrumentation.newActivity( cl, component.getClassName(), r.intent);
//获取Applciation实例
Application app = r.packageInfo.makeApplication(false, mInstrumentation);
if (activity != null) {
//(3)调用activity.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);
if (customIntent != null) {
activity.mIntent = customIntent;
}
int theme = r.activityInfo.getThemeResource();
if (theme != 0) {
activity.setTheme(theme);
}
//(4) 调用Instrumentation.callActivityOnCreate() 触发Activity生命周期
if (r.isPersistable()) {
mInstrumentation.callActivityOnCreate(activity, r.state, r.persistentState);
} else {
mInstrumentation.callActivityOnCreate(activity, r.state);
}
return activity;
}
至此Activity已经被启动起来了