启动 Activity#
// 启动指定 Activity
void startBootActivity() {
Intent i = new Intent(this, BootActivity.class);
startActivity(i);
}
Activity 调用 ActivityTaskManagerService#
Activity 不会直接接触到 ActivityTaskManagerService,而是透过 Instrumentation 呼叫Acitivty#startActivity 方法:最终都会导向 Activity#startActivityForResult方法,再透过 Instrumentation 请求启动 Activity
其中有一个重点是它会传入目前进程的 ApplicationThread另一个则是 mToken
参数,它代表了当前应用在 AMS 中 ActivityManager 的代表
// Activity.java
public class Activity extends ContextThemeWrapper
implements LayoutInflater.Factory2,
Window.Callback, KeyEvent.Callback,
...省略部分接口 {
/*package*/ ActivityThread mMainThread;
private Instrumentation mInstrumentation;
@Override
public void startActivity(Intent intent) {
this.startActivity(intent, null);
}
@Override
public void startActivity(Intent intent, @Nullable Bundle options) {
if (mIntent != null && mIntent.hasExtra(AutofillManager.EXTRA_RESTORE_SESSION_TOKEN)
&& mIntent.hasExtra(AutofillManager.EXTRA_RESTORE_CROSS_ACTIVITY)) {
... 省略部分
}
// @ 分析 startActivityForResult
if (options != null) {
startActivityForResult(intent, -1, options);
} else {
startActivityForResult(intent, -1);
}
}
public void startActivityForResult(@RequiresPermission Intent intent, int requestCode,
@Nullable Bundle options) {
if (mParent == null) {
options = transferSpringboardActivityOptions(options);
// @ 追踪 Instrumentation#execStartActivity 函數,mMainThread 就是 ActivityThread
Instrumentation.ActivityResult ar =
mInstrumentation.execStartActivity(
// @ 查看 getApplicationThread 方法
this, mMainThread.getApplicationThread(),
mToken, // 类型为 IBinder,ActivityRecord 的代理物件
this,
intent, requestCode, options);
... 省略部分
} else {
... 省略部分
}
}
}
// ---------------------------------------------------------
// ActivityThread .java
public final class ActivityThread extends ClientTransactionHandler
implements ActivityThreadInternal {
// 一个应用行程只有一个
final ApplicationThread mAppThread = new ApplicationThread();
public ApplicationThread getApplicationThread()
{
return mAppThread;
}
private class ApplicationThread extends IApplicationThread.Stub {
... 省略細節
}
}
Acitivty 的请求都会通过 Instrumentation 类(这个就算是一个 Hook),用来监控应用与系统 AMS 互动过程
Instrumentation#execStartActivity
方法:最后在启动了ActivityTaskManage#startActivity
方法 取得代理类与 ATMS 进程通信 (ATMS 属于 SystemServer 进程)
// Instrumentation.java
public class Instrumentation {
public ActivityResult execStartActivity(
Context who, IBinder contextThread, IBinder token, Activity target,
Intent intent, int requestCode, Bundle options) {
IApplicationThread whoThread = (IApplicationThread) contextThread;
... 省略部分
try {
...省略部分
// 启动了 ActivityTaskManager#startActivity 函数
// whoThread 就是 IApplicationThread
int result = ActivityTaskManager.getService().startActivity(whoThread,
who.getBasePackageName(), who.getAttributionTag(), intent,
intent.resolveTypeIfNeeded(who.getContentResolver()), token,
target != null ? target.mEmbeddedID : null, requestCode, 0, null, options);
// 检查AMS启动Activity启动结果的检查
checkStartActivityResult(result, intent);
} catch (RemoteException e) {
throw new RuntimeException("Failure from system", e);
}
return null;
}
}
Instrumentation 的行为主要是透过 ActivityTaskManager 取得 Binder 代理类与 ActivityTaskManagerService 通信
// Instrumentation.java
public static void checkStartActivityResult(int res, Object intent) {
if (!ActivityManager.isStartResultFatalError(res)) {
return;
}
switch (res) {
// 在 Android Manifest 沒有注册
case ActivityManager.START_INTENT_NOT_RESOLVED:
case ActivityManager.START_CLASS_NOT_FOUND:
if (intent instanceof Intent && ((Intent)intent).getComponent() != null)
throw new ActivityNotFoundException(
"Unable to find explicit activity class "
+ ((Intent)intent).getComponent().toShortString()
+ "; have you declared this activity in your AndroidManifest.xml?");
throw new ActivityNotFoundException(
"No Activity found to handle " + intent);
// 权限禁止
case ActivityManager.START_PERMISSION_DENIED:
throw new SecurityException("Not allowed to start activity "
+ intent);
// 请求冲突
case ActivityManager.START_FORWARD_AND_REQUEST_CONFLICT:
throw new AndroidRuntimeException(
"FORWARD_RESULT_FLAG used while also requesting a result");
... 省略部分
default:
throw new AndroidRuntimeException("Unknown error code "
+ res + " when starting " + intent);
}
}
ActivityTaskManager 透过 Binder 机制最终就会到达 系统进程 的 ActivityTaskManagerService (AIDL 的 Server 端)
重点参数 | 说明 |
---|---|
caller | 呼叫者 |
intent | 准备呼叫的 Activity 信息 |
resultTo | 呼叫者 在 AMS 中的 ActivityRecord |
// ActivityTaskManagerService.java
// SystemService 启动的系统进程
// IActivityTaskManager.Stub 是 Service 端的实作
public class ActivityTaskManagerService extends IActivityTaskManager.Stub { // IActivityTaskManager 是 IDE 自動生成類
@Override
public final int startActivity(IApplicationThread caller, String callingPackage,
String callingFeatureId, Intent intent, String resolvedType, IBinder resultTo,
String resultWho, int requestCode, int startFlags, ProfilerInfo profilerInfo,
Bundle bOptions) {
// @ 分析 startActivityAsUser
return startActivityAsUser(caller, // 呼叫者 IApplicationThread
callingPackage,
callingFeatureId,
intent, // 准备呼叫的Activity信息
resolvedType,
resultTo, // 呼叫者 在 AMS 中的 ActivityRecord
resultWho, requestCode, startFlags, profilerInfo, bOptions,
UserHandle.getCallingUserId());
}
}
ActivityStartController - 准备 ActivityStart#
startActivity
(使用者行程) -> Binder -> startActivityAsUser
(系统行程),最后透过 ActivityStartController 来启动指定的 Activity
// ActivityTaskManagerService.java
public class ActivityTaskManagerService extends IActivityTaskManager.Stub {
/**
* @call呼叫者的IBinder(就是应用行程的Binder Server),
* 对应的就是ActivityThread#ApplicationThread(内部类)
*/
@Override
public final int startActivity(IApplicationThread caller, String callingPackage,
String callingFeatureId, Intent intent, String resolvedType, IBinder resultTo,
String resultWho, int requestCode, int startFlags, ProfilerInfo profilerInfo,
Bundle bOptions) {
// @ 查看 startActivityAsUser
return startActivityAsUser(caller, callingPackage, callingFeatureId, intent, resolvedType,
resultTo, resultWho, requestCode, startFlags, profilerInfo, bOptions,
UserHandle.getCallingUserId());
}
@Override
public int startActivityAsUser(IApplicationThread caller, String callingPackage,
/*省略部分參數*/) {
// @ 查看 startActivityAsUser
return startActivityAsUser(caller, callingPackage, callingFeatureId, intent, resolvedType,
resultTo, resultWho, requestCode, startFlags, profilerInfo, bOptions, userId,
true /*validateIncomingUser*/);
}
private int startActivityAsUser(IApplicationThread caller, String callingPackage,
/*省略部分參數*/) {
assertPackageMatchesCallingUid(callingPackage);
enforceNotIsolatedCaller("startActivityAsUser");
userId = getActivityStartController().checkTargetUser(userId, validateIncomingUser,
Binder.getCallingPid(), Binder.getCallingUid(), "startActivityAsUser");
// obtainStarter 返回一个ActivityStarter类
return getActivityStartController().obtainStarter(intent, "startActivityAsUser")
.setCaller(caller)
.setCallingPackage(callingPackage)
.setCallingFeatureId(callingFeatureId)
.setResolvedType(resolvedType)
.setResultTo(resultTo)
.setResultWho(resultWho)
.setRequestCode(requestCode)
.setStartFlags(startFlags)
.setProfilerInfo(profilerInfo)
.setActivityOptions(bOptions)
.setUserId(userId)
.execute(); // 直接查看 ActivityStarter#execute 函数
}
}
从 ActivityStartController 可以取得复用(obtain)的 ActivityStarter 类
这里 ActivityStartController 有使用到 工厂模式,目标产生产品是 ActivityStarter
ActivityStarter是使用 Builder 模式,可以设定需要请动 Activity 的选项
ActivityStarter#execute
主要有两个动作:
- 判断目标 Activity 是否是重量级
- 执行应用(APP)行程的启动 Activity 请求
// ActivityStarter.java
private final ActivityTaskSupervisor mSupervisor;
// Request 是内部类
Request mRequest = new Request();
class ActivityStarter {
int execute() {
try {
int res;
if (mRequest.activityInfo == null) {
// @ 分析 resolveActivity 方法
mRequest.resolveActivity(mSupervisor);
}
// 线程锁
synchronized (mService.mGlobalLock) {
... 省略部分
//下一小节会分析这两个方法
// 1.判断目标Activity是否是重量级
res = resolveToHeavyWeightSwitcherIfNeeded();
if (res != START_SUCCESS) {
return res;
}
// 2. 执行activity请求
res = executeRequest(mRequest);
... 省略部分
}
}
}
static class Request {
ActivityInfo activityInfo;
void resolveActivity(ActivityTaskSupervisor supervisor) {
...
// @ 分析 resolveIntent 方法
resolveInfo = supervisor.resolveIntent(intent, resolvedType, userId,
0 /* matchFlags */,
computeResolveFilterUid(callingUid, realCallingUid, filterCallingUid));
...
activityInfo = supervisor.resolveActivity(intent, resolveInfo, startFlags,
profilerInfo);
}
}
}
ActivityTaskSupervisor#resolveActivity
:到 PackageManagerService 找到对应的 Acitiviy 信息(也就是 ActivityInfo)
// ActivityTaskSupervisor.java
final ActivityTaskManagerService mService;
ResolveInfo resolveIntent(Intent intent, String resolvedType, int userId, int flags,
int filterCallingUid) {
try {
... 省略部分
final long token = Binder.clearCallingIdentity();
try {
// 透过 PKMS 取得 ResolveInfo
return mService.getPackageManagerInternalLocked().resolveIntent(
intent, resolvedType, modifiedFlags, privateResolveFlags, userId, true,
filterCallingUid);
} finally {
Binder.restoreCallingIdentity(token);
}
} /* 省略 finally */
}
ActivityInfo resolveActivity(Intent intent, ResolveInfo rInfo, int startFlags,
ProfilerInfo profilerInfo) {
// ActivityInfo 在 ResolveInfo 內
final ActivityInfo aInfo = rInfo != null ? rInfo.activityInfo : null;
...
return aInfo;
}
ActivityStarter - 准备启动 execute#
ActivityStarter#resolveToHeavyWeightSwitcherIfNeeded
:判断目标 Activity 是否是重量级,若当前系统中已经存在的重量级进程,并且里面有你要 Activity,就直接返回
若你将要启动的 Activity 是重量级进程但不存在,那就会继续往下执行赋予新 Intent
// ActivityStarter.java
private final ActivityTaskManagerService mService;
/**
* 如果这是一个重量级进程而已经有另一个不同的重量级进程在运行,
* 则更新对重量级切换的请求
*/
private int resolveToHeavyWeightSwitcherIfNeeded() {
... 省略部分
// 判断是否已经启动
final WindowProcessController heavy = mService.mHeavyWeightProcess;
if (heavy == null ||
(heavy.mInfo.uid == mRequest.activityInfo.applicationInfo.uid
&& heavy.mName.equals(mRequest.activityInfo.processName))
) {
return START_SUCCESS;
}
... 省略部分
// 创建新 Intent
final Intent newIntent = new Intent();
if (mRequest.requestCode >= 0) {
// Caller is requesting a result.
newIntent.putExtra(HeavyWeightSwitcherActivity.KEY_HAS_RESULT, true);
}
newIntent.putExtra(HeavyWeightSwitcherActivity.KEY_INTENT, new IntentSender(target));
heavy.updateIntentForHeavyWeightActivity(newIntent);
newIntent.putExtra(HeavyWeightSwitcherActivity.KEY_NEW_APP,
mRequest.activityInfo.packageName);
newIntent.setFlags(mRequest.intent.getFlags());
newIntent.setClassName("android" /* packageName */,
HeavyWeightSwitcherActivity.class.getName());
mRequest.intent = newIntent;
... 省略部分
return START_SUCCESS;
}
ActivityStarter#executeRequest
:执行启动 Activity 动作,以下执行的动作可以分为
判断 caller(呼叫者进程)是否还存活,有可能调用者(APP)被系统杀掉、异常退出等等,这时候 caller 就会消失
处理 Intent flag 的 FLAG_ACTIVITY_FORWARD_RESULT
,FLAG_ACTIVITY_FORWARD_RESULT
具有跨越是传递功能,当启用后,setResult 结果会返回到来源 Acitivty
判断是否支持该 Intent(多个判断)
透过 ActivityTaskManagerService、ActivityTaskSupervisor 判断启动权限
创建 ActivityRecord 对象,并呼叫 startActivityUnchecked 方法
// ActivityStarter.java
private final ActivityTaskManagerService mService;
private final ActivityTaskSupervisor mSupervisor;
private int mLastStartActivityResult;
private int executeRequest(Request request) {
// 使用者 APP 行程
final IApplicationThread caller = request.caller;
// Actiivty 相关信息
ActivityInfo aInfo = request.activityInfo;
// 该Activity所属的Task(Stack)
Task inTask = request.inTask;
// 1. 判断 caller 是否存在
WindowProcessController callerApp = null;
if (caller != null) {
callerApp = mService.getProcessController(caller);
if (callerApp != null) {
callingPid = callerApp.getPid();
callingUid = callerApp.mInfo.uid;
} else {
// 调用者如果不存在则 START_PERMISSION_DENIED
err = ActivityManager.START_PERMISSION_DENIED;
}
}
... 省略部分
ActivityRecord sourceRecord = null; // 启动来源
ActivityRecord resultRecord = null; // 目标结果
if (resultTo != null) {
sourceRecord = mRootWindowContainer.isInAnyStack(resultTo);
... Debug 訊息
if (sourceRecord != null) {
if (requestCode >= 0 && !sourceRecord.finishing) {
resultRecord = sourceRecord;
}
}
}
final int launchFlags = intent.getFlags();
// 2. FLAG_ACTIVITY_FORWARD_RESULT 具有跨越是传递功能
if ((launchFlags & Intent.FLAG_ACTIVITY_FORWARD_RESULT) != 0 && sourceRecord != null) {
// 不能再使用 startActivityForResult 方法
if (requestCode >= 0) {
// 否则会报START_FORWARD_AND_REQUEST_CONFLICT错误
SafeActivityOptions.abort(options);
return ActivityManager.START_FORWARD_AND_REQUEST_CONFLICT;
}
resultRecord = sourceRecord.resultTo;
if (resultRecord != null && !resultRecord.isInStackLocked()) {
resultRecord = null;
}
// 转换setResult结果到来源Activity
resultWho = sourceRecord.resultWho;
requestCode = sourceRecord.requestCode;
sourceRecord.resultTo = null;
if (resultRecord != null) {
resultRecord.removeResultsLocked(sourceRecord, resultWho, requestCode);
}
if (sourceRecord.launchedFromUid == callingUid) {
callingPackage = sourceRecord.launchedFromPackage;
callingFeatureId = sourceRecord.launchedFromFeatureId;
}
}
... 省略部分
// 3. 判断是否支持该Intent
if (err == ActivityManager.START_SUCCESS && aInfo == null) {
err = ActivityManager.START_CLASS_NOT_FOUND;
}
if (err == ActivityManager.START_SUCCESS && sourceRecord != null
&& sourceRecord.getTask().voiceSession != null) {
// 语音相关
if ((launchFlags & FLAG_ACTIVITY_NEW_TASK) == 0
&& sourceRecord.info.applicationInfo.uid != aInfo.applicationInfo.uid) {
try {
intent.addCategory(Intent.CATEGORY_VOICE); // 語音
if (!mService.getPackageManager().activitySupportsIntent(
intent.getComponent(), intent, resolvedType)) {
Slog.w(TAG, "Activity being started in current voice task does not support "
+ "voice: " + intent);
err = ActivityManager.START_NOT_VOICE_COMPATIBLE;
}
} catch (RemoteException e) {
Slog.w(TAG, "Failure checking voice capabilities", e);
err = ActivityManager.START_NOT_VOICE_COMPATIBLE;
}
}
}
...省略部分
// 4. 必须经过三种判断,判断调用者是否有权限来启动Activity
boolean abort = !mSupervisor.checkStartAnyActivityPermission(intent, aInfo, resultWho,
requestCode, /* 省略部份参数*/);
abort |= !mService.mIntentFirewall.checkStartActivity(intent, callingUid,
callingPid, resolvedType, aInfo.applicationInfo);
abort |= !mService.getPermissionPolicyInternal().checkStartActivity(intent, callingUid,
callingPackage);
boolean restrictedBgActivity = false;
if (!abort) {
try {
restrictedBgActivity = shouldAbortBackgroundActivityStart(callingUid,
callingPid, callingPackage, realCallingUid, realCallingPid, callerApp,
request.originatingPendingIntent, request.allowBackgroundActivityStart,
intent);
} /* 省略 finally */
}
... 省略部分
// 5. 创建ActivityRecord,记录各种判断结果
final ActivityRecord r = new ActivityRecord.Builder(mService)
.setCaller(callerApp)
.setLaunchedFromPid(callingPid)
.setLaunchedFromUid(callingUid)
.setLaunchedFromPackage(callingPackage)
.setLaunchedFromFeature(callingFeatureId)
.setIntent(intent)
.setResolvedType(resolvedType)
.setActivityInfo(aInfo)
.setConfiguration(mService.getGlobalConfiguration())
.setResultTo(resultRecord)
.setResultWho(resultWho)
.setRequestCode(requestCode)
.setComponentSpecified(request.componentSpecified)
.setRootVoiceInteraction(voiceSession != null)
.setActivityOptions(checkedOptions)
.setSourceRecord(sourceRecord)
.build();
mLastStartActivityRecord = r;
... 省略部分
final ActivityStack resultStack = resultRecord == null
? null : resultRecord.getRootTask();
// @ 分析 startActivityUnchecked 方法
mLastStartActivityResult = startActivityUnchecked(r, sourceRecord, voiceSession,
request.voiceInteractor, startFlags, true /* doResume */, checkedOptions, inTask,
restrictedBgActivity, intentGrants);
...
return mLastStartActivityResult;
}
ActivityStarter 依赖ActivityRecord#Builder
,透过 Builder 模式来创建 ActivityRecord 对象,这个 Activity 中纪录呼叫、目标 Activity
描述者 | 代表 Activity 类 |
---|---|
PKMS | ActivityInfo (AndroidManifest 内的节点信息) |
AMS | ActivityRecord |
ActivityStarter - Activity 启动流程#
重点包括
- 决定 Activity 目标 Task
- 显示 Activity 启动动画
- 通知 RootWindowContainer 启动 Acitivty 的 Window 视窗
- 在 executeRequest 函数中,最后会呼叫到 startActivityUnchecked 方法,以下简单说明这些方法的功能
ActivityStarter 重点方法 | 功能 |
---|---|
executeRequest | 检查权限、Caller (Client 端的 IBinder) 等等 |
startActivityUnchecked | 经过检查后,准备启动 Activity,若启动失败也在负责移除 |
startActivityInner | 主要是对 Activity 栈的控制,可添加 Activity 到 stack 当中 or 通知 Intent |
// ActivityStarter.java
// executeRequest 呼叫该 Function
private int startActivityUnchecked(final ActivityRecord r, ActivityRecord sourceRecord,
IVoiceInteractionSession voiceSession, IVoiceInteractor voiceInteractor,
int startFlags, boolean doResume, ActivityOptions options, Task inTask,
boolean restrictedBgActivity, NeededUriGrants intentGrants) {
int result = START_CANCELED;
final Task startedActivityRootTask;
...
try {
...
// @ 分析 startActivityInner 方法
result = startActivityInner(r, sourceRecord, voiceSession, voiceInteractor,
startFlags, doResume, options, inTask, restrictedBgActivity, intentGrants);
...
} finally {
...
startedActivityRootTask = handleStartResult(r, result);
...
}
postStartActivityProcessing(r, result, startedActivityStack);
return result;
}
ActivityStarter#startActivityInner
方法:如果没设定其他 Flag,最后就会启动 Task#startActivityLocked
方法,该方法有两个重点
定义 ActivityStarter 的 mSourceRootTask
、mTargetRootTask
成员,决定 Activity 所属的来源、目标栈 (Task)
// ActivityStarter.java
private Task mSourceRootTask; // 来源
private Task mTargetRootTask; // 启动目标
ActivityRecord mStartActivity;
private final ActivityTaskManagerService mService;
private final RootWindowContainer mRootWindowContainer;
int startActivityInner(final ActivityRecord r,
ActivityRecord sourceRecord,
/* 省略部份*/ ) {
...省略部分
// 取得可重用的 Task
final Task reusedTask = getReusableTask();
final Task targetTask = reusedTask != null ? reusedTask : computeTargetTask();
// 是否创建新 Task
final boolean newTask = targetTask == null;
mTargetTask = targetTask;
computeLaunchParams(r, sourceRecord, targetTask);
// 判断当前 ActivtyRecord 是否能在目标 Task 启动
int startResult = isAllowedToStart(r, newTask, targetTask);
if (startResult != START_SUCCESS) {
return startResult;
}
// 如果是复用 Task,则取得目标栈顶 Activity (尚未 finsih)
final ActivityRecord targetTaskTop = newTask
? null : targetTask.getTopNonFinishingActivity();
if (targetTaskTop != null) {
// 重复使用 Task
startResult = recycleTask(targetTask, targetTaskTop, reusedTask, intentGrants);
if (startResult != START_SUCCESS) {
return startResult;
}
} else {
mAddingToTask = true;
}
...
if (mTargetRootTask == null) {
mTargetRootTask = getLaunchRootTask(mStartActivity, mLaunchFlags, targetTask, mOptions);
}
// 依照当前分析狀況,会启动新 Task
if (newTask) {
final Task taskToAffiliate = (mLaunchTaskBehind && mSourceRecord != null)
? mSourceRecord.getTask() : null;
// 设定新 Task
setNewTask(taskToAffiliate);
} else if (mAddingToTask) {
addOrReparentStartingActivity(targetTask, "adding to task");
}
...省略部分
return START_SUCCESS;
}
分析 Intent;设定 Activity 启动画面 startActivityLocked
、启动 Acitivty resumeFocusedTasksTopActivities
// ActivityStarter.java
private Task mSourceRootTask;
private Task mTargetRootTask;
ActivityRecord mStartActivity;
private final ActivityTaskManagerService mService;
private final RootWindowContainer mRootWindowContainer;
int startActivityInner(final ActivityRecord r,
ActivityRecord sourceRecord, // 呼叫者 資訊
/* 省略部分參數 */) {
...
// @ 1. 分析 Intent,设定 Activity 启动画面 (先分析)
mTargetRootTask.startActivityLocked(mStartActivity,
topStack != null ? topStack.getTopNonFinishingActivity() : null, newTask,
mKeepCurTransition, mOptions);
if (mDoResume) { // 该 Activity 存在
final ActivityRecord topTaskActivity =
mStartActivity.getTask().topRunningActivityLocked();
if (!mTargetRootTask.isTopActivityFocusable()
|| (topTaskActivity != null && topTaskActivity.isTaskOverlay()
&& mStartActivity != topTaskActivity)) {
//如果没有不可聚焦(Fousable)则无法回复(resume),
//但仍会让该Activity可见
//也就是可见的暂停状态
mTargetRootTask.ensureActivitiesVisible(null /* starting */,
0 /* configChanges */, !PRESERVE_WINDOWS);
mTargetRootTask.mDisplayContent.executeAppTransition();
} else {
// 若栈顶Activity不在焦点上,则将其移动到前面
if (mTargetRootTask.isTopActivityFocusable()
&& !mRootWindowContainer.isTopDisplayFocusedRootTask(mTargetRootTask)) {
mTargetRootTask.moveToFront("startActivityInner");
}
// 2. @ 开始新的活动(后分析)
mRootWindowContainer.resumeFocusedTasksTopActivities(
mTargetRootTask, mStartActivity, mOptions, mTransientLaunch);
}
}
...
return START_SUCCESS;
}
Task 分析 Intent - 添加 Activity 启动画面#
Task#startActivityLocked方法:主要是 判断使用者设定的 Intent、设定 Activity 初始加载的画面,最后 透过 AcitivtyRecord 来启动 Activity 开始动画
// TaskFragment.java
class TaskFragment extends WindowContainer<WindowContainer> {
final ActivityTaskSupervisor mTaskSupervisor;
...
}
// ------------------------------------------------------
// Task.java
class Task extends TaskFragment {
void startActivityLocked(ActivityRecord r, @Nullable ActivityRecord focusedTopActivity,
boolean newTask, boolean keepCurTransition, ActivityOptions options,
@Nullable ActivityRecord sourceRecord) {
Task rTask = r.getTask();
final boolean allowMoveToFront = options == null || !options.getAvoidMoveToFront();
final boolean isOrhasTask = rTask == this || hasChild(rTask);
...
final Task activityTask = r.getTask();
if (task == activityTask && mChildren.indexOf(task) != (getChildCount() - 1)) {
mStackSupervisor.mUserLeaving = false;
...
}
task = activityTask;
... 省略 Debug 訊息
// The transition animation and starting window are not needed if {@code allowMoveToFront}
// is false, because the activity won't be visible.
if ((!isHomeOrRecentsStack() ||
hasActivity()) && allowMoveToFront) {
final DisplayContent dc = getDisplay().mDisplayContent;
... 省略 Debug 訊息
if ((r.intent.getFlags() & Intent.FLAG_ACTIVITY_NO_ANIMATION) != 0) {
// 无跳转动画
dc.prepareAppTransition(TRANSIT_NONE, keepCurTransition);
// 添加无动画 intent
mStackSupervisor.mNoAnimActivities.add(r);
} else {
// 需要跳转动画
int transit = TRANSIT_ACTIVITY_OPEN;
if (newTask) {
if (r.mLaunchTaskBehind) {
transit = TRANSIT_TASK_OPEN_BEHIND;
} else if (getDisplay().isSingleTaskInstance()) {
transit = TRANSIT_SHOW_SINGLE_TASK_DISPLAY;
keepCurTransition = false;
} else {
if (canEnterPipOnTaskSwitch(focusedTopActivity,
null /* toFrontTask */, r, options)) {
focusedTopActivity.supportsEnterPipOnTaskSwitch = true;
}
transit = TRANSIT_TASK_OPEN;
}
}
dc.prepareAppTransition(transit, keepCurTransition);
mStackSupervisor.mNoAnimActivities.remove(r);
}
boolean doShow = true;
if (newTask) { // 启动一个新栈
if ((r.intent.getFlags() & Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED) != 0) {
resetTaskIfNeeded(r, r);
doShow = topRunningNonDelayedActivityLocked(null) == r;
}
} else if (options != null && options.getAnimationType()
== ActivityOptions.ANIM_SCENE_TRANSITION) {
doShow = false;
}
if (r.mLaunchTaskBehind) {
...
} else if (SHOW_APP_STARTING_PREVIEW && doShow) {
...
// @ 追踪 showStartingWindow 方法
// r 是 ActivityRecord
r.showStartingWindow(prev, newTask, isTaskSwitch(r, focusedTopActivity));
}
} else {
...
}
}
}
RootWindowContainer 启动栈顶 Activity#
RootWindowContainer#resumeFocusedTasksTopActivities方法:找到、并让 Task 栈上的顶端 Activity 显示(可聚焦 Focused 的 Activity)
// RootWindowContainer.java
ActivityTaskSupervisor mTaskSupervisor;
boolean resumeFocusedTasksTopActivities(
Task targetRootTask, ActivityRecord target, ActivityOptions targetOptions) {
// @ 追蹤 resumeFocusedTasksTopActivities
return resumeFocusedTasksTopActivities(targetRootTask, target, targetOptions,
false /* deferPause */);
}
boolean resumeFocusedTasksTopActivities(
Task targetRootTask, ActivityRecord target, ActivityOptions targetOptions,
boolean deferPause) {
if (!mTaskSupervisor.readyToResume()) {
return false;
}
boolean result = false;
if (targetRootTask != null && (targetRootTask.isTopRootTaskInDisplayArea()
|| getTopDisplayFocusedRootTask() == targetRootTask)) {
result = targetRootTask.resumeTopActivityUncheckedLocked(target, targetOptions,
deferPause);
}
for (int displayNdx = getChildCount() - 1; displayNdx >= 0; --displayNdx) {
final DisplayContent display = getChildAt(displayNdx);
final boolean curResult = result;
boolean[] resumedOnDisplay = new boolean[1];
display.forAllRootTasks(rootTask -> {
// 頂層 Activity
final ActivityRecord topRunningActivity =
rootTask.topRunningActivity();
if (!rootTask.isFocusableAndVisible() || topRunningActivity == null) {
return;
}
if (rootTask == targetRootTask) {
// 已經在 resumed 狀態,不再 resumed
resumedOnDisplay[0] |= curResult;
return;
}
if (rootTask.getDisplayArea().isTopRootTask(rootTask)
&& topRunningActivity.isState(RESUMED)) {
// Kick off any lingering app transitions form the MoveTaskToFront
// operation, but only consider the top task and root-task on that
// display.
rootTask.executeAppTransition(targetOptions);
} else {
resumedOnDisplay[0] |= topRunningActivity.makeActiveIfNeeded(target);
}
});
result |= resumedOnDisplay[0];
if (!resumedOnDisplay[0]) { // 尚未啟動
// display 是 DisplayContent 對象
final Task focusedRoot = display.getFocusedRootTask();
if (focusedRoot != null) {
// @ 继续分析 resumeTopActivityUncheckedLocked 方法
result |= focusedRoot.resumeTopActivityUncheckedLocked(target, targetOptions);
} else if (targetRootTask == null) {
// ... 找不到 Task,启动 HomeActivity
result |= resumeHomeActivity(null /* prev */, "no-focusable-task",
display.getDefaultTaskDisplayArea());
}
}
}
return result;
}
先看看 Task & Window 的关系,Task 关联 ActivityRecord,并使用连接串起多个 Task,ActivityRecord 又可以管理多个 Window 画面
调用 Task#resumeTopActivityUncheckedLocked函数,该目的在找到 Task 末端节点,并执行 resumeTopActivityInnerLocked
函数
// Task.java
boolean resumeTopActivityUncheckedLocked(ActivityRecord prev, ActivityOptions options,
boolean deferPause) {
if (mInResumeTopActivity) {
// Don't even start recursing.
return false;
}
boolean someActivityResumed = false;
try {
// Protect against recursion.
mInResumeTopActivity = true;
// 找到末端节点
if (isLeafTask()) {
if (isFocusableAndVisible()) {
// 递归结束&发现可用Activity就启动
// @分析resumeTopActivityInnerLocked方法
someActivityResumed = resumeTopActivityInnerLocked(
prev,
options,
deferPause);
}
} else {
int idx = mChildren.size() - 1;
while (idx >= 0) {
final Task child = (Task) getChildAt(idx--);
// 找到 Top 並且可 Focus 的 Activity
if (!child.isTopActivityFocusable()) {
continue;
}
// 该 Task 不可见
if (child.getVisibility(null /* starting */) != TASK_VISIBILITY_VISIBLE) {
break;
}
// 递归呼叫resumeTopActivityUncheckedLocked函数
someActivityResumed |= child.resumeTopActivityUncheckedLocked(prev, options,
deferPause);
if (idx >= mChildren.size()) {
idx = mChildren.size() - 1;
}
}
}
// 栈顶 Activity
final ActivityRecord next = topRunningActivity(true /* focusableOnly */);
if (next == null || !next.canTurnScreenOn()) {
checkReadyForSleep();
}
} finally {
mInResumeTopActivity = false;
}
return someActivityResumed;
}
找到目标叶节点后,Task#resumeTopActivityInnerLocked 方法是启动 Activity 的入口函数,该函数会透过 attachedToProcess
判断目标进程是否可连接
- 已启动,则透过
scheduleTransaction
恢复 Activity - 未启动,就透过
startSpecificActivity
启动 Activity
// Task.java
final ActivityTaskManagerService mAtmService;
final ActivityTaskSupervisor mTaskSupervisor;
private boolean resumeTopActivityInnerLocked(ActivityRecord prev, ActivityOptions options,
boolean deferPause) {
ActivityRecord next = topRunningActivity(true /* focusableOnly */);
... 省略部分
// 判断是否可以连接到APP进程
if(next.attachedToProcess()) {
// 如果前一个活动是半透明的,则强制更新可见性,添加到WM的开启应用列表中
final boolean lastActivityTranslucent = lastFocusedRootTask != null
&& (lastFocusedRootTask.inMultiWindowMode()
|| (lastFocusedRootTask.mLastPausedActivity != null
&& !lastFocusedRootTask.mLastPausedActivity.occludesParent()));
if (!next.mVisibleRequested || next.stopped || lastActivityTranslucent) {
// 设置为可见
next.setVisibility(true);
}
// schedule launch ticks to collect information about slow apps.
next.startLaunchTickingLocked();
ActivityRecord lastResumedActivity =
lastFocusedRootTask == null ? null : lastFocusedRootTask.getResumedActivity();
final ActivityState lastState = next.getState();
mAtmService.updateCpuStats();
... 省略 Log
// 设定State到Resumed
next.setState(RESUMED, "resumeTopActivityInnerLocked");
boolean notUpdated = true;
... 省略部分
try {
// 要传送给Client端的信息
// next.appToken就是目标应用的ApplicationThread(Binder Server类)
final ClientTransaction transaction =
ClientTransaction.obtain(
next.app.getThread(),
next.appToken
);
// Deliver all pending results.
ArrayList<ResultInfo> a = next.results;
if (a != null) {
final int N = a.size();
if (!next.finishing && N > 0) {
... 省略 Log 訊息
// 添加 callback
// 注意 ActivityResultItem 在应用端会被呼叫
transaction.addCallback(ActivityResultItem.obtain(a));
}
}
if (next.newIntents != null) {
transaction.addCallback(
NewIntentItem.obtain(next.newIntents, true /* resume */));
}
// 清楚 应用的 停止状态
next.notifyAppResumed(next.stopped);
... 省略 Log
mAtmService.getAppWarningsLocked().onResumeActivity(next);
... 省略部分
transaction.setLifecycleStateRequest(
ResumeActivityItem.obtain(next.app.getReportedProcState(),
dc.isNextTransitionForward()));
// @ 1. 分析 scheduleTransaction !!
mAtmService.getLifecycleManager().scheduleTransaction(transaction);
... 省略 Log
} catch (Exception e) {
... 省略部分
// 重新启动Activity
mTaskSupervisor.startSpecificActivity(next, true, false);
return true;
}
... 省略部分
} else {
... 省略部分
// @ 2. 分析 startSpecificActivity, 启动新 Activity
mTaskSupervisor.startSpecificActivity(next, true, true);
}
return true;
}
启动已存在 Activity#
Task#resumeTopActivityInnerLocked 函数会判断目标 ActivityRecord 是否已启动,若已启动则透过 ClientLifecycleManager#scheduleTransaction
恢复 Activity
ClientLifecycleManager - scheduleTransaction#
第一步的重点在 Binder Client & Server 的转换,这里会透过 ClientTransaction
来呼叫 App 端的 BinderServer(就是ActivityThread#ApplicationThread
类)
// ClientLifecycleManager.java
class ClientLifecycleManager {
void scheduleTransaction(ClientTransaction transaction) throws RemoteException {
// IApplicationThread 是应用端
final IApplicationThread client = transaction.getClient();
transaction.schedule();
if (!(client instanceof Binder)) {
// 如果客户端不是Binder,这就是一个远端调用,这个该对象就可以被回收
// 如果对象是Binder就由客户(应用)端自己回收
transaction.recycle();
}
}
}
ClientTransaction 呼叫目标应用的 ApplicationThread(也就是目标应用的 BinderServer)
// ClientTransaction.java
/** Target client. */
private IApplicationThread mClient; // IApplicationThread 是目标应用的 BinderServer
public void schedule() throws RemoteException {
mClient.scheduleTransaction(this);
}
ApplicationThread - scheduleTransaction 启动 Activity#
ApplicationThread 是 ActivityThread 的内部类,它实现了 Binder Server 的部分(每个应用都有实现一个 ApplicationThread,是为了让 AMS 有办法操控 Activity)
// ActivityThread.java
public final class ActivityThread extends ClientTransactionHandler
implements ActivityThreadInternal {
// 实现 AIDL 的 IApplicationThread.Stub 类
private class ApplicationThread extends IApplicationThread.Stub {
@Override
public void scheduleTransaction(ClientTransaction transaction) throws RemoteException {
// 查看 ClientTransactionHandler 父类
ActivityThread.this.scheduleTransaction(transaction);
}
}
}
呼叫到 ActivityThread 的父类的 scheduleTransaction 方法 (也就是 ClientTransactionHandler,ClientTransactionHandler 负责处理 AMS 传来的信息)
// ClientTransactionHandler.java
public abstract class ClientTransactionHandler {
// 准备启动目标 Activity
void scheduleTransaction(ClientTransaction transaction) {
transaction.preExecute(this);
// 主要看 sendMessage 函数
// 下面來看看传入 EXECUTE_TRANSACTION 最终会如何处理
sendMessage(ActivityThread.H.EXECUTE_TRANSACTION, transaction);
}
// 由 ActivityThread 实作
abstract void sendMessage(int what, Object obj);
}
ActivityThread 实作 sendMessage 方法,以启动 Activity 来说就是对 Handler 传入 EXECUTE_TRANSACTION
信息,再由 TransactionExecutor#execute 函数处理
// ActivityThread.java
final H mH = new H();
private final TransactionExecutor mTransactionExecutor = new TransactionExecutor(this);
// H 是 Handler
class H extends Handler {
public static final int EXECUTE_TRANSACTION = 159;
public void handleMessage(Message msg) {
switch (msg.what) {
... 省略部分
case EXECUTE_TRANSACTION:
// 对应 AMS 传人的 ClientTransaction 对象
final ClientTransaction transaction = (ClientTransaction) msg.obj;
mTransactionExecutor.execute(transaction);
if (isSystem()) {
// 如果是系统进程则在Client端回收对象,
// 而不是ClientLifecycleManager回收
// 避免在该函数信息在被处理完之前就被回收!!
transaction.recycle();
}
break;
}
}
private void sendMessage(int what,
Object obj, // EXECUTE_TRANSACTION
int arg1, int arg2, boolean async) {
... 省略 Log 訊息
Message msg = Message.obtain();
msg.what = what;
msg.obj = obj;
msg.arg1 = arg1;
msg.arg2 = arg2;
if (async) {
msg.setAsynchronous(true);
}
mH.sendMessage(msg);
}
TransactionExecutor#execute 函数:执行所有 ClientTransactionItem (AMS 传来) 的 execute 函数
// TransactionExecutor.java
private ClientTransactionHandler mTransactionHandler;
public void execute(ClientTransaction transaction) {
... 省略部分
// 分析 executeCallbacks
executeCallbacks(transaction);
executeLifecycleState(transaction);
... 省略部分
}
public void executeCallbacks(ClientTransaction transaction) {
final List<ClientTransactionItem> callbacks = transaction.getCallbacks();
...省略部分
for (int i = 0; i < size; ++i) {
// ClientTransactionItem 是抽象,实作是 ActivityResultItem
final ClientTransactionItem item = callbacks.get(i);
... 省略部分
item.execute(mTransactionHandler, token, mPendingActions);
item.postExecute(mTransactionHandler, token, mPendingActions);
... 省略部分
}
}
ActivityResultItem - execute 呼叫 Instrumentation#
这里的 ClientTransactionItem 是抽象类,藉由传入的对象不同,有不同的实作细节
// ActivityResultItem.java
public class ActivityResultItem extends ActivityTransactionItem {
@Override
public void execute(ClientTransactionHandler client, ActivityClientRecord r,
PendingTransactionActions pendingActions) {
// @ 分析 handleSendResult 方法
client.handleSendResult(r, mResultInfoList, "ACTIVITY_RESULT");
}
}
// ---------------------------------------------------------------
// ActivityThread.java
@Override
public void handleSendResult(ActivityClientRecord r, List<ResultInfo> results, String reason) {
final boolean resumed = !r.paused;
if (!r.activity.mFinished && r.activity.mDecor != null
&& r.hideForNow && resumed) {
updateVisibility(r, true);
}
if (resumed) {
try {
// Now we are idle.
r.activity.mCalled = false;
mInstrumentation.callActivityOnPause(r.activity);
if (!r.activity.mCalled) {
throw new SuperNotCalledException(
"Activity " + r.intent.getComponent().toShortString()
+ " did not call through to super.onPause()");
}
} /*省略 catch*/
}
checkAndBlockForNetworkAccess();
deliverResults(r, results, reason);
if (resumed) {
// 执行目标 ++ onResume ++
r.activity.performResume(false, reason);
}
}
// ---------------------------------------------------------------
// Activity.java
final void performResume(boolean followedByPause, String reason) {
... 省略部分
// mResumed is set by the instrumentation
mInstrumentation.callActivityOnResume(this);
... 省略部分
}
Instrumentation 呼叫 onResume#
最终可以看到 Activity#onResume
函数会透过 Instrumentation 呼叫
// /app/Instrumentation.java
public void callActivityOnResume(Activity activity) {
activity.mResumed = true;
// 呼叫 Activity#onResume 函数
activity.onResume();
if (mActivityMonitors != null) {
synchronized (mSync) {
final int N = mActivityMonitors.size();
for (int i=0; i<N; i++) {
final ActivityMonitor am = mActivityMonitors.get(i);
am.match(activity, activity, activity.getIntent());
}
}
}
}
启动新 Activity#
Task#resumeTopActivityInnerLocked
函数会判断目标 ActivityRecord 是否已启动,若已启动则透过 ActivityTaskSupervisor#startSpecificActivity
启动 Activity
ActivityTaskSupervisor - startSpecificActivity#
这里的关键是在调用 realStartActivityLocked
函数,这里会取用 ClientTransaction 对象,透过 ActivityTaskManagerService 将 ClientTransaction 对象传给目标(要启动的)Activity,之后该 Activity 会使用该对象
// ActivityTaskSupervisor.java
final ActivityTaskManagerService mService
void startSpecificActivity(ActivityRecord r, boolean andResume, boolean checkConfig) {
// Is this activity's application already running?
final WindowProcessController wpc =
mService.getProcessController(r.processName, r.info.applicationInfo.uid);
boolean knownToBeDead = false;
if (wpc != null && wpc.hasThread()) {
try {
realStartActivityLocked(r, wpc, andResume, checkConfig);
return;
} /* 省略 catch */
// If a dead object exception was thrown -- fall through to
// restart the application.
knownToBeDead = true;
}
...省略部分
}
boolean realStartActivityLocked(ActivityRecord r, WindowProcessController proc,
boolean andResume, boolean checkConfig) throws RemoteException {
... 省略部分
try {
... 省略部分
try {
// Create activity launch transaction.
final ClientTransaction clientTransaction = ClientTransaction.obtain(
proc.getThread(), r.appToken);
final boolean isTransitionForward = r.isTransitionForward();
// 1.添加Callback是一个重点!!
// 之后启动的Activity会使用到LaunchActivityItem类
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.getFilteredReferrer(r.launchedFromPackage), task.voiceInteractor,
proc.getReportedProcState(), r.getSavedState(), r.getPersistentSavedState(),
results, newIntents, r.takeOptions(), isTransitionForward,
proc.createProfilerInfoIfNeeded(), r.assistToken, activityClientController,
r.createFixedRotationAdjustmentsIfNeeded(), r.shareableActivityToken,
r.getLaunchedFromBubble()));
// Set desired final state.
final ActivityLifecycleItem lifecycleItem;
if (andResume) {
lifecycleItem = ResumeActivityItem.obtain(isTransitionForward);
} else {
lifecycleItem = PauseActivityItem.obtain();
}
clientTransaction.setLifecycleStateRequest(lifecycleItem);
// 2. Schedule transaction. (继续分析)
mService.getLifecycleManager().scheduleTransaction(clientTransaction);
...省略部分
} /*省略 catch*/
... 省略部分
} /*省略 catch*/
}
LaunchActivityItem - execute 呼叫 Instrumentation#
// LaunchActivityItem.java
public class LaunchActivityItem extends ClientTransactionItem {
@Override
public void execute(ClientTransactionHandler client, IBinder token,
PendingTransactionActions pendingActions) {
ActivityClientRecord r = client.getLaunchingActivity(token);
// handleLaunchActivity 是抽象方法
// ActivityThread 是它的实作类
client.handleLaunchActivity(r, pendingActions, null /* customIntent */);
}
}
// -------------------------------------------------------------
// ActivityThread.java
public final class ActivityThread extends ClientTransactionHandler
implements ActivityThreadInternal {
@Override
public Activity handleLaunchActivity(ActivityClientRecord r,
PendingTransactionActions pendingActions, Intent customIntent) {
... 省略部分
final Activity a = performLaunchActivity(r, customIntent);
... 省略部分
}
}
ActivityThread#performLaunchActivity:创建 ContextImpl,透过 Instrumentation 类创建 Activity、Application 等等… 对象
// ActivityThread.java
public final class ActivityThread extends ClientTransactionHandler
implements ActivityThreadInternal {
private Activity performLaunchActivity(ActivityClientRecord r, Intent customIntent) {
...省略部分
// 创建 Context
ContextImpl appContext = createBaseContextForActivity(r);
Activity activity = null;
try {
// 使用 Instrumentation 创建 Activity、Application
java.lang.ClassLoader cl = appContext.getClassLoader();
activity = mInstrumentation.newActivity(
cl, component.getClassName(), r.intent);
StrictMode.incrementExpectedActivityCount(activity.getClass());
r.intent.setExtrasClassLoader(cl);
r.intent.prepareToEnterProcess(isProtectedComponent(r.activityInfo),
appContext.getAttributionSource());
if (r.state != null) {
r.state.setClassLoader(cl);
}
} /* 省略 catch */
try {
Application app = r.packageInfo.makeApplication(false, mInstrumentation);
... 省略部分
if (activity != null) {
... 省略部分
// 呼叫 Activity#onCreate 函數
if (r.isPersistable()) {
mInstrumentation.callActivityOnCreate(activity, r.state, r.persistentState);
} else {
mInstrumentation.callActivityOnCreate(activity, r.state);
}
if (!activity.mCalled) {
throw new SuperNotCalledException(
"Activity " + r.intent.getComponent().toShortString() +
" did not call through to super.onCreate()");
}
r.activity = activity;
...
}
} /* 省略 catch */
return activity;
}
}
Instrumentation - 创建 Activity、Application#
Instrumentation#newActivity:
反射創建 Activity 對象
// Instrumentation.java
public Activity newActivity(Class<?> clazz, Context context,
IBinder token, Application application, Intent intent, ActivityInfo info,
CharSequence title, Activity parent, String id,
Object lastNonConfigurationInstance) throws InstantiationException,
IllegalAccessException {
Activity activity = (Activity)clazz.newInstance();
ActivityThread aThread = null;
// Activity.attach expects a non-null Application Object.
if (application == null) {
// 创建 Application 对象
application = new Application();
}
activity.attach(context, aThread, this, token, 0 /* ident */, application, intent,
info, title, parent, id,
(Activity.NonConfigurationInstances)lastNonConfigurationInstance,
new Configuration(), null /* referrer */, null /* voiceInteractor */,
null /* window */, null /* activityConfigCallback */, null /*assistToken*/,
null /*shareableActivityToken*/);
return activity;
}
Instrumentation - 呼叫 onCreate#
ActivityThread#performLaunchActivity
函数会使用到 Instrumentation,并透過 Instrumentation 来呼叫 Activity#onCreate
函数
// Instrumentation.java
public void callActivityOnCreate(Activity activity, Bundle icicle) {
prePerformCreate(activity);
// 呼叫 onCreate
activity.performCreate(icicle);
postPerformCreate(activity);
}
// -------------------------------------------------------------
// Activity.java
final void performCreate(Bundle icicle) {
performCreate(icicle, null);
}
final void performCreate(Bundle icicle, PersistableBundle persistentState) {
if (Trace.isTagEnabled(Trace.TRACE_TAG_WINDOW_MANAGER)) {
Trace.traceBegin(Trace.TRACE_TAG_WINDOW_MANAGER, "performCreate:"
+ mComponent.getClassName());
}
... 省略部分
// 呼叫 onCreate 函數
if (persistentState != null) {
onCreate(icicle, persistentState);
} else {
onCreate(icicle);
}
... 省略部分
}
ActivityThread#
真正的启动类是 ActivitiyThread.java,它的内部就有我们所详知的 main 方法,在这里我们还可以看到 Main 所使用的 Looper,并且启动 Looper,令一个重点是 attach 函数
/**
* ActivityThread.java
* 路徑: ./frameworks/base/core/java/android/app/ActivityThread.java
*/
public static void main(String[] args) {
Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, "ActivityThreadMain");
...省略部份
// MainLooper
Looper.prepareMainLooper(); // # prepare Main Looper
ActivityThread thread = new ActivityThread();
thread.attach(false); //@ 追尋 attach
if (sMainThreadHandler == null) {
sMainThreadHandler = thread.getHandler();
}
if (false) {
Looper.myLooper().setMessageLogging(new
LogPrinter(Log.DEBUG, "ActivityThread"));
}
Looper.loop(); // # 啟動 Looper
throw new RuntimeException("Main thread loop unexpectedly exited");
}
ActivityThread - attach 开始连接#
直接关注重点部份,也就是 attachApplication 函数,Android 透过 Binder(不细讲,需看另外一篇)机制,取得代理器(ActivityManagerProxy)来呼叫到服务方跳转到 ActivityManagerService 类
// ActivityThread.java
private void attach(boolean system) { // # main 傳入 false
sCurrentActivityThread = this;
mSystemThread = system;
if (!system) {
// View 管理器
ViewRootImpl.addFirstDrawHandler(new Runnable() {
@Override
public void run() {
ensureJitEnabled();
}
});
...省略部份
// 取得AMS的代理对象,透过它与AMS沟通
final IActivityManager mgr = ... // # AIDL, Service Port
try {
// 传入 Application
mgr.attachApplication(mAppThread); // @ important ! Jamp to ActivityManagerService.class
} catch (RemoteException ex) {
throw ex.rethrowFromSystemServer();
}
...省略部份
} else {
// SystemServer 才会传入 true
...省略,因為 main 傳入的是 false
}
// add dropbox logging to libcore
DropBox.setReporter(new DropBoxReporter());
// @ 注册 View 管理器的 callBack
ViewRootImpl.addConfigCallback(...);
}
函数 attachApplication 也接收一个参数 mAppThread
,它就是 ApplicationThread,在之后的绑定 Application 需要使用到
ActivityManagerService 类 - attachApplication#
AMS 类作为 AMS 的 Server 端,必须实现 IActivityManager.Stub 方法;attachApplication 函数相当长,它的重点在
- bindApplication,绑定 App 端的 Application,也就是 App 端的 Binder,好让 AMS 可以直接操控 Activity
- attachApplicationLocked(连接 Activity)
// ActivityManagerService.java
public class ActivityManagerService extends IActivityManager.Stub
implements Watchdog.Monitor, BatteryStatsImpl.BatteryCallback, ActivityManagerGlobalLock {
public ActivityTaskManagerInternal mAtmInternal;
... 省略其他函數
@Override
public final void attachApplication(IApplicationThread thread, long startSeq) {
if (thread == null) {
throw new SecurityException("Invalid application interface");
}
synchronized (this) {
// 调用者的 PID
int callingPid = Binder.getCallingPid();
// 调用者的 UID
final int callingUid = Binder.getCallingUid();
// 把 PID/UID 设定为 AMS 的 PID/UID
final long origId = Binder.clearCallingIdentity();
attachApplicationLocked(thread, callingPid, callingUid, startSeq);
// 恢复为调用者的 PID/UID
Binder.restoreCallingIdentity(origId);
}
}
private boolean attachApplicationLocked(IApplicationThread thread,
int pid) {
try {
... 省略部分
// # 1.绑定,这里也是使用Binder机制,它会呼叫到App应用的Service
// 也就是呼叫到ApplicationThread中的bindApplication
thread.bindApplication(processName, appInfo, providers, app.instrumentationClass,
profilerInfo, app.instrumentationArguments, app.instrumentationWatcher,
app.instrumentationUiAutomationConnection, testMode,
mBinderTransactionTrackingEnabled, enableTrackAllocation,
isRestrictedBackupMode || !normalMode, app.persistent,
new Configuration(mConfiguration), app.compat,
getCommonServicesLocked(app.isolated),
mCoreSettingsObserver.getCoreSettingsLocked());
} /* 省略 catch */
...省略
if (normalMode) {
try {
// @ 2. 连接 Activity
if (mAtmInternal.attachApplication(app)) {
didSomething = true;
}
} /* 省略 catch */
}
}
}
bindApplication 会呼叫到 App 应用的 Service 去做绑定(也就是 ApplicationThread),但这边先不关注这个,先看 attachApplication,它会 绑定需要的 Activity、还有 启动 Activity 种种的操作(先提出待会会使用到的两个)
Binder 安全性带有调用者的信息,该信息是系统设定,用来验证调用者是否有权限调用
Http 安全性 CS 构架中,使用应用层的设定的信息,该信息有可能有被窜改
ActivityTaskManagerInternal - 绑定&启动 Activity#
在上面的 AMS 中会呼叫到attachApplicationLocked#attachApplication
方法,而 ActivityTaskManagerInternal 类是抽象类,它的实作是 ActivityTaskManagerService#LocalService
// ActivityTaskManagerService.java
public class ActivityTaskManagerService extends IActivityTaskManager.Stub {
RootWindowContainer mRootWindowContainer;
... 省略部分
final class LocalService extends ActivityTaskManagerInternal {
@Override
public boolean attachApplication(WindowProcessController wpc) throws RemoteException {
synchronized (mGlobalLockWithoutBoost) {
// 省略 trace
try {
return mRootWindowContainer.attachApplication(wpc);
} finally {
... 省略 trace
}
}
}
}
}
RootWindowContainer#attachApplication
// RootWindowContainer.java
boolean attachApplication(WindowProcessController app) throws RemoteException {
boolean didSomething = false;
for (int displayNdx = getChildCount() - 1; displayNdx >= 0; --displayNdx) {
mTmpRemoteException = null;
mTmpBoolean = false; // Set to true if an activity was started.
final DisplayContent display = getChildAt(displayNdx);
display.forAllRootTasks(rootTask -> {
if (mTmpRemoteException != null) {
return;
}
if (rootTask.getVisibility(null /*starting*/) == TASK_VISIBILITY_INVISIBLE) {
return;
}
// 查看 startActivityForAttachedApplicationIfNeeded 函数
final PooledFunction c = PooledLambda.obtainFunction(
RootWindowContainer::startActivityForAttachedApplicationIfNeeded, this,
PooledLambda.__(ActivityRecord.class), app,
rootTask.topRunningActivity());
rootTask.forAllActivities(c);
c.recycle();
});
...省略部分
}
...省略部分
return didSomething;
}
private boolean startActivityForAttachedApplicationIfNeeded(ActivityRecord r,
WindowProcessController app, ActivityRecord top) {
... 省略部分
try {
if (mTaskSupervisor.realStartActivityLocked(r, app,
top == r && r.isFocusable() /*andResume*/, true /*checkConfig*/)) {
mTmpBoolean = true;
}
} /* 省略 catch */
return false;
}
realStartActivityLocked 函数:在这边会做一些启动前的准备、校验,准备好后使用 Binder 启动呼叫 ApplicationThread 来启动 Activity(还记得刚刚 App 端有把自身的 Binder 传给 AMS 吗?)
// RootWindowContainer.java
final boolean realStartActivityLocked(ActivityRecord r, ProcessRecord app,
boolean andResume, boolean checkConfig) throws RemoteException {
if (!allPausedActivitiesComplete()) {
...省略 Debug 訊息
return false;
}
if (andResume) { //# true
r.startFreezingScreenLocked(app, 0); //# freez haven't start activity
mWindowManager.setAppVisibility(r.appToken, true);
// schedule launch ticks to collect information about slow apps.
r.startLaunchTickingLocked(); // # cellection of app's data who start slowly
}
if (checkConfig) { // # true, check setting infomation
Configuration config = mWindowManager.updateOrientationFromAppTokens(
mService.mConfiguration,
r.mayFreezeScreenLocked(app) ? r.appToken : null);
mService.updateConfigurationLocked(config, r, false, true /* deferResume */);
}
// # ActivityRecord set data form the ProcessRecord 兩個都是傳近來的參數
r.app = app;
app.waitingToKill = null;
r.launchCount++;
r.lastLaunchTime = SystemClock.uptimeMillis();
int idx = app.activities.indexOf(r);
if (idx < 0) {
app.activities.add(r);
}
mService.updateLruProcessLocked(app, true, null);
mService.updateOomAdjLocked();
... 省略部份
final ActivityStack stack = task.stack;
try {
... 省略部份
//# if activity is home's, add it in this activity buttom of stack(如果是桌面 Activity,添加到當前 Activity 棧底)
if (r.isHomeActivity()) {
// Home process is the root process of the task. (本地流程是任務的根本流程)
mService.mHomeProcess = task.mActivities.get(0).app;
}
... 省略部份
// 往下追 scheduleLaunchActivity
app.thread.scheduleLaunchActivity(new Intent(r.intent), r.appToken, //@ all params prepare done, ready start activity
System.identityHashCode(r), r.info, new Configuration(mService.mConfiguration),
new Configuration(task.mOverrideConfig), r.compat, r.launchedFromPackage,
task.voiceInteractor, app.repProcState, r.icicle, r.persistentState, results,
newIntents, !andResume, mService.isNextTransitionForward(), profilerInfo);
} /* 省略 catch */
App 端 - ApplicationThread#
ApplicationThread ActivityThread 的私有内部类,并继承于 ApplicationThreadNative(Binder Server),它的主要功能在实现 IApplicationThread 接口,这里就是 App 端实现的 Binder
/**
* AcitivtyThread.class
*/
public final class AcitivtyThread {
/**
* AcitivtyThread#ApplicationThread.class
*/
private class ApplicationThread extends ApplicationThreadNative {
@Override
public final void scheduleLaunchActivity(Intent intent, IBinder token, int ident,
ActivityInfo info, Configuration curConfig, Configuration overrideConfig,
CompatibilityInfo compatInfo, String referrer, IVoiceInteractor voiceInteractor,
int procState, Bundle state, PersistableBundle persistentState,
List<ResultInfo> pendingResults, List<ReferrerIntent> pendingNewIntents,
boolean notResumed, boolean isForward, ProfilerInfo profilerInfo) {
updateProcessState(procState, false);
ActivityClientRecord r = new ActivityClientRecord(); //# Inner Class record it
r.token = token;
r.ident = ident;
r.intent = intent;
r.referrer = referrer;
r.voiceInteractor = voiceInteractor;
r.activityInfo = info;
r.compatInfo = compatInfo;
r.state = state;
r.persistentState = persistentState;
r.pendingResults = pendingResults;
r.pendingIntents = pendingNewIntents;
r.startsNotResumed = notResumed;
r.isForward = isForward;
r.profilerInfo = profilerInfo;
r.overrideConfig = overrideConfig;
updatePendingConfiguration(curConfig);
sendMessage(H.LAUNCH_ACTIVITY, r); //@ send message with activity start, call H.class
}
}
}
这里有两个地方要注意
它创建了 ActivityClientRecord(是 ActivityThread 静态内部类),用来纪录所有有关这次启动的信息
透过 Handler 机制传送了 LAUNCH_ACTIVITY 信息
/**
* ActivityThread.class
* 最呼叫到 外部 ActivityThread 的 sendMessage 方法
*/
private 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) {
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);
}
/**
* ActivityThread#H.class
* 最终会呼叫到ActivityThread的私有内部类H
*/
private class H extends Handler {
public void handleMessage(Message msg) {
switch (msg.what) {
case LAUNCH_ACTIVITY: {
Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, "activityStart");
final ActivityClientRecord r = (ActivityClientRecord) msg.obj;
r.packageInfo = getPackageInfoNoCheck(
r.activityInfo.applicationInfo, r.compatInfo);
//@ 启动 Activity
handleLaunchActivity(r, null, "LAUNCH_ACTIVITY");
Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);
} break;
...省略其他
}
}
/**
* ActivityThread.class
* handleLaunchActivity 主要是调用了 performLaunchActivity 方法
*/
private void handleLaunchActivity(ActivityClientRecord r, Intent customIntent, String reason) {
...省略部份
// Initialize before creating the activity
WindowManagerGlobal.initialize();
Activity a = performLaunchActivity(r, customIntent); //@ prerform launch activity
...省略部份
}
performLaunchActivity - 创建 Activity#
performLaunchActivity 函数存在于 ActivityThread 这个类中,主要的功能都会在这里创建、绑定(Application,Context)
/**
* ActivityThread.class
*/
private Activity performLaunchActivity(ActivityClientRecord r, Intent customIntent) {
ActivityInfo aInfo = r.activityInfo;
if (r.packageInfo == null) {
r.packageInfo = getPackageInfo(aInfo.applicationInfo, r.compatInfo,
Context.CONTEXT_INCLUDE_CODE);
}
ComponentName component = r.intent.getComponent();
if (component == null) {
// # 设定预设 Componect
component = r.intent.resolveActivity(
mInitialApplication.getPackageManager());
r.intent.setComponent(component);
}
if (r.activityInfo.targetActivity != null) {
component = new ComponentName(r.activityInfo.packageName,
r.activityInfo.targetActivity);
}
// 创建Activity引用,准备回传
Activity activity = null;
try {
// 获取 LoadedApk - class, packageInfo is LoadedApk
java.lang.ClassLoader cl = r.packageInfo.getClassLoader();
// 使用 反射调用- 创建 Activity
activity = mInstrumentation.newActivity( //# reflection create
cl, component.getClassName(), r.intent);
StrictMode.incrementExpectedActivityCount(activity.getClass());
r.intent.setExtrasClassLoader(cl);
r.intent.prepareToEnterProcess();
if (r.state != null) {
r.state.setClassLoader(cl);
}
} catch (Exception e) {
if (!mInstrumentation.onException(activity, e)) {
throw new RuntimeException(
"Unable to instantiate activity " + component
+ ": " + e.toString(), e);
}
}
try {
// packageInfo is LoadedApk
Application app = r.packageInfo.makeApplication(false, mInstrumentation); //# get appliction object
...省略部份
if (activity != null) {
// # createBaseContextForActivity 方法会返回 ContextImpl 类
Context appContext = createBaseContextForActivity(r, activity);
...省略部份
Window window = null;
if (r.mPendingRemoveWindow != null && r.mPreserveWindow) {
window = r.mPendingRemoveWindow;
r.mPendingRemoveWindow = null;
r.mPendingRemoveWindowManager = null;
}
// # 将 Application & Context 绑定到 Activity 对象 !
activity.attach(appContext, this, getInstrumentation(), r.token, // # let appliction & context bind on activity
r.ident, app, r.intent, r.activityInfo, title, r.parent,
r.embeddedID, r.lastNonConfigurationInstances, config,
r.referrer, r.voiceInteractor, window);
if (customIntent != null) {
activity.mIntent = customIntent;
}
r.lastNonConfigurationInstances = null;
activity.mStartedActivity = false;
int theme = r.activityInfo.getThemeResource();
if (theme != 0) {
activity.setTheme(theme);
}
activity.mCalled = false;
if (r.isPersistable()) {
// @ 调用 Activity 的 onCreate 方法!
mInstrumentation.callActivityOnCreate(activity, r.state, r.persistentState);
} else {
mInstrumentation.callActivityOnCreate(activity, r.state);
}
...省略部份
} catch (SuperNotCalledException e) {
throw e;
} catch (Exception e) {
if (!mInstrumentation.onException(activity, e)) {
throw new RuntimeException(
"Unable to start activity " + component
+ ": " + e.toString(), e);
}
}
return activity;
}
Instrumentation - onCreate 呼叫#
Instrumentation 是连接 ActivityThread & Activity 中间的桥梁,之后就可以连接到我们所使用的 onCreate 函数
//ActivityThread.class
private Activity performLaunchActivity(ActivityClientRecord r, Intent customIntent) {
...
if (r.isPersistable()) {
// @ 调用 Activity 的 onCreate 方法!
mInstrumentation.callActivityOnCreate(activity, r.state, r.persistentState);
} else {
mInstrumentation.callActivityOnCreate(activity, r.state);
}
...
}
/**
* Instrumentation.class
* callActivityOnCreate接收ActivityThread所创建的Activity,
* 并透过Instrumentation与Activity连接
*/
public void callActivityOnCreate(Activity activity, Bundle icicle,
PersistableBundle persistentState) {
prePerformCreate(activity);
activity.performCreate(icicle, persistentState);
postPerformCreate(activity);
}
// ----------------------------------------------------------------
// Activity.class
public class Activity extends ContextThemeWrapper
implements LayoutInflater.Factory2,
Window.Callback, KeyEvent.Callback,
OnCreateContextMenuListener, ComponentCallbacks2,
Window.OnWindowDismissedCallback, WindowControllerCallback {
... 省略其他 Activity 函數
final void performCreate(Bundle icicle, PersistableBundle persistentState) {
restoreHasCurrentPermissionRequest(icicle);
onCreate(icicle, persistentState);
mActivityTransitionState.readState(icicle);
performCreateCommon();
}
public void onCreate(@Nullable Bundle savedInstanceState,
@Nullable PersistableBundle persistentState) {
onCreate(savedInstanceState);
}
// 最终我们复写onCreate的地方!
@MainThread
@CallSuper
protected void onCreate(@Nullable Bundle savedInstanceState) {
if (DEBUG_LIFECYCLE) Slog.v(TAG, "onCreate " + this + ": " + savedInstanceState);
if (mLastNonConfigurationInstances != null) {
mFragments.restoreLoaderNonConfig(mLastNonConfigurationInstances.loaders);
}
if (mActivityInfo.parentActivityName != null) {
if (mActionBar == null) {
mEnableDefaultActionBarUp = true;
} else {
mActionBar.setDefaultDisplayHomeAsUpEnabled(true);
}
}
if (savedInstanceState != null) {
Parcelable p = savedInstanceState.getParcelable(FRAGMENTS_TAG);
mFragments.restoreAllState(p, mLastNonConfigurationInstances != null
? mLastNonConfigurationInstances.fragments : null);
}
mFragments.dispatchCreate();
getApplication().dispatchActivityCreated(this, savedInstanceState);
if (mVoiceInteractor != null) {
mVoiceInteractor.attachActivity(this);
}
mCalled = true;
}
}