根 Activity (.MainActivity)的启动过程比较复杂,由三个部分:
- Laucnher 请求 AMS 过程
- AMS 到 ApplicationThread 的调用过程
- ActivityThread 启动 Activity
Launcher 请求 AMS 过程
当电机某个应用程序的快捷图标时,会通过 Launcher 请求 AMS 来启动该应用程序,Launcher 调用 startActivitySafely 方法:
packages/apps/Launcher3/src/com/android/launcher3/Launcher.java
public boolean startActivitySafely(View v, Intent intent, ItemInfo item) {
boolean success = super.startActivitySafely(v, intent, item);
if (success && v instanceof BubbleTextView) {
// This is set to the view that launched the activity that navigated the user away
// from launcher. Since there is no callback for when the activity has finished
// launching, enable the press state and keep this reference to reset the press
// state when we return to launcher.
BubbleTextView btv = (BubbleTextView) v;
btv.setStayPressed(true);
setOnResumeCallback(btv);
}
return success;
}
调用父类BaseDraggingActivity的 startActivitySafely
packages/apps/Launcher3/src/com/android/launcher3/BaseDraggingActivity.java
public boolean startActivitySafely(View v, Intent intent, ItemInfo item) {
//...
// Prepare intent
//设置为FLAG_ACTIVITY_NEW_TASK,
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
if (v != null) {
intent.setSourceBounds(getViewBounds(v));
}
try {
boolean isShortcut = Utilities.ATLEAST_MARSHMALLOW
&& (item instanceof ShortcutInfo)
&& (item.itemType == Favorites.ITEM_TYPE_SHORTCUT
|| item.itemType == Favorites.ITEM_TYPE_DEEP_SHORTCUT)
&& !((ShortcutInfo) item).isPromise();
if (isShortcut) {
// Shortcuts need some special checks due to legacy reasons.
startShortcutIntentSafely(intent, optsBundle, item);
} else if (user == null || user.equals(Process.myUserHandle())) {
// Could be launching some bookkeeping activity
//调用startActivity
startActivity(intent, optsBundle);
} else {
LauncherAppsCompat.getInstance(this).startActivityForProfile(
intent.getComponent(), user, intent.getSourceBounds(), optsBundle);
}
getUserEventDispatcher().logAppLaunch(v, intent);
return true;
} catch (ActivityNotFoundException|SecurityException e) {
Toast.makeText(this, R.string.activity_not_found, Toast.LENGTH_SHORT).show();
Log.e(TAG, "Unable to launch. tag=" + item + " intent=" + intent, e);
}
return false;
}
startActivity 在 Activity.java 里
frameworks/base/core/java/android/app/Activity.java
public void startActivity(Intent intent, @Nullable Bundle options) {
if (options != null) {
startActivityForResult(intent, -1, options);
} else {
// Note we want to go through this call for compatibility with
// applications that may have overridden the method.
startActivityForResult(intent, -1);
}
}
//这里的第二个参数是-1,不需要知道结果
public void startActivityForResult(@RequiresPermission Intent intent, int requestCode,
@Nullable Bundle options) {
if (mParent == null) { //如果第一次启动
options = transferSpringboardActivityOptions(options);
//Instrumentation类是Android操作系统中程序端操作Activity的具体操作类
//当系统需要具体执行Activity的某个操作时,需要借助于Instrumentation来实现
Instrumentation.ActivityResult ar =
mInstrumentation.execStartActivity(
this, mMainThread.getApplicationThread(), mToken, this,
intent, requestCode, options);
if (ar != null) {
mMainThread.sendActivityResult(
mToken, mEmbeddedID, requestCode, ar.getResultCode(),
ar.getResultData());
}
//...
} else {
//...
}
}
Instrumentation 用来监控应用程序和系统的交互
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) {
//...
try {
intent.migrateExtraStreamToClipData();
intent.prepareToLeaveProcess(who);
int result = ActivityManager.getService()
.startActivity(whoThread, who.getBasePackageName(), intent,
intent.resolveTypeIfNeeded(who.getContentResolver()),
token, target != null ? target.mEmbeddedID : null,
requestCode, 0, null, options);
checkStartActivityResult(result, intent);
} catch (RemoteException e) {
throw new RuntimeException("Failure from system", e);
}
return null;
}
ActivityManager.getService()获取 AMS 的代理对象,然后调用 startActivity 方法
./frameworks/base/core/java/android/app/ActivityManager.java
public static IActivityManager getService() {
return IActivityManagerSingleton.get();
}
private static final Singleton<IActivityManager> IActivityManagerSingleton =
new Singleton<IActivityManager>() {
@Override
protected IActivityManager create() {
//得到名为"activity"的Service引用(iBinder类型的AMS引用),就是AMS
final IBinder b = ServiceManager.getService(Context.ACTIVITY_SERVICE);
//AIDL获得接口
final IActivityManager am = IActivityManager.Stub.asInterface(b);
return am;
}
};
所以ActivityManager.getService().startActivity()是使用 Binder 机制进行了跨进程间的通信
ActivityManagerService 继承 ActivityManagerNative,而它又实现了 IActivityManager 借口,最终调用到 AMS 的 startActivity
日志截图:
AMS 到 ApplicationThread 的调用过程
Launcher 使用 AIDL 调用 AMS 的接口后,代码逻辑进入 AMS 中
AMS 的 startActivity 方法如下所示:
frameworks/base/services/core/java/com/android/server/am/ActivityManagerService.java
@Override
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的变量
@Override
public final 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 /*validateIncomingUser*/);
}
public final 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("startActivity");
//检查调用者权限
userId = mActivityStartController.checkTargetUser(userId, validateIncomingUser,
Binder.getCallingPid(), Binder.getCallingUid(), "startActivityAsUser");
// TODO: Switch to user app stacks here.
return mActivityStartController.obtainStarter(intent, "startActivityAsUser")
.setCaller(caller)
.setCallingPackage(callingPackage)
.setResolvedType(resolvedType)
.setResultTo(resultTo)
.setResultWho(resultWho)
.setRequestCode(requestCode)
.setStartFlags(startFlags)
.setProfilerInfo(profilerInfo)
.setActivityOptions(bOptions)
.setMayWait(userId) //这里setMayWait时,mayWait会被设置成true
.execute();
}
//frameworks/base/services/core/java/com/android/server/am/ActivityStartController.java
int checkTargetUser(int targetUserId, boolean validateIncomingUser,
int realCallingPid, int realCallingUid, String reason) {
if (validateIncomingUser) {
//检查调用者是否又权限,如果没有权限就会抛出异常
return mService.mUserController.handleIncomingUser(realCallingPid, realCallingUid,
targetUserId, false, ALLOW_FULL_ONLY, reason, null);
} else {
mService.mUserController.ensureNotSpecialUser(targetUserId);
return targetUserId;
}
}
最后调用了 ActivityStarter 的 execute 方法,这个专门用于启动 Activity:
./frameworks/base/services/core/java/com/android/server/am/ActivityStarter.java
int execute() {
try {
// TODO(b/64750076): Look into passing request directly to these methods to allow
// for transactional diffs and preprocessing.
if (mRequest.mayWait) {
//调用startActivityMayWait
return startActivityMayWait(mRequest.caller, mRequest.callingUid,
mRequest.callingPackage, 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);
} else {
return startActivity(mRequest.caller, mRequest.intent, mRequest.ephemeralIntent,
mRequest.resolvedType, mRequest.activityInfo, mRequest.resolveInfo,
mRequest.voiceSession, mRequest.voiceInteractor, mRequest.resultTo,
mRequest.resultWho, mRequest.requestCode, mRequest.callingPid,
mRequest.callingUid, mRequest.callingPackage, mRequest.realCallingPid,
mRequest.realCallingUid, mRequest.startFlags, mRequest.activityOptions,
mRequest.ignoreTargetSecurity, mRequest.componentSpecified,
mRequest.outActivity, mRequest.inTask, mRequest.reason,
mRequest.allowPendingRemoteAnimationRegistryLookup,
mRequest.originatingPendingIntent);
}
} finally {
onExecutionComplete();
}
}
private int startActivityMayWait(IApplicationThread caller, int callingUid,
String callingPackage, 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) {
//...
//通过ActivityStackSupervisor获取ResolveInfo信息
ResolveInfo rInfo = mSupervisor.resolveIntent(intent, resolvedType, userId, 0 /* matchFlags */,
computeResolveFilterUid(callingUid, realCallingUid, mRequest.filterCallingUid));
//...
// 通过ActivityStackSupervior获取ActivityInfo信息
ActivityInfo aInfo = mSupervisor.resolveActivity(intent, rInfo, startFlags, profilerInfo);
synchronized (mService) {
final ActivityStack stack = mSupervisor.mFocusedStack;
stack.mConfigWillChange = globalConfig != null
&& mService.getGlobalConfiguration().diff(globalConfig) != 0;
if (DEBUG_CONFIGURATION) Slog.v(TAG_CONFIGURATION,
"Starting activity when config will change = " + stack.mConfigWillChange);
final long origId = Binder.clearCallingIdentity();
//...
//这里调用startActivity活动
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);
Binder.restoreCallingIdentity(origId);
if (stack.mConfigWillChange) {
// If the caller also wants to switch to a new configuration,
// do so now. This allows a clean switch, as we are waiting
// for the current activity to pause (so we will not destroy
// it), and have not yet started the next activity.
mService.enforceCallingPermission(android.Manifest.permission.CHANGE_CONFIGURATION,
"updateConfiguration()");
stack.mConfigWillChange = false;
if (DEBUG_CONFIGURATION) Slog.v(TAG_CONFIGURATION,
"Updating to new configuration after starting activity.");
mService.updateConfigurationLocked(globalConfig, null, false);
}
//...
}
}
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) {
if (TextUtils.isEmpty(reason)) { //启动的理由不能为空
throw new IllegalArgumentException("Need to specify a reason.");
}
mLastStartReason = reason;
mLastStartActivityTimeMs = System.currentTimeMillis();
mLastStartActivityRecord[0] = null;
//调用了startActivity防范
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);
if (outActivity != null) {
// mLastStartActivityRecord[0] is set in the call to startActivity above.
outActivity[0] = mLastStartActivityRecord[0];
}
return getExternalResult(mLastStartActivityResult);
}
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) {
int err = ActivityManager.START_SUCCESS;
// Pull the optional Ephemeral Installer-only bundle out of the options early.
final Bundle verificationBundle
= options != null ? options.popAppVerificationBundle() : null;
ProcessRecord callerApp = null;
if (caller != null) { //判断IApplicationThread类型的caller是否为null
//caller指向的时Launcher所在的应用程序进程的ApplicationThread对象
//AMS的getrRecordForAppLocked方法的道德时代表Launcher进程的callerApp对象
//ProcessRecord用于描述一个应用程序进程
//ActivityRecord用于描述一个Activity,用来记录一个Activity的所有信息
callerApp = mService.getRecordForAppLocked(caller);
if (callerApp != null) {
callingPid = callerApp.pid;
callingUid = callerApp.info.uid;
} else {
Slog.w(TAG, "Unable to find app for caller " + caller
+ " (pid=" + callingPid + ") when starting: "
+ intent.toString());
err = ActivityManager.START_PERMISSION_DENIED;
}
}
//...
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; //将创建的ActivityRecord赋值给ActivityRecord[]类型的outActivity
}
//...
//outActivity作为参数继续传递
return startActivity(r, sourceRecord, voiceSession, voiceInteractor, startFlags,
true /* doResume */, checkedOptions, inTask, outActivity);
}
private int startActivity(final ActivityRecord r, ActivityRecord sourceRecord,
IVoiceInteractionSession voiceSession, IVoiceInteractor voiceInteractor,
int startFlags, boolean doResume, ActivityOptions options, TaskRecord inTask,
ActivityRecord[] outActivity) {
int result = START_CANCELED;
try {
mService.mWindowManager.deferSurfaceLayout();
//紧接着调用startActivityUncheked
result = startActivityUnchecked(r, sourceRecord, voiceSession, voiceInteractor,
startFlags, doResume, options, inTask, outActivity);
} finally {
// If we are not able to proceed, disassociate the activity from the task. Leaving an
// activity in an incomplete state can lead to issues, such as performing operations
// without a window container.
final ActivityStack stack = mStartActivity.getStack();
if (!ActivityManager.isStartResultSuccessful(result) && stack != null) {
stack.finishActivityLocked(mStartActivity, RESULT_CANCELED,
null /* intentResultData */, "startActivity", true /* oomAdj */);
}
mService.mWindowManager.continueSurfaceLayout();
}
postStartActivityProcessing(r, result, mTargetStack);
return result;
}
private int startActivityUnchecked(final ActivityRecord r, ActivityRecord sourceRecord,
IVoiceInteractionSession voiceSession, IVoiceInteractor voiceInteractor,
int startFlags, boolean doResume, ActivityOptions options, TaskRecord inTask,
ActivityRecord[] outActivity) {
//...计算启动 Activity 的 Flag 值
computeLaunchingTaskFlags();
computeSourceStack();
mIntent.setFlags(mLaunchFlags);
//...
//之前启动根Activity会将intent的Flag设置为FLAG_ACTIVITY_NEW_TASK,这里判断就通过了
if (mStartActivity.resultTo == null && mInTask == null && !mAddingToTask
&& (mLaunchFlags & FLAG_ACTIVITY_NEW_TASK) != 0) {
newTask = true;
//创建一个新的TaskRecord,用来描述一个Activity任务栈,会创建一个新的Activity任务栈
result = setTaskFromReuseOrCreateNewTask(taskToAffiliate, topStack);
} else if (mSourceRecord != null) {
result = setTaskFromSourceRecord();
} else if (mInTask != null) {
result = setTaskFromInTask();
} else {
// This not being started from an existing activity, and not part of a new task...
// just put it in the top task, though these days this case should never happen.
setTaskToCurrentTopOrCreateNewTask();
}
if (result != START_SUCCESS) {
return result;
}
//...处理 Task 和 Activity 的进栈操作
mTargetStack.startActivityLocked(mStartActivity, topFocused, newTask, mKeepCurTransition,
mOptions);
if (mDoResume) {
final ActivityRecord topTaskActivity =
mStartActivity.getTask().topRunningActivityLocked();
if (!mTargetStack.isFocusable()
|| (topTaskActivity != null && topTaskActivity.mTaskOverlay
&& mStartActivity != topTaskActivity)) {
// If the activity is not focusable, we can't resume it, but still would like to
// make sure it becomes visible as it starts (this will also trigger entry
// animation). An example of this are PIP activities.
// Also, we don't want to resume activities in a task that currently has an overlay
// as the starting activity just needs to be in the visible paused state until the
// over is removed.
mTargetStack.ensureActivitiesVisibleLocked(null, 0, !PRESERVE_WINDOWS);
// Go ahead and tell window manager to execute app transition for this activity
// since the app transition will not be triggered through the resume channel.
mService.mWindowManager.executeAppTransition();
} else {
// If the target stack was not previously focusable (previous top running activity
// on that stack was not visible) then any prior calls to move the stack to the
// will not update the focused stack. If starting the new activity now allows the
// task stack to be focusable, then ensure that we now update the focused stack
// accordingly.
if (mTargetStack.isFocusable() && !mSupervisor.isFocusedStack(mTargetStack)) {
mTargetStack.moveToFront("startActivityUnchecked");
}
//调用ActivityStackSupervisor的resumeFocusedStackTopActivityLocked方法
//启动栈中顶部的 Activity
mSupervisor.resumeFocusedStackTopActivityLocked(mTargetStack, mStartActivity,
mOptions);
}
} else if (mStartActivity != null) {
mSupervisor.mRecentTasks.add(mStartActivity.getTask());
}
mSupervisor.updateUserStackLocked(mStartActivity.userId, mTargetStack);
mSupervisor.handleNonResizableTaskIfNeeded(mStartActivity.getTask(), preferredWindowingMode,
preferredLaunchDisplayId, mTargetStack);
return START_SUCCESS;
}
startActivityLocked 里调用 insertTaskAtTop() 方法,尝试将 Task 和 Activity 入栈。如果 Activity 是以 NEW_TASK 的模式启动或者 Task 堆栈中不存在该 TaskId,则 task 会重新入栈并且放在栈的顶部。注意:Task 先入栈,之后才是 Activity 入栈,它们是包含关系。
void startActivityLocked(ActivityRecord r, ActivityRecord focusedTopActivity,
boolean newTask, boolean keepCurTransition, ActivityOptions options) {
TaskRecord rTask = r.getTask();
final int taskId = rTask.taskId;
// mLaunchTaskBehind tasks get placed at the back of the task stack.
if (!r.mLaunchTaskBehind && (taskForIdLocked(taskId) == null || newTask)) {
// Last activity in task had been removed or ActivityManagerService is reusing task.
// Insert or replace.
// Might not even be in.
insertTaskAtTop(rTask, r);
}
//...
}
结构图:
调用resumeFocusedStackTopActivityLocked方法
frameworks/base/services/core/java/com/android/server/am/ActivityStackSupervisor.java
boolean resumeFocusedStackTopActivityLocked(
ActivityStack targetStack, ActivityRecord target, ActivityOptions targetOptions) {
if (!readyToResume()) {
return false;
}
if (targetStack != null && isFocusedStack(targetStack)) {
return targetStack.resumeTopActivityUncheckedLocked(target, targetOptions);
}
//获取要启动的Activity的状态是不是处于停止状态的ActivityRecord
final ActivityRecord r = mFocusedStack.topRunningActivityLocked();
//如果ActivityRecord不为null,或者要启动的Activity的状态不是RESUMED
if (r == null || !r.isState(RESUMED)) {
//调用ActivityStack的resumeTopActivityUncheckedLocked
mFocusedStack.resumeTopActivityUncheckedLocked(null, null);
} else if (r.isState(RESUMED)) {
// Kick off any lingering app transitions form the MoveTaskToFront operation.
mFocusedStack.executeAppTransition(targetOptions);
}
return false;
}
在 ActivityStack 调用的resumeTopActivityUncheckedLocked
frameworks/base/services/core/java/com/android/server/am/ActivityStack.java
boolean resumeTopActivityUncheckedLocked(ActivityRecord prev, ActivityOptions options) {
if (mStackSupervisor.inResumeTopActivity) {
// Don't even start recursing.
return false;
}
boolean result = false;
try {
// Protect against recursion.
mStackSupervisor.inResumeTopActivity = true;
//这里调用了resumeTopActivityInnerLocked
result = resumeTopActivityInnerLocked(prev, options);
// When resuming the top activity, it may be necessary to pause the top activity (for
// example, returning to the lock screen. We suppress the normal pause logic in
// {@link #resumeTopActivityUncheckedLocked}, since the top activity is resumed at the
// end. We call the {@link ActivityStackSupervisor#checkReadyForSleepLocked} again here
// to ensure any necessary pause logic occurs. In the case where the Activity will be
// shown regardless of the lock screen, the call to
// {@link ActivityStackSupervisor#checkReadyForSleepLocked} is skipped.
final ActivityRecord next = topRunningActivityLocked(true /* focusableOnly */);
if (next == null || !next.canTurnScreenOn()) {
checkReadyForSleep();
}
} finally {
mStackSupervisor.inResumeTopActivity = false;
}
return result;
}
@GuardedBy("mService")
private boolean resumeTopActivityInnerLocked(ActivityRecord prev, ActivityOptions options) {
//...
ActivityStack lastStack = mStackSupervisor.getLastStack();
if (next.app != null && next.app.thread != null) {
//...
} else {
//...
if (DEBUG_STATES) Slog.d(TAG_STATES, "resumeTopActivityLocked: Restarting " + next);
//这里代码非常多,著需要关注调用了ActivityStackSupervisor的startSpecificActivityLocked
mStackSupervisor.startSpecificActivityLocked(next, true, true);
}
if (DEBUG_STACK) mStackSupervisor.validateTopActivitiesLocked();
return true;
}
又回到了 ActivityStackSupervisor 里
frameworks/base/services/core/java/com/android/server/am/ActivityStackSupervisor.java
void startSpecificActivityLocked(ActivityRecord r,
boolean andResume, boolean checkConfig) {
// Is this activity's application already running?
//根据进程名称和 Application 的 UID,来判断目标进程是否已经创建
ProcessRecord app = mService.getProcessRecordLocked(r.processName,
r.info.applicationInfo.uid, true);
getLaunchTimeTracker().setLaunchTime(r);
//判断要启动的Activity所在的应用程序进程如果已经运行的话
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,第二个参数代表要启动的Activity所在的应用程序进程的ProcessRecord
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.
}
//如果没有,则代表进程未创建,调用 AMS 创建 Activity 所在进程
mService.startProcessLocked(r.processName, r.info.applicationInfo, true, 0,
"activity", r.intent.getComponent(), false, false, true);
}
这里 app.thread 指的是 IApplicationThread,它的实现是 ActivityThread 的内部类 ApplicationThread,其中 ApplicationThread 继承了 IApplicationThread.Stub。app 指的传入的要启动的是 Activity 所在的应用程序进程。
这段代码就是要在目标应用进程启动 Activity,当前代码逻辑运行在 AMS 所在的进程(SysstemServer 进程)中,通过 ApplicationThread 来与应用进程进行 Binder 通信。
换句话说,ApplicationThread 是 AMS 所在进程(SystemServer 进程)和应用程序进程通信桥梁。
这里有一个简要的流程来解释 ApplicationThread 的角色和它何时被创建:
- Zygote 进程:Zygote 是 Android 系统中所有应用进程的父进程。它的主要职责是初始化 Dalvik/ART 虚拟机、预加载类和资源等,为启动新的应用进程做好准备。但是,Zygote 不负责直接启动应用进程中的组件如 Activity 或 Service。
- 启动新应用进程:当需要启动一个新的应用程序时,AMS 会请求 Zygote 启动一个新的应用进程。这个新的进程实际上是 Zygote 的一个副本(fork 出来的),包含了已经预加载的资源和环境。
- Application 创建:在这个新启动的应用进程中,Android Runtime 会调用 ActivityThread.main() 方法,这是应用进程的入口点。在这里,会创建一个 ActivityThread 实例,每个应用进程都有自己的 ActivityThread。
- ApplicationThread 创建:ActivityThread 中包含了一个 ApplicationThread 对象,这是一个实现了 IApplicationThread.Stub 接口的 Binder 对象。ApplicationThread 被用来与 AMS 进行跨进程通信(IPC)。AMS 使用这个接口向应用进程发送指令,例如启动或停止 Activity、Service 等。
- 注册到 AMS:一旦 ApplicationThread 创建完成,它会被注册到 AMS,使得 AMS 可以通过它与应用进程交互。这通常发生在应用进程启动后不久,随着 Application 和主 Activity 的创建过程完成。
因此,虽然 ApplicationThread 的存在是为了让应用进程能够与 AMS 通信,但它并不是在 Zygote 初始化阶段创建的,而是在应用进程启动之后,由该进程内部自行创建并初始化的。这样设计允许每个应用进程独立管理自己的生命周期和状态,同时也能接收来自系统的命令。
realStartActivityLock 的代码 Android8 和 Android9 差别比较大,主要是多了事务(Transaction)
frameworks/base/services/core/java/com/android/server/am/ActivityStackSupervisor.java
final boolean realStartActivityLocked(ActivityRecord r, ProcessRecord app,
boolean andResume, boolean checkConfig) throws RemoteException {
//...
try {
//...
// Create activity launch transaction.
//创建了 Activity 启动事务,并传入 app.thread 参数,它是 applicationThread 类型
final ClientTransaction clientTransaction = ClientTransaction.obtain(app.thread,
r.appToken);
//在此处增加了callback调用,这里增加的是一个LaunchActivityItem类,后面会轮询execute
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. 执行 Activity 的启动事务,由 ClientLifecycleManager 来完成
mService.getLifecycleManager().scheduleTransaction(clientTransaction);
//...
} catch (RemoteException e) {
//...
}
} finally {
endDeferResume();
}
//...
return true;
}
应用程序进程创建后会运行代表主线程的实例 ActivityThread,它管理着当前应用程序进程的主线程。ActivityThread 内部有一个 ApplicationThread,调用了 scheduleLauncherActivity 方法:
但是在安卓 9 里找不到对应的代码了,取代这个代码的是:
这里的 ClientTransaction 的 client 是之前传入的 app.thread,是一个 ActivityThread 类
frameworks/base/services/core/java/com/android/server/am/ClientLifecycleManager.java
class ClientLifecycleManager {
void scheduleTransaction(ClientTransaction transaction) throws RemoteException {
final IApplicationThread client = transaction.getClient();
//通过传入的参数调用ClientTransaction的schedule()
transaction.schedule();
if (!(client instanceof Binder)) {
// If client is not an instance of Binder - it's a remote call and at this point it is
// safe to recycle the object. All objects used for local calls will be recycled after
// the transaction is executed on client in ActivityThread.
transaction.recycle();
}
}
}
mClient 就是传入的 app.thread,事务最终是调用 app.thread 的 scheduleTransaction 执行。
到这里startActivity 的操作成功的从AMS 转移到了另一个进程 B 的 ApplicationThread 中
frameworks/base/core/java/android/app/servertransaction/ClientTransaction.java
public class ClientTransaction implements Parcelable, ObjectPoolItem {
private IApplicationThread mClient;
public void schedule() throws RemoteException {
mClient.scheduleTransaction(this);
}
}
frameworks/base/core/java/android/app/ActivityThread.java
public final class ActivityThread extends ClientTransactionHandler {
public void scheduleTransaction(ClientTransaction transaction) throws RemoteException {
//这里应该调用的是ClientTransactionHandler的scheduleTransaction
ActivityThread.this.scheduleTransaction(transaction);
}
}
ActivityThread 启动 Activity 过程
上面代码中的 scheduleTransaction() 方法仍然是调用了 ActivityThread 的 scheduleTransaction() 方法,但实际上这个方法是在 ActivityThread 的父类 ClientTransactionHandler 中实现
这个 scheduleTransaction 只有个 ClientTransactionHandler.java 里有这个函数:
frameworks/base/core/java/android/app/ClientTransactionHandler.java
public abstract class ClientTransactionHandler {
void scheduleTransaction(ClientTransaction transaction) {
transaction.preExecute(this);
//sendMessage方法向H类发送类型为ClientTransaction,发送的消息是EXECUTE_TRANSACTION
sendMessage(ActivityThread.H.EXECUTE_TRANSACTION, transaction);
}
}
sendMessage 方法有多个重载方法,最终调用的是 ActivityThread.java 里的。
./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) {
sendMessage(what, obj, arg1, 0, false);
}
private void sendMessage(int what, Object obj, int arg1, int arg2) {
sendMessage(what, obj, arg1, arg2, false);
}
private void sendMessage(int what, Object obj, int arg1, int arg2, boolean async) {
if (DEBUG_MESSAGES) Slog.v(
TAG, "SCHEDULE " + what + " " + mH.codeToString(what)
+ ": " + arg1 + " / " + obj);
Message msg = Message.obtain();
msg.what = what;
msg.obj = obj;
msg.arg1 = arg1;
msg.arg2 = arg2;
if (async) {
msg.setAsynchronous(true);
}
mH.sendMessage(msg);
}
这里的 mH 指的是H,它是 ActivityThread 的内部类并继承自 Handler,是应用程序进程中主线程的消息管理类。因为 ApplicationThread 是一个 Binder,它的调用逻辑运行在 Binder 线程池中,所以这里需要用 H 将代码的逻辑切换到主线程中:
frameworks/base/core/java/android/app/ActivityThread.java
public final class ActivityThread extends ClientTransactionHandler {
//...
final H mH = new H();
//...
class H extends Handler {
public static final int BIND_APPLICATION = 110;
public static final int EXIT_APPLICATION = 111;
public static final int RECEIVER = 113;
public static final int CREATE_SERVICE = 114;
public static final int SERVICE_ARGS = 115;
public static final int STOP_SERVICE = 116;
//...
public void handleMessage(Message msg) {
if (DEBUG_MESSAGES) Slog.v(TAG, ">>> handling: " + codeToString(msg.what));
switch (msg.what) {
//...
case EXECUTE_TRANSACTION:
//将传递过来的msg.obj转换为ClientTransaction
final ClientTransaction transaction = (ClientTransaction) msg.obj;
//TransactionExecutor调用execute
mTransactionExecutor.execute(transaction);
if (isSystem()) {
// Client transactions inside system process are recycled on the client side
// instead of ClientLifecycleManager to avoid being cleared before this
// message is handled.
transaction.recycle();
}
// TODO(lifecycler): Recycle locally scheduled transactions.
break;
case RELAUNCH_ACTIVITY:
handleRelaunchActivityLocally((IBinder) msg.obj);
break;
}
//...
}
}
}
在TransactionExecutor调用execute 的函数
frameworks/base/core/java/android/app/servertransaction/TransactionExecutor.java
public class TransactionExecutor {
public void execute(ClientTransaction transaction) {
final IBinder token = transaction.getActivityToken();
log("Start resolving transaction for client: " + mTransactionHandler + ", token: " + token);
// 执行 callback
executeCallbacks(transaction);
// 执行 lifecycleState
executeLifecycleState(transaction);
mPendingActions.clear();
log("End resolving transaction");
}
//executeCallbacks会遍历transaction里的所有callback来调用execute()
public void executeCallbacks(ClientTransaction transaction) {
final List<ClientTransactionItem> callbacks = transaction.getCallbacks();
//...
final IBinder token = transaction.getActivityToken();
//从token中获取ActivityClientRecord
ActivityClientRecord r = mTransactionHandler.getActivityClient(token);
//...
final int size = callbacks.size();
for (int i = 0; i < size; ++i) {
final ClientTransactionItem item = callbacks.get(i);
log("Resolving callback: " + item);
final int postExecutionState = item.getPostExecutionState();
final int closestPreExecutionState = mHelper.getClosestPreExecutionState(r,
item.getPostExecutionState());
if (closestPreExecutionState != UNDEFINED) {
//这里都最后调用了cycleToPath
cycleToPath(r, closestPreExecutionState);
}
item.execute(mTransactionHandler, token, mPendingActions);
item.postExecute(mTransactionHandler, token, mPendingActions);
if (r == null) {
// Launch activity request will create an activity record.
r = mTransactionHandler.getActivityClient(token);
}
if (postExecutionState != UNDEFINED && r != null) {
// Skip the very last transition and perform it by explicit state request instead.
final boolean shouldExcludeLastTransition =
i == lastCallbackRequestingState && finalState == postExecutionState;
//这里都最后调用了cycleToPath
cycleToPath(r, postExecutionState, shouldExcludeLastTransition);
}
}
}
}
在 executeCallbacks 中遍历了所有的 ClientTransactionItem 并执行了 ClientTransactionItem 的 execute 方法。
当 Activity 正常启动时,通过 addCallback 添加的是一个 LaunchActivityItem 的实例。
LaunchActivityItem 里的 execute 函数,里面的 client 应该还是 ActivityThread
./frameworks/base/core/java/android/app/servertransaction/LaunchActivityItem.java
public class LaunchActivityItem extends ClientTransactionItem {
//...
public void execute(ClientTransactionHandler client, IBinder token,
PendingTransactionActions pendingActions) {
Trace.traceBegin(TRACE_TAG_ACTIVITY_MANAGER, "activityStart");
ActivityClientRecord r = new ActivityClientRecord(token, mIntent, mIdent, mInfo,
mOverrideConfig, mCompatInfo, mReferrer, mVoiceInteractor, mState, mPersistentState,
mPendingResults, mPendingNewIntents, mIsForward,
mProfilerInfo, client);
//这里就已经到了与 Activity 生命周期相关的方法。
//这里的 client 是 ClientTransactionHandler 类型,
//实际实现类是 ActivityThread,因此最终方法又回到了 ActivityThread。
client.handleLaunchActivity(r, pendingActions, null /* customIntent */);
Trace.traceEnd(TRACE_TAG_ACTIVITY_MANAGER);
}
//...
}
ActivityThread 的 handleLaunchActivity
这是一个比较重要的方法,Activity 的生命周期方法就是在这个方法中有序执行
frameworks/base/core/java/android/app/ActivityThread.java
public Activity handleLaunchActivity(ActivityClientRecord r,
PendingTransactionActions pendingActions, Intent customIntent) {
//...
//初始化Activity的WindowManager,每个Activity都会对应一个窗口
WindowManagerGlobal.initialize();
//调用performLaunchActivity,创建并显示Activity
final Activity a = performLaunchActivity(r, customIntent);
//...
return a;
}
/** Core implementation of activity launch. */
private Activity performLaunchActivity(ActivityClientRecord r, Intent customIntent) {
//获取ActivityInfo类
//用于存储代码以及AndroidManifes设置的Activity和Receiver节点信息
//比如Activity的theme和launchMode
ActivityInfo aInfo = r.activityInfo;
if (r.packageInfo == null) {
//获取APK文件的描述类LoadedApk
r.packageInfo = getPackageInfo(aInfo.applicationInfo, r.compatInfo,
Context.CONTEXT_INCLUDE_CODE);
}
//获取要启动的Activity的ComponentName类,保存了该Activity的包名和类名
ComponentName component = r.intent.getComponent();
//...
//创建启动Activity的上下文环境
ContextImpl appContext = createBaseContextForActivity(r);
Activity activity = null;
try {
//根据component的类名,通过反射创建指定的Activity
//并回调Activity的performCreate方法执行onCreate
java.lang.ClassLoader cl = appContext.getClassLoader();
activity = mInstrumentation.newActivity(
cl, component.getClassName(), r.intent);
StrictMode.incrementExpectedActivityCount(activity.getClass());
//...
} catch (Exception e) {
//...
}
try {
//创建Application,makeApplication会调用Activity里的onCreate方法
Application app = r.packageInfo.makeApplication(false, mInstrumentation);
//...
if (activity != null) {
CharSequence title = r.activityInfo.loadLabel(appContext.getPackageManager());
Configuration config = new Configuration(mCompatConfiguration);
//...
appContext.setOuterContext(activity);
//初始化Activity,在attach方法中会创建Window对象并与Activity自身进行关联
//建立activity与context之间的联系,创建phoneWindow对象,并于Activity关联操作
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);
//...
//调用Instrumentation最终调用Activity的onCreate方法
if (r.isPersistable()) {
mInstrumentation.callActivityOnCreate(activity, r.state, r.persistentState);
} else {
mInstrumentation.callActivityOnCreate(activity, r.state);
}
//...
}
//...
} catch (SuperNotCalledException e) {
//...
} catch (Exception e) {
//...
}
return activity;
}
调用Instrumentation启动Activity
frameworks/base/core/java/android/app/Instrumentation.java
public void callActivityOnCreate(Activity activity, Bundle icicle) {
prePerformCreate(activity);
activity.performCreate(icicle); //调用了Activity的performCreate方法
postPerformCreate(activity);
}
调用了Activity的performCreate方法
frameworks/base/core/java/android/app/Activity.java
final void performCreate(Bundle icicle, PersistableBundle persistentState) {
mCanEnterPictureInPicture = true;
restoreHasCurrentPermissionRequest(icicle);
if (persistentState != null) { //调用onCreate方法
onCreate(icicle, persistentState);
} else {
onCreate(icicle);
}
writeEventLog(LOG_AM_ON_CREATE_CALLED, "performCreate");
mActivityTransitionState.readState(icicle);
mVisibleFromClient = !mWindow.getWindowStyle().getBoolean(
com.android.internal.R.styleable.Window_windowNoDisplay, false);
mFragments.dispatchActivityCreated();
mActivityTransitionState.setEnterActivityOptions(this, getActivityOptions());
}
至此,目标 Activity 已经成功创建,并执行生命周期方法。
根 Activity 启动过程中涉及的进程
根 Activity 启动过程中涉及 4 个进程,分别是 Zygote 进程、Launcher 进程、AMS 所在的进程(SystemServer 进程)、应用程序进程。
- Laucnher 向 AMS 请求创建根 Activity
- AMS 判断根 Activity 所需的应用进程是否存在并启动,如果不存在 Zygote 创建应用程序进程。
- 应用程序进程启动后,AMS 请求创建应用程序进程并启动根 Activity
在步骤 1、步骤 4 使用 Binder 通信,步骤 2 使用 Socket 通信
如果是普通 Activity 启动,只涉及 AMS 所在的进程和应用程序进程。
Activity 初始化和销毁执行顺序
frameworks/base/core/java/android/app/servertransaction/TransactionExecutor.java
public class TransactionExecutor {
public void cycleToPath(ActivityClientRecord r, int finish) {
cycleToPath(r, finish, false /* excludeLastState */);
}
/**
* Transition the client between states with an option not to perform the last hop in the
* sequence. This is used when resolving lifecycle state request, when the last transition must
* be performed with some specific parameters.
*/
private void cycleToPath(ActivityClientRecord r, int finish,
boolean excludeLastState) {
// 获取当前 Activity 的生命周期状态,即开始时的状态,所以start是3
final int start = r.getLifecycleState();
log("Cycle from: " + start + " to: " + finish + " excludeLastState:" + excludeLastState);
// 获取要执行的生命周期数组
final IntArray path = mHelper.getLifecyclePath(start, finish, excludeLastState);
// 按顺序执行 Activity 的生命周期
performLifecycleSequence(r, path);
}
//总结:
//首先获取了当前 Activity 生命周期状态,即开始执行 getLifecyclePath 时 Activity 的生命周期状态,
//由于 executeLifecycleState 方法是在 executeCallback 之后执行的,上面我们已经提到此时的 Activity 已经执行完了创建流程,
//并执行过了 onCreate 的生命周期。因此,这里的 start 应该是 ON_CREATE 状态,ON_CREATE 的值为 1
private void performLifecycleSequence(ActivityClientRecord r, IntArray path) {
final int size = path.size();
// 遍历数组,执行 Activity 的生命周期,path里面包含了finish的状态
// 就依次从ON_CREATE开始,直到ON_RESUME结束
for (int i = 0, state; i < size; i++) {
state = path.get(i);
log("Transitioning to state: " + state);
switch (state) {
case ON_CREATE:
mTransactionHandler.handleLaunchActivity(r, mPendingActions,
null /* customIntent */);
break;
case ON_START:
mTransactionHandler.handleStartActivity(r, mPendingActions);
break;
case ON_RESUME:
mTransactionHandler.handleResumeActivity(r.token, false /* finalStateRequest */,
r.isForward, "LIFECYCLER_RESUME_ACTIVITY");
break;
case ON_PAUSE:
mTransactionHandler.handlePauseActivity(r.token, false /* finished */,
false /* userLeaving */, 0 /* configChanges */, mPendingActions,
"LIFECYCLER_PAUSE_ACTIVITY");
break;
case ON_STOP:
mTransactionHandler.handleStopActivity(r.token, false /* show */,
0 /* configChanges */, mPendingActions, false /* finalStateRequest */,
"LIFECYCLER_STOP_ACTIVITY");
break;
case ON_DESTROY:
mTransactionHandler.handleDestroyActivity(r.token, false /* finishing */,
0 /* configChanges */, false /* getNonConfigInstance */,
"performLifecycleSequence. cycling to:" + path.get(size - 1));
break;
case ON_RESTART:
mTransactionHandler.performRestartActivity(r.token, false /* start */);
break;
default:
throw new IllegalArgumentException("Unexpected lifecycle state: " + state);
}
}
}
}
流程图语法记录:
zenuml
title Launcher请求AMS过程
Launcher.startActivitySafely
Launcher -> Activity.startActivity
Activity -> Activity.startActivityForResult
Activity -> Instrumentation.execStartActivity {
ActivityTaskManager.getService {
return AcitvityMangerService
}
ActivityManagerService.startActivity
}