1 前言
ATMS启动流程 介绍了 ActivityTaskManagerService(ATMS)的启动和初始化流程,本文将介绍 Activity 的启动流程。由于 Activity 启动流程复杂,本文按进程将其拆分为3个部分展开介绍:
- Launcher 进程:介绍从 Launcher(startActivitySafely 方法)到 ATMS(startActivity 方法)的调用流程;
- system_server 进程:介绍从 ATMS(startActivity 方法)到 ApplicationThread(scheduleTransaction 方法)的调用流程;
- 应用进程:介绍从 ApplicationThread(scheduleTransaction 方法)到 Activity(onCreate 方法)的调用流程。
为区分不同进程,将 Launcher 进程、system_server 进程、应用进程分别标识为浅蓝色、深蓝色、紫色。
2 源码分析
2.1 Launcher 到 ATMS
Launcher 一般指桌面程序,Launcher 类继承了 Activity 类,当用户点击桌面上的快捷方式图标时,就会调用 Launcher 的 startActivitySafely() 方法。
如图,浅蓝色的类是 Launcher 进程中执行的,深蓝色的类是在 system_server 进程中执行的,黄色的类是指 AIDL 文件生成的接口(用于跨进程)。
(1)startActivitySafely
/packages/apps/Launcher3/src/com/android/launcher3/Launcher.java
public boolean startActivitySafely(View v, Intent intent, ItemInfo item, String sourceContainer) {
...
//调用父类 BaseDraggingActivity 的 startActivitySafely 方法
boolean success = super.startActivitySafely(v, intent, item, sourceContainer);
...
}
(2)startActivitySafely
/packages/apps/Launcher3/src/com/android/launcher3/BaseDraggingActivity.java
public boolean startActivitySafely(View v, Intent intent, ItemInfo item, String sourceContainer) {
...
//getActivityLaunchOptions(v).toBundle(),ActivityOptions 存储了 v 的参数,用于启动动画
Bundle optsBundle = (v != null) ? getActivityLaunchOptionsAsBundle(v) : null;
...
//设置 FLAG_ACTIVITY_NEW_TASK,保证 Activity 在新任务栈中运行(后面还会出现)
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
...
try {
...
if (isShortcut) {
startShortcutIntentSafely(intent, optsBundle, item, sourceContainer);
} else if (user == null || user.equals(Process.myUserHandle())) {
...
//调用父类 Activity 的 startActivity 方法
startActivity(intent, optsBundle);
...
}
...
}
...
}
(3)startActivity
/frameworks/base/core/java/android/app/Activity.java
public void startActivity(Intent intent, Bundle options) {
if (options != null) {
//第二个参数为-1表示 launcher 不需要知道返回结果
startActivityForResult(intent, -1, options);
} else {
startActivityForResult(intent, -1);
}
}
public void startActivityForResult(Intent intent, int requestCode, Bundle options) {
//mParent 为 Activity 类型,表示当前 Activity 的父类
if (mParent == null) {
//options == null ? ActivityOptions.fromBundle(ActivityTaskManager.getService().getActivityOptions(mToken)) : options
options = transferSpringboardActivityOptions(options);
// Instrumentation 类用于监控系统和应用程序之间的交互
Instrumentation.ActivityResult ar = mInstrumentation.execStartActivity(
this, mMainThread.getApplicationThread(), mToken, this, intent, requestCode, options);
...
}
...
}
Launcher 是 Activity 的子类,在 Launchar 启动过程中,就已创建 Instrumentation 对象,具体在 ActivityThread 的 handleBindApplication() 方法中创建,并通过 Activity 的 attach() 方法注入到 Activity 中。
Instrumentation 具有盯梢 application 及 activity 生命周期的功用,用于监控 app 和系统的交互,在应用进程中单例存在,即每个应用进程中有且仅有一个 Instrumentation 对象(Launcher 也属于一个应用进程)。
(4)execStartActivity
/frameworks/base/core/java/android/app/Instrumentation.java
public ActivityResult execStartActivity( Context who, IBinder contextThread, IBinder token,
Activity target, Intent intent, int requestCode, Bundle options) {
IApplicationThread whoThread = (IApplicationThread) contextThread;
...
try {
...
int result = ActivityTaskManager.getService().startActivity(
whoThread, who.getBasePackageName(), intent, intent.resolveTypeIfNeeded(who.getContentResolver()),
token, target != null ? target.mEmbeddedID : null, requestCode, 0, null, options);
...
}
...
}
/frameworks/base/core/java/android/app/ActivityTaskManager.java
public static IActivityTaskManager getService() {
return IActivityTaskManagerSingleton.get();
}
private static final Singleton<IActivityTaskManager> IActivityTaskManagerSingleton = new Singleton<IActivityTaskManager>() {
@Override
protected IActivityTaskManager create() {
final IBinder b = ServiceManager.getService(Context.ACTIVITY_TASK_SERVICE); //"activity_task"
return IActivityTaskManager.Stub.asInterface(b);
}
};
ATMS 的启动及初始化过程→ATMS启动流程,ServiceManager 调用 native 层的 ServiceManager,获取在 Android 系统启动时注册的 ATMS 服务。
ATMS 用于管理 Activity 及其容器(任务、堆栈、显示等),在 Android 10 中才出现,由原来的 AMS(ActivityManagerService)分离而来,承担了 AMS 的部分职责。
2.2 ATMS 到 ApplicationThread
如图,深蓝色的类是在 system_server 进程中执行的,紫色的类是待启动应用进程中执行的,黄色的类是指 AIDL 文件生成的接口(用于跨进程)。
(1)startActivity
/frameworks/base/services/core/java/com/android/server/wm/ActivityTaskManagerService.java
public final int startActivity(IApplicationThread caller, String callingPackage, Intent intent, String resolvedType,
IBinder resultTo, String resultWho, int requestCode, int startFlags, ProfilerInfo profilerInfo, Bundle bOptions) {
return startActivityAsUser(caller, callingPackage, intent, resolvedType, resultTo, resultWho,
requestCode, startFlags, profilerInfo, bOptions, UserHandle.getCallingUserId());
}
//较上面方法,多传了调用者的 UserId
public int startActivityAsUser(IApplicationThread caller, String callingPackage, Intent intent, String resolvedType,
IBinder resultTo, String resultWho, int requestCode, int startFlags, ProfilerInfo profilerInfo, Bundle bOptions, int userId) {
return startActivityAsUser(caller, callingPackage, intent, resolvedType, resultTo,
resultWho, requestCode, startFlags, profilerInfo, bOptions, userId, true);
}
int startActivityAsUser(IApplicationThread caller, String callingPackage, Intent intent,
String resolvedType, IBinder resultTo, String resultWho, int requestCode, int startFlags,
ProfilerInfo profilerInfo, Bundle bOptions, int userId, boolean validateIncomingUser) {
//判断调用者进程是否被隔离
enforceNotIsolatedCaller("startActivityAsUser");
//检查调用者权限
userId = getActivityStartController().checkTargetUser(userId, validateIncomingUser, Binder.getCallingPid(), Binder.getCallingUid(), "startActivityAsUser");
return getActivityStartController().obtainStarter(intent, "startActivityAsUser")
.setCaller(caller) //mRequest.caller = caller
.setCallingPackage(callingPackage) //mRequest.callingPackage = callingPackage
.setResolvedType(resolvedType) //mRequest.resolvedType = resolvedType
.setResultTo(resultTo) //mRequest.resultTo = resultTo
.setResultWho(resultWho) //mRequest.resultWho = resultWho
.setRequestCode(requestCode) //mRequest.requestCode = requestCode
.setStartFlags(startFlags) //mRequest.startFlags = startFlags
.setProfilerInfo(profilerInfo) //mRequest.profilerInfo = profilerInfo
.setActivityOptions(bOptions) //mRequest.activityOptions = SafeActivityOptions.fromBundle(bOptions)
.setMayWait(userId) //mRequest.mayWait = true、mRequest.userId = userId
.execute();
}
说明:obtainStarter() 方法获取了一个 ActivityStarter 对象,该对象根据 Intent、flag 转换为 ActivityRecord、TaskRecord、ActivityStack;setCaller() 等 setter 方法会将值注入到 ActivityStarter 的 mRequest 对象(Request 类型)中,该对象在定义时就被初始化。
(2)obtainStarter
/frameworks/base/services/core/java/com/android/server/wm/ActivityStartController.java
ActivityStarter obtainStarter(Intent intent, String reason) {
//mFactory 为 DefaultFactory 类型,是 ActivityStarter 的静态内部类
return mFactory.obtain().setIntent(intent).setReason(reason);
}
DefaultFactory 是 ActivityStarter 的静态内部类,其创建流程如下:(详情→ATMS启动流程)
- 在 AMS 的构造方法中调用 ATMS 的 initialize() 方法;
- 在 ATMS 的 initialize() 方法中调用 ActivityStartController 的构造方法创建 ActivityStartController 对象;
- 在 ActivityStartController 的构造方法中调用 DefaultFactory 的构造方法创建 DefaultFactory 对象。
(3)obtain
/frameworks/base/services/core/java/com/android/server/wm/ActivityStarter.DefaultFactory.java
static class DefaultFactory implements Factory {
...
//MAX_STARTER_COUNT = 3
private SynchronizedPool<ActivityStarter> mStarterPool = new SynchronizedPool<>(MAX_STARTER_COUNT);
...
public ActivityStarter obtain() {
ActivityStarter starter = mStarterPool.acquire();
if (starter == null) {
//参数:ActivityStartController、ActivityTaskManagerService、ActivityStackSupervisor、ActivityStartInterceptor
starter = new ActivityStarter(mController, mService, mSupervisor, mInterceptor);
}
return starter;
}
}
(4)execute
/frameworks/base/services/core/java/com/android/server/wm/ActivityStarter.java
int execute() {
try {
if (mRequest.mayWait) {
return startActivityMayWait(mRequest.caller, mRequest.callingUid,
mRequest.callingPackage, mRequest.realCallingPid, mRequest.realCallingUid,
mRequest.intent, mRequest.resolvedType,
mRequest.voiceSession, mRequest.voiceInteractor, mRequest.resultTo,
mRequest.resultWho, mRequest.requestCode, mRequest.startFlags,
mRequest.profilerInfo, mRequest.waitResult, mRequest.globalConfig,
mRequest.activityOptions, mRequest.ignoreTargetSecurity, mRequest.userId,
mRequest.inTask, mRequest.reason,
mRequest.allowPendingRemoteAnimationRegistryLookup,
mRequest.originatingPendingIntent, mRequest.allowBackgroundActivityStart);
}
...
}
...
}
在 setMayWait(userId) 中,已将 mRequest.mayWait 置为 true,因此会进入 startActivityMayWait() 方法。
(5)startActivityMayWait
/frameworks/base/services/core/java/com/android/server/wm/ActivityStarter.java
private int startActivityMayWait(IApplicationThread caller, int callingUid, String callingPackage,
int requestRealCallingPid, int requestRealCallingUid, Intent intent, String resolvedType,
IVoiceInteractionSession voiceSession, IVoiceInteractor voiceInteractor, IBinder resultTo,
String resultWho, int requestCode, int startFlags, ProfilerInfo profilerInfo, WaitResult outResult,
Configuration globalConfig, SafeActivityOptions options, boolean ignoreTargetSecurity,
int userId, TaskRecord inTask, String reason, boolean allowPendingRemoteAnimationRegistryLookup,
PendingIntentRecord originatingPendingIntent, boolean allowBackgroundActivityStart) {
...
//解析 Intent
ResolveInfo rInfo = mSupervisor.resolveIntent(intent, resolvedType, userId, 0,
computeResolveFilterUid(callingUid, realCallingUid, mRequest.filterCallingUid));
...
//收集目标 Intent 的信息
ActivityInfo aInfo = mSupervisor.resolveActivity(intent, rInfo, startFlags, profilerInfo);
synchronized (mService.mGlobalLock) {
...
//创建 ActivityRecord 数组
final ActivityRecord[] outRecord = new ActivityRecord[1];
int res = startActivity(caller, intent, ephemeralIntent, resolvedType, aInfo, rInfo,
voiceSession, voiceInteractor, resultTo, resultWho, requestCode, callingPid,
callingUid, callingPackage, realCallingPid, realCallingUid, startFlags, options,
ignoreTargetSecurity, componentSpecified, outRecord, inTask, reason,
allowPendingRemoteAnimationRegistryLookup, originatingPendingIntent,
allowBackgroundActivityStart);
...
}
}
(6)startActivity
/frameworks/base/services/core/java/com/android/server/wm/ActivityStarter.java
private int startActivity(IApplicationThread caller, Intent intent, Intent ephemeralIntent, String resolvedType,
ActivityInfo aInfo, ResolveInfo rInfo, IVoiceInteractionSession voiceSession, IVoiceInteractor voiceInteractor,
IBinder resultTo, String resultWho, int requestCode, int callingPid, int callingUid, String callingPackage,
int realCallingPid, int realCallingUid, int startFlags, SafeActivityOptions options, boolean ignoreTargetSecurity,
boolean componentSpecified, ActivityRecord[] outActivity, TaskRecord inTask, String reason, boolean allowPendingRemoteAnimationRegistryLookup,
PendingIntentRecord originatingPendingIntent, boolean allowBackgroundActivityStart) {
...
mLastStartActivityRecord[0] = null;
mLastStartActivityResult = startActivity(caller, intent, ephemeralIntent, resolvedType,
aInfo, rInfo, voiceSession, voiceInteractor, resultTo, resultWho, requestCode,
callingPid, callingUid, callingPackage, realCallingPid, realCallingUid, startFlags,
options, ignoreTargetSecurity, componentSpecified, mLastStartActivityRecord,
inTask, allowPendingRemoteAnimationRegistryLookup, originatingPendingIntent,
allowBackgroundActivityStart);
...
}
(7)startActivity
/frameworks/base/services/core/java/com/android/server/wm/ActivityStarter.java
private int startActivity(IApplicationThread caller, Intent intent, Intent ephemeralIntent, String resolvedType,
ActivityInfo aInfo, ResolveInfo rInfo, IVoiceInteractionSession voiceSession, IVoiceInteractor voiceInteractor,
IBinder resultTo, String resultWho, int requestCode, int callingPid, int callingUid, String callingPackage,
int realCallingPid, int realCallingUid, int startFlags, SafeActivityOptions options, boolean ignoreTargetSecurity,
boolean componentSpecified, ActivityRecord[] outActivity, TaskRecord inTask, boolean allowPendingRemoteAnimationRegistryLookup,
PendingIntentRecord originatingPendingIntent, boolean allowBackgroundActivityStart) {
...
WindowProcessController callerApp = null;
if (caller != null) {
//从 ATMS 中获取 WindowProcessController
callerApp = mService.getProcessController(caller);
...
}
...
//一个 ActivityRecord 对应一个 Activity,描述了 Activity 的信息
ActivityRecord r = new ActivityRecord(mService, callerApp, callingPid, callingUid,
callingPackage, intent, resolvedType, aInfo, mService.getGlobalConfiguration(),
resultRecord, resultWho, requestCode, componentSpecified, voiceSession != null,
mSupervisor, checkedOptions, sourceRecord);
if (outActivity != null) {
outActivity[0] = r;
}
...
final int res = startActivity(r, sourceRecord, voiceSession, voiceInteractor, startFlags, true,
checkedOptions, inTask, outActivity, restrictedBgActivity);
...
}
(8)startActivity
/frameworks/base/services/core/java/com/android/server/wm/ActivityStarter.java
private int startActivity(final ActivityRecord r, ActivityRecord sourceRecord,
IVoiceInteractionSession voiceSession, IVoiceInteractor voiceInteractor,
int startFlags, boolean doResume, ActivityOptions options, TaskRecord inTask,
ActivityRecord[] outActivity, boolean restrictedBgActivity) {
...
try {
mService.mWindowManager.deferSurfaceLayout();
result = startActivityUnchecked(r, sourceRecord, voiceSession, voiceInteractor,
startFlags, doResume, options, inTask, outActivity, restrictedBgActivity);
}
...
}
(9)startActivityUnchecked
/frameworks/base/services/core/java/com/android/server/wm/ActivityStarter.java
private int startActivityUnchecked(final ActivityRecord r, ActivityRecord sourceRecord,
IVoiceInteractionSession voiceSession, IVoiceInteractor voiceInteractor,
int startFlags, boolean doResume, ActivityOptions options, TaskRecord inTask,
ActivityRecord[] outActivity, boolean restrictedBgActivity) {
//初始化 ActivityStarter 的属性
setInitialState(r, options, inTask, doResume, startFlags, sourceRecord, voiceSession, voiceInteractor, restrictedBgActivity);
...
//计算 mLaunchFlags
computeLaunchingTaskFlags();
//计算 mSourceStack
computeSourceStack();
...
final TaskRecord taskToAffiliate = (mLaunchTaskBehind && mSourceRecord != null) ? mSourceRecord.getTaskRecord() : null;
...
if (mStartActivity.resultTo == null && mInTask == null && !mAddingToTask && (mLaunchFlags & FLAG_ACTIVITY_NEW_TASK) != 0) {
newTask = true;
//创建新的 TaskStack,即 mTargetStack:computeStackFocus() -> getLaunchStack()
result = setTaskFromReuseOrCreateNewTask(taskToAffiliate);
}
...
//处理 Task 和 Activity 的进栈操作
mTargetStack.startActivityLocked(mStartActivity, topFocused, newTask, mKeepCurTransition, mOptions);
if (mDoResume) {
final ActivityRecord topTaskActivity = mStartActivity.getTaskRecord().topRunningActivityLocked();
if (!mTargetStack.isFocusable() || (topTaskActivity != null && topTaskActivity.mTaskOverlay && mStartActivity != topTaskActivity)) {
...
} else {
...
//启动焦点栈的栈顶 Activity
mRootActivityContainer.resumeFocusedStacksTopActivities(mTargetStack, mStartActivity, mOptions);
}
}
...
}
RootActivityContainer 在 Android 10 中才出现,由原来的 ActivityStackSupervisor 分离而来,目的在于同 RootWindowContainer 保持对等的层次结构。
RootActivityContainer 在 ATMS 的 initialize() 方法中创建,并在 ActivityStarter 的构造方法中通过 ATMS.mRootActivityContainer 注入到 ActivityStarter 中。
ActivityStack 的创建流程如下:
(10)resumeFocusedStacksTopActivities
/frameworks/base/services/core/java/com/android/server/wm/RootActivityContainer .java
boolean resumeFocusedStacksTopActivities(ActivityStack targetStack, ActivityRecord target, ActivityOptions targetOptions) {
...
if (targetStack != null && (targetStack.isTopStackOnDisplay() || getTopDisplayFocusedStack() == targetStack)) {
result = targetStack.resumeTopActivityUncheckedLocked(target, targetOptions);
}
...
}
(11)resumeTopActivityUncheckedLocked
/frameworks/base/services/core/java/com/android/server/wm/ActivityStack.java
boolean resumeTopActivityUncheckedLocked(ActivityRecord prev, ActivityOptions options) {
...
try {
...
result = resumeTopActivityInnerLocked(prev, options);
...
}
...
}
(12)resumeTopActivityInnerLocked
/frameworks/base/services/core/java/com/android/server/wm/ActivityStack.java
private boolean resumeTopActivityInnerLocked(ActivityRecord prev, ActivityOptions options) {
...
ActivityRecord next = topRunningActivityLocked(true);
...
mStackSupervisor.setLaunchSource(next.info.applicationInfo.uid);
...
if (next.attachedToProcess()) {
...
} else {
...
//mStackSupervisor 为 ActivityStackSupervisor,在 ATMS 的 initialize() 方法中创建
mStackSupervisor.startSpecificActivityLocked(next, true, true);
}
...
}
ActivityStackSupervisor 在 ATMS 的 initialize() 方法中创建,并在 ActivityStack 的构造方法中注入到 ActivityStack 中。
(13)startSpecificActivityLocked
/frameworks/base/services/core/java/com/android/server/wm/ActivityStackSupervisor.java
void startSpecificActivityLocked(ActivityRecord r, boolean andResume, boolean checkConfig) {
final WindowProcessController wpc = mService.getProcessController(r.processName, r.info.applicationInfo.uid);
...
//判断应用进程是否已创建,即 IApplicationThread 是否为空
if (wpc != null && wpc.hasThread()) {
try {
//启动 Activity
realStartActivityLocked(r, wpc, andResume, checkConfig);
return;
}
}
try {
...
//应用进程不存在,通知创建应用进程
final Message msg = PooledLambda.obtainMessage(
ActivityManagerInternal::startProcess, mService.mAmInternal, r.processName,
r.info.applicationInfo, knownToBeDead, "activity", r.intent.getComponent());
mService.mH.sendMessage(msg);
}
...
}
(14)realStartActivityLocked
/frameworks/base/services/core/java/com/android/server/wm/ActivityStackSupervisor.java
boolean realStartActivityLocked(ActivityRecord r, WindowProcessController proc, boolean andResume, boolean checkConfig) throws RemoteException {
...
try {
...
r.setProcess(proc);
...
proc.addActivityIfNeeded(r);
...
try {
...
//创建启动 Activity 的事务
//instance = new ClientTransaction(); instance.mClient = client; instance.mActivityToken = activityToken
final ClientTransaction clientTransaction = ClientTransaction.obtain(proc.getThread(), r.appToken);
...
final DisplayContent dc = r.getDisplay().mDisplayContent;
//添加回调,这里添加的 LaunchActivityItem 会在 TransactionExecutor 中获取并执行
clientTransaction.addCallback(LaunchActivityItem.obtain(new Intent(r.intent),
System.identityHashCode(r), r.info,
mergedConfiguration.getGlobalConfiguration(),
mergedConfiguration.getOverrideConfiguration(), r.compat,
r.launchedFromPackage, task.voiceInteractor, proc.getReportedProcState(),
r.icicle, r.persistentState, results, newIntents,
dc.isNextTransitionForward(), proc.createProfilerInfoIfNeeded(), r.assistToken));
final ActivityLifecycleItem lifecycleItem;
if (andResume) {
lifecycleItem = ResumeActivityItem.obtain(dc.isNextTransitionForward());
}
...
clientTransaction.setLifecycleStateRequest(lifecycleItem);
//启动事务,mService 为 ATMS,ClientLifecycleManager 对象在 ATMS 的构造方法中创建
mService.getLifecycleManager().scheduleTransaction(clientTransaction);
...
}
...
}
...
}
ClientLifecycleManager 在 ATMS 的 构造方法中创建。
LaunchActivityItem 封装了 Activity 的启动信息,其父类(ClientTransactionItem)实现了 Parcelable 接口,是 Binder 跨进程通讯的数据包,LaunchActivityItem 对象被添加到 ClientTransaction 中,随着 ClientTransaction 一起传送到应用进程。
(15)scheduleTransaction
/frameworks/base/services/core/java/com/android/server/wm/ClientLifecycleManager.java
void scheduleTransaction(ClientTransaction transaction) throws RemoteException {
...
transaction.schedule();
...
}
(16)schedule
/frameworks/base/core/java/android/app/servertransaction/ClientTransaction.java
public void schedule() throws RemoteException {
//mClient 为 IApplicationThread 类型
mClient.scheduleTransaction(this);
}
ClientTransaction 的实现了 Parcelable 接口,是 Binder 跨进程通讯的数据包,通过调用 mClient.scheduleTransaction(this) 将自身封装的数据传送到应用进程。
2.3 ApplicationThread 到 Activity
如图,深蓝色的类是在 system_server 进程中执行的,紫色的类是待启动应用进程中执行的,黄色的类是指 AIDL 文件生成的接口(用于跨进程),绿色的类实现了 Parcelable 接口(Binder 跨进程通讯传输的数据包)。
(1)scheduleTransaction
/frameworks/base/core/java/android/app/ActivityThread.****ApplicationThread.java
public void scheduleTransaction(ClientTransaction transaction) throws RemoteException {
//ActivityThread 继承了 ClientTransactionHandler,这里调用的是父类的 scheduleTransaction() 方法
ActivityThread.this.scheduleTransaction(transaction);
}
说明:ApplicationThread 是 ActivityThread 的内部类,并继承了 IApplicationThread.Stub 类。
(2)scheduleTransaction
/frameworks/base/core/java/android/app/ClientTransactionHandler.java
void scheduleTransaction(ClientTransaction transaction) {
transaction.preExecute(this);
sendMessage(ActivityThread.H.EXECUTE_TRANSACTION, transaction);
}
(3)sendMessage
/frameworks/base/core/java/android/app/ActivityThread.java
void sendMessage(int what, Object obj) {
sendMessage(what, obj, 0, 0, false);
}
private void sendMessage(int what, Object obj, int arg1, int arg2, boolean async) {
...
Message msg = Message.obtain();
msg.what = what;
msg.obj = obj;
msg.arg1 = arg1;
msg.arg2 = arg2;
if (async) {
msg.setAsynchronous(true);
}
//mH 是 H 类的对象,在定义时就被创建:mH = new H()
mH.sendMessage(msg);
}
H 类继承 Handler 类,是 ActivityThread 的内部类,主要用于 Binder 线程和主线程(UI线程)间通讯。
(4)handleMessage
/frameworks/base/core/java/android/app/ActivityThread.****H.java
class H extends Handler {
...
public static final int EXECUTE_TRANSACTION = 159;
...
public void handleMessage(Message msg) {
...
switch (msg.what) {
...
case EXECUTE_TRANSACTION:
final ClientTransaction transaction = (ClientTransaction) msg.obj;
//mTransactionExecutor 在定义时就被初始化,即:mTransactionExecutor = new TransactionExecutor(this);
mTransactionExecutor.execute(transaction);
...
break;
...
}
...
}
}
前面与 ATMS 进程通讯运行在 Binder 线程中,即 ApplicationThread,所以这里需要用 H 将代码逻辑切换至主线程(UI 线程)。TransactionExecutor 在 ApplicationThread 中定义时就被初始化。
(5)scheduleTransaction
/frameworks/base/core/java/android/app/servertransaction/TransactionExecutor.java
public void execute(ClientTransaction transaction) {
...
executeCallbacks(transaction);
executeLifecycleState(transaction);
...
}
(6)executeCallbacks
/frameworks/base/core/java/android/app/servertransaction/TransactionExecutor.java
public void executeCallbacks(ClientTransaction transaction) {
final List<ClientTransactionItem> callbacks = transaction.getCallbacks();
...
final IBinder token = transaction.getActivityToken();
ActivityClientRecord r = mTransactionHandler.getActivityClient(token);
...
final int size = callbacks.size();
for (int i = 0; i < size; ++i) {
//item 是 ClientTransactionItem 的子类(LaunchActivityItem)的对象
final ClientTransactionItem item = callbacks.get(i);
...
item.execute(mTransactionHandler, token, mPendingActions);
item.postExecute(mTransactionHandler, token, mPendingActions);
...
}
}
(7)execute
/frameworks/base/core/java/android/app/servertransaction/LaunchActivityItem.java
public void execute(ClientTransactionHandler client, IBinder token, PendingTransactionActions pendingActions) {
...
//创建 ActivityClientRecord,它是 ActivityThread 的内部类
ActivityClientRecord r = new ActivityClientRecord(token, mIntent, mIdent, mInfo,
mOverrideConfig, mCompatInfo, mReferrer, mVoiceInteractor, mState, mPersistentState,
mPendingResults, mPendingNewIntents, mIsForward,
mProfilerInfo, client, mAssistToken);
//client 是 ClientTransactionHandler 的子类(ActivityThread)的对象
client.handleLaunchActivity(r, pendingActions, null);
...
}
(8)handleLaunchActivity
/frameworks/base/core/java/android/app/ActivityThread.java
public Activity handleLaunchActivity(ActivityClientRecord r, PendingTransactionActions pendingActions, Intent customIntent) {
...
//获取 WMS
WindowManagerGlobal.initialize();
...
final Activity a = performLaunchActivity(r, customIntent);
...
return a;
}
(9)performLaunchActivity
/frameworks/base/core/java/android/app/ActivityThread.java
private Activity performLaunchActivity(ActivityClientRecord r, Intent customIntent) {
ActivityInfo aInfo = r.activityInfo;
...
//ComponentName 中包含 Activity 的类名和包名
ComponentName component = r.intent.getComponent();
...
//创建 Context:ContextImpl.createActivityContext(this, r.packageInfo, r.activityInfo, r.token, displayId, r.overrideConfig)
ContextImpl appContext = createBaseContextForActivity(r);
Activity activity = null;
try {
java.lang.ClassLoader cl = appContext.getClassLoader();
//创建 Activity,通过反射实现:cl.loadClass(className).newInstance()
activity = mInstrumentation.newActivity(cl, component.getClassName(), r.intent);
...
}
...
try {
//创建 Application
Application app = r.packageInfo.makeApplication(false, mInstrumentation);
...
if (activity != null) {
...
Window window = null; //实现类为 PhoneWindow
...
appContext.setOuterContext(activity);
//将属性(Instrumentation等)注入 Activity,并创建 PhoneWindow、WindowManagerImpl 对象
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);
...
if (r.isPersistable()) {
//回调 Activity 的 onCreate() 方法
mInstrumentation.callActivityOnCreate(activity, r.state, r.persistentState);
}
...
r.activity = activity;
}
//切换 Activity 状态
r.setState(ON_CREATE);
...
synchronized (mResourcesManager) {
mActivities.put(r.token, r);
}
}
...
return activity;
}
在创建和启动应用进程时,就已在 ActivityThread 的 handleBindApplication() 方法中,创建了 Instrumentation 对象,并通过 Activity 的 attach() 方法注入到 Activity 中。
Instrumentation 具有盯梢 application 及 activity 生命周期的功用,用于监控 app 和系统的交互,在应用进程中单例存在,即每个应用进程中有且仅有一个 Instrumentation 对象。
(10)callActivityOnCreate
/frameworks/base/core/java/android/app/Instrumentation.java
public void callActivityOnCreate(Activity activity, Bundle icicle, PersistableBundle persistentState) {
//onCreate() 方法回调前处理
prePerformCreate(activity);
//调用 onCreate() 方法
activity.performCreate(icicle, persistentState);
//onCreate() 方法回调后处理
postPerformCreate(activity);
}
(11)performCreate
/frameworks/base/core/java/android/app/Activity.java
final void performCreate(Bundle icicle, PersistableBundle persistentState) {
dispatchActivityPreCreated(icicle);
...
if (persistentState != null) {
//调用用户自定义 Activity 的 oncreate() 方法
onCreate(icicle, persistentState);
} else {
onCreate(icicle);
}
...
dispatchActivityPostCreated(icicle);
}
声明:本文转自【framework】Activity启动流程
标签:...,java,int,流程,mRequest,framework,intent,Activity From: https://www.cnblogs.com/zhyan8/p/17233659.html