Android中ActivityManagerService简称AMS,主要负责Android中四大组件创建启动管理。
本地环境如下:
compileSdkVersion 30
buildToolsVersion "30.0.3"
minSdkVersion 21
targetSdkVersion 30
1)从调用startActivity开始
startActivity(Intent(this,MainActivity::class.java))
2)进入Activity中的startActivity,源码5664行
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)) {
if (TextUtils.equals(getPackageName(),
intent.resolveActivity(getPackageManager()).getPackageName())) {
// Apply Autofill restore mechanism on the started activity by startActivity()
final IBinder token =
mIntent.getIBinderExtra(AutofillManager.EXTRA_RESTORE_SESSION_TOKEN);
// Remove restore ability from current activity
mIntent.removeExtra(AutofillManager.EXTRA_RESTORE_SESSION_TOKEN);
mIntent.removeExtra(AutofillManager.EXTRA_RESTORE_CROSS_ACTIVITY);
// Put restore token
intent.putExtra(AutofillManager.EXTRA_RESTORE_SESSION_TOKEN, token);
intent.putExtra(AutofillManager.EXTRA_RESTORE_CROSS_ACTIVITY, true);
}
}
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);
}
}
3)进入Activity 中的startActivityForResult
public void startActivityForResult(@RequiresPermission Intent intent, int requestCode,
//开始跳转
Instrumentation.ActivityResult ar =
mInstrumentation.execStartActivity(
this, mMainThread.getApplicationThread(), mToken, this,
intent, requestCode, options);
}
4)进入Instrumentation中的execStartActivity方法,见源码1690行
public ActivityResult execStartActivity(
Context who, IBinder contextThread, IBinder token, Activity target,
Intent intent, int requestCode, Bundle options) {
//此处省略。。。。
//使用binder跨进程通信启动Activity
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);
// 检查跳转的结果
checkStartActivityResult(result, intent);
} catch (RemoteException e) {
throw new RuntimeException("Failure from system", e);
}
return null;
}
Android不同的版本中getService处也是有所差异
在Android 5.0中是ActivityManagerNative.getDefault().
在Android 7.0中getService()是:ActivityManager.getService()
Android 9.0及以上版本则是:ActivityTaskManager.getService()
所以最新的版本中AMS的简称要改成:"ATMS"才算正确
5)进入ActivityTaskManager中获取Service 见源码:149行
通过Singleton获取ActivityTaskManagerService对象
public static IActivityTaskManager getService() {
return IActivityTaskManagerSingleton.get();
}
6)进入ActivityTaskManager类中调用startActivity,见源码:1043行
@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) {
return startActivityAsUser(caller, callingPackage, callingFeatureId, intent, resolvedType,
resultTo, resultWho, requestCode, startFlags, profilerInfo, bOptions,
UserHandle.getCallingUserId());
}
//见源码1077行
private int startActivityAsUser(IApplicationThread caller, String callingPackage,
@Nullable String callingFeatureId, Intent intent, String resolvedType,
IBinder resultTo, String resultWho, int requestCode, int startFlags,
ProfilerInfo profilerInfo, Bundle bOptions, int userId, boolean validateIncomingUser) {
assertPackageMatchesCallingUid(callingPackage);
enforceNotIsolatedCaller("startActivityAsUser");
userId = getActivityStartController().checkTargetUser(userId, validateIncomingUser,
Binder.getCallingPid(), Binder.getCallingUid(), "startActivityAsUser");
// TODO: Switch to user app stacks here.
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();
}
在getActivityStartController方法中返回的ActivityStartController,然后调用obtainStarter获取ActivityStarter对象
7)进入ActivityStarter类中的execute方法,见源码:628行
在execute方法中(源码:669行)会调用executeRequest方法
private int executeRequest(Request request) {
//此处省略若干行
//核心代码startActivityUnchecked()
//见源码1186行
mLastStartActivityResult = startActivityUnchecked(r, sourceRecord, voiceSession,
request.voiceInteractor, startFlags, true /* doResume */, checkedOptions, inTask,
restrictedBgActivity, intentGrants);
if (request.outActivity != null) {
request.outActivity[0] = mLastStartActivityRecord;
}
return mLastStartActivityResult;
}
private int startActivityUnchecked(final ActivityRecord r, ActivityRecord sourceRecord,
IVoiceInteractionSession voiceSession, IVoiceInteractor voiceInteractor,
int startFlags, boolean doResume, ActivityOptions options, Task inTask,
boolean restrictedBgActivity, NeededUriGrants intentGrants) {
//此处省略,若干行
//见源码:1521行
result = startActivityInner(r, sourceRecord, voiceSession, voiceInteractor,
startFlags, doResume, options, inTask, restrictedBgActivity, intentGrants);
return result;
}
//进入startActivityInner
int startActivityInner(final ActivityRecord r, ActivityRecord sourceRecord,
IVoiceInteractionSession voiceSession, IVoiceInteractor voiceInteractor,
int startFlags, boolean doResume, ActivityOptions options, Task inTask,
boolean restrictedBgActivity, NeededUriGrants intentGrants) {
//见源码1731行
mRootWindowContainer.resumeFocusedStacksTopActivities(
mTargetStack, mStartActivity, mOptions);
}
}
return START_SUCCESS;
}
8)进入RootWindowContainer类中的resumeFocusedStacksTopActivities方法
//源码2289行
boolean resumeFocusedStacksTopActivities(
ActivityStack targetStack, ActivityRecord target, ActivityOptions targetOptions) {
if (focusedStack != null) {
//源码2337
result |= focusedStack.resumeTopActivityUncheckedLocked(target, targetOptions);
} else if (targetStack == null) {
result |= resumeHomeActivity(null /* prev */, "no-focusable-task",
display.getDefaultTaskDisplayArea());
}
}
}
return result;
}
9)进入ActivityStack中的resumeTopActivityUncheckedLocked见源码1501
boolean resumeTopActivityUncheckedLocked(ActivityRecord prev, ActivityOptions options) {
//见源码1511行
result = resumeTopActivityInnerLocked(prev, options);
return result;
}
private boolean resumeTopActivityInnerLocked(ActivityRecord prev, ActivityOptions options) {
//见源码:1934行
mStackSupervisor.startSpecificActivity(next, true, true);
}
return true;
}
10)进入ActivityStackSupervisor中的startSpecificActivity方法,见源码:964行
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);
//见源码972行
realStartActivityLocked(r, wpc, andResume, checkConfig);
}
//进入realStartActivityLocked方法,见源码:719行
boolean realStartActivityLocked(ActivityRecord r, WindowProcessController proc,
boolean andResume, boolean checkConfig) throws RemoteException {
//见源码843行
//此处为核心代码
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, proc.getReportedProcState(),
r.getSavedState(), r.getPersistentSavedState(), results, newIntents,
dc.isNextTransitionForward(), proc.createProfilerInfoIfNeeded(),
r.assistToken, r.createFixedRotationAdjustmentsIfNeeded()));
// Set desired final state.
final ActivityLifecycleItem lifecycleItem;
if (andResume) {
lifecycleItem = ResumeActivityItem.obtain(dc.isNextTransitionForward());
} else {
lifecycleItem = PauseActivityItem.obtain();
}
clientTransaction.setLifecycleStateRequest(lifecycleItem);
// Schedule transaction.
mService.getLifecycleManager().scheduleTransaction(clientTransaction);
return true;
}
如上代码创建ClientTransaction对象,然后通过clientTransaction.addCallback(见源码843行)添加一个LaunchActivityItem对象,(LaunchActivityItem.obtain方法返回的是一个LaunchActivityItem对象)此处尤为重要。
然后调用ClientLifecycleManager的scheduleTransaction方法把当前的是事务进行提交
此处源码在Android低版本中是直接调用的ActivityThread中的scheduleLaunchActivity方法进行进程切换启动目标Activity的
11)进入ClientLifecycleManager中的scheduleTransaction方法
void scheduleTransaction(@NonNull IApplicationThread client, @NonNull IBinder activityToken,
@NonNull ActivityLifecycleItem stateRequest) throws RemoteException {
final ClientTransaction clientTransaction = transactionWithState(client, activityToken,
stateRequest);
scheduleTransaction(clientTransaction);
}
void scheduleTransaction(ClientTransaction transaction) throws RemoteException {
final IApplicationThread client = transaction.getClient();
//此处为事务的提交
*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();
}
}
见ClientLifecycleManager的47行transaction.schedule()方法为事务的触发执行
12)进入ClientTransaction类中的的schedule方法
public void schedule() throws RemoteException {
mClient.scheduleTransaction(this);
}
如上代码mClient为IApplicationThread,
在源码中IApplicationThread的实现类为ActivityThread的内部类ApplicationThread
13)进入ActivityThread类中可以得知ApplicationThread中的scheduleTransaction方法最后调用到了ActivityThread父类的scheduleTransaction,
如下:
@Override
public void scheduleTransaction(ClientTransaction transaction) throws RemoteException {
ActivityThread.this.scheduleTransaction(transaction);
}
根据如上代码在ActivityThread中无法直接找到scheduleTransaction方法,于是进入ActivityThread的父类:ClientTransactionHandler中找到了scheduleTransaction方法的
如下:
void scheduleTransaction(ClientTransaction transaction) {
transaction.preExecute(this);
sendMessage(ActivityThread.H.EXECUTE_TRANSACTION, transaction);
}
方法中发送了一个EXECUTE_TRANSACTION消息,到H的handler中
14)进入ActivityThread中的H的handler消息EXECUTE_TRANSACTION,看到如下代码:
case EXECUTE_TRANSACTION:
final ClientTransaction transaction = (ClientTransaction) msg.obj;
//此处开始了事务的执行
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();
}
如上代码:mTransactionExecutor.execute(transaction);正式进入了事务的执行过程,前面一堆的过程都是做Activity启动前的校验初始化赋值等工作
15)进入TransactionExecutor中的execute方法,如下
public void execute(ClientTransaction transaction) {
// 前面省略若干行
//主要执行代码
executeCallbacks(transaction);
}
public void executeCallbacks(ClientTransaction transaction) {
final List<ClientTransactionItem> callbacks = transaction.getCallbacks();
//此处省略
for (int i = 0; i < size; ++i) {
final ClientTransactionItem item = callbacks.get(i);
//此处见源码:135行
item.execute(mTransactionHandler, token, mPendingActions);
item.postExecute(mTransactionHandler, token, mPendingActions);
}
}
}
根据上诉代码可知callbacks.get(i)获取的是ClientTransactionItem对象,而ClientTransactionItem的子类是:LaunchActivityItem
详见源码如下:
public class LaunchActivityItem extends ClientTransactionItem{
}
这时回退到第十步骤可以看到如下代码:clientTransaction.addCallback(LaunchActivityItem.obtain())
LaunchActivityItem.obtain方法返回的是LaunchActivityItem对象,具体可以查看源码
public static LaunchActivityItem obtain(Intent intent, 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 isForward, ProfilerInfo profilerInfo,
IBinder assistToken, FixedRotationAdjustments fixedRotationAdjustments) {
LaunchActivityItem instance = ObjectPool.obtain(LaunchActivityItem.class);
if (instance == null) {
instance = new LaunchActivityItem();
}
return instance;
}
根据如上分析可知: item.execute()方法最后执行的是LaunchActivityItem中的execute方法
16)进入LaunchActivityItem中的execute,源码:78行
@Override
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, mAssistToken, mFixedRotationAdjustments);
client.handleLaunchActivity(r, pendingActions, null /* customIntent */);
Trace.traceEnd(TRACE_TAG_ACTIVITY_MANAGER);
}
根据十三步中得知execute中接收的ClientTransactionHandler为ActivityThread对象,因此client.handleLaunchActivity方法最后执行的是ActivityThread中的handleLaunchActivity
17)进入ActivityThread中的handleLaunchActivity
public Activity handleLaunchActivity(ActivityClientRecord r,
PendingTransactionActions pendingActions, Intent customIntent) {
//见源码3601行
final Activity a = performLaunchActivity(r, customIntent);
return a;
}
//进入performLaunchActivity
private Activity performLaunchActivity(ActivityClientRecord r, Intent customIntent) {
ActivityInfo aInfo = r.activityInfo;
//见源码3419行
if (r.isPersistable()) {
mInstrumentation.callActivityOnCreate(activity, r.state, r.persistentState);
} else {
mInstrumentation.callActivityOnCreate(activity, r.state);
}
return activity;
}
18)进入Instrumentation类中的callActivityOnCreate方法,
public void callActivityOnCreate(Activity activity, Bundle icicle) {
prePerformCreate(activity);
activity.performCreate(icicle);
postPerformCreate(activity);
}
根据activity.performCreate(icicle)进入Activity中一探究竟
19)进入Activity类中performCreate方法
final void performCreate(Bundle icicle, PersistableBundle persistentState) {
//核心代码,见源码7997行
if (persistentState != null) {
onCreate(icicle, persistentState);
} else {
onCreate(icicle);
}
}
到此整个Activity的onCreate进行了触发,目标Activity的跳转流程执行完毕
如上便是9.0以上Activity的执行过程
根据上述流程,梳理了整个Activity的源码流程图如下:
调用流程图
如上流程,在不同的Android版本中存在差异,但,大致流程相通,
下图Android7.0版本中的启动流程
根据两个流程可知,低版本的Android系统中使用了ActivityThread.scheduleLaunchActivity进行了启动,而在高版本中使用了事务的方法进行整个流程的执行。