title: Activity启动startActivity
startActivity(new Intent(this, SecondActivity.class));
其实在前台Activity中启动另一个Activity的过程主要分为以下几步:
原Activity的onPause
新Activity的onCreate
新Activity的onStart
新Activity的onResume
原Activity的onStop
原Activity的onSaveInstanceState
[/frameworks/base/core/java/android/app/Activity.java]
public void startActivity(Intent intent, @Nullable Bundle options) {
if (options != null) {
startActivityForResult(intent, -1, options);
} else { //执行else中的操作
startActivityForResult(intent, -1);
}
[/framework/base/core/java/android/app/Instrumentation.java]
public ActivityResult execStartActivity(
Context who, IBinder contextThread, IBinder token, Activity target,
Intent intent, int requestCode, Bundle options) {
IApplicationThread whoThread = (IApplicationThread) contextThread;
try {
int result = ActivityManager.getService()
.startActivity(whoThread, who.getBasePackageName(), intent,
intent.resolveTypeIfNeeded(who.getContentResolver()),
token, target != null ? target.mEmbeddedID : null,
requestCode, 0, null, options); //调用AMS.startActivity
checkStartActivityResult(result, intent); //检查startActivity的结果
} catch (RemoteException e) {
throw new RuntimeException("Failure from system", e);
}
return null;
}
其中就是获取到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());
}
mActivityStarterController.obtainStarter函数返回一个ActivityStarter对象:
[/frameworks/base/services/core/java/com/android/server/am/ActivityStartController.java]
/**
* @return A starter to configure and execute starting an activity. It is valid until after
* {@link ActivityStarter#execute} is invoked. At that point, the starter should be
* considered invalid and no longer modified or used.
*/
ActivityStarter obtainStarter(Intent intent, String reason) {
return mFactory.obtain().setIntent(intent).setReason(reason);
}
类里面主要的执行的操作:
WMS.deferSurfaceLayout:暂停布局
ActivityStarter.startActivityUnchecked:关键函数,启动Activity
WMS.continueSurfaceLayout:继续布局
ActivityStarter.postStartActivityPorcessing
[/frameworks/base/services/core/java/com/android/server/am/ActivityStack.java]
boolean resumeFocusedStackTopActivityLocked(
ActivityStack targetStack, ActivityRecord target, ActivityOptions targetOptions) {
......
if (targetStack != null && isFocusedStack(targetStack)) { //执行该条件
return targetStack.resumeTopActivityUncheckedLocked(target, targetOptions);
}
......
return false;
}
final boolean startPausingLocked(boolean userLeaving, boolean uiSleeping,
ActivityRecord resuming, boolean pauseImmediately) {
...
if (prev.app != null && prev.app.thread != null) {
try {
... mService.getLifecycleManager().scheduleTransaction(prev.app.thread, prev.appToken,
PauseActivityItem.obtain(prev.finishing, userLeaving,
prev.configChangeFlags, pauseImmediately)); //关键操作
} catch (Exception e) {
.....
}
} else {
...
}
...
}
[//frameworks/base/services/core/java/com/android/server/am/ClientLifecycleManager.java ]
将PauseActivityItem对象设置到clientTransaction对象中。并返回该clientTransaction对象。
接下来看看ClientTransaction.schedule函数:
// /frameworks/base/core/java/android/app/servertransaction/ClientTransaction.java
private IApplicationThread mClient;
public void schedule() throws RemoteException {
mClient.scheduleTransaction(this);
}
mClient实质就是应用进程与系统进程(system_server)通信的服务端,即ActivityThread.ApplicaitonThread对象。所以接下来调用到了ActivityThread.ApplicationThread.sheduleTransaction函数:
///frameworks/base/core/java/android/app/ActivityThread.java
@Override
public void scheduleTransaction(ClientTransaction transaction) throws RemoteException {
ActivityThread.this.scheduleTransaction(transaction);
}
。接着来分析一下这三个过程。
执行到TransactionExecutor.execute函数做了些什么:
// /frameworks/base/core/java/android/app/servertransaction/TransactionExecutor.java
/** Transition to the final state if requested by the transaction. */
private void executeLifecycleState(ClientTransaction transaction) {
final ActivityLifecycleItem lifecycleItem = transaction.getLifecycleStateRequest(); //根据前文描述,lifecycleItem就是PauseActivityItem对象
cycleToPath(r, lifecycleItem.getTargetState(), true /* excludeLastState */);
// Execute the final transition with proper parameters.
lifecycleItem.execute(mTransactionHandler, token, mPendingActions);
lifecycleItem.postExecute(mTransactionHandler, token, mPendingActions);
}
PauseActivityItem.postExecute
该函数涉及到了新的Activity的启动流程,后续再接着分析。先看一下该函数的code。
@Override
public void postExecute(ClientTransactionHandler client, IBinder token,
PendingTransactionActions pendingActions) {
if (mDontReport) {
return;
}
try {
// TODO(lifecycler): Use interface callback instead of AMS.
ActivityManager.getService().activityPaused(token); //跨进程调用AMS.activityPaused函数
} catch (RemoteException ex) {
throw ex.rethrowFromSystemServer();
}
}
接下来要启动的Activity所在进程已启动,所以执行的是realStartActivityLocked函数:
// /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 {
try {
// Create activity launch transaction.
final ClientTransaction clientTransaction = ClientTransaction.obtain(app.thread,
r.appToken);
clientTransaction.addCallback(LaunchActivityItem.obtain(new Intent(r.intent),...,
profilerInfo)); //【1】将LaunchActivityItem这个callback添加到clientTransaction
// Set desired final state.
final ActivityLifecycleItem lifecycleItem;
if (andResume) { //andResume值为true
lifecycleItem = ResumeActivityItem.obtain(mService.isNextTransitionForward());
} else {
lifecycleItem = PauseActivityItem.obtain();
}
clientTransaction.setLifecycleStateRequest(lifecycleItem); //【2】将ResumeActivityItem设置给clientTransaction
// Schedule transaction.
mService.getLifecycleManager().scheduleTransaction(clientTransaction); //【3】调用ClientLifecycleManager.scheduleTransaction分发事务
...
} catch (RemoteException e) {
throw e;
}
}
return true;
}
该函数主要的操作:
// /frameworks/base/core/java/android/app/servertransaction/ClientTransaction.java
public void schedule() throws RemoteException {
mClient.scheduleTransaction(this);
}
此处的mClient是与系统进程通信的服务端,即ActivityThread.ApplicationThread,即此处调用的是ActivityThread.ApplicationThread.scheduleTransaction:
@Override
public void scheduleTransaction(ClientTransaction transaction) throws RemoteException {
ActivityThread.this.scheduleTransaction(transaction);
}
public void execute(ClientTransaction transaction) {
final IBinder token = transaction.getActivityToken();
log("Start resolving transaction for client: " + mTransactionHandler + ", token: " + token);
executeCallbacks(transaction);
executeLifecycleState(transaction);
mPendingActions.clear();
log("End resolving transaction");
}
此函数中依然有2个操作:
中。所以此处的:
// /frameworks/base/core/java/android/app/servertransaction/LaunchActivityItem.java
/** Cycle through all states requested by callbacks and execute them at proper times. */
@VisibleForTesting
public void executeCallbacks(ClientTransaction transaction) {
final List<ClientTransactionItem> callbacks = transaction.getCallbacks();
final int size = callbacks.size(); //callbacks.size = 1
for (int i = 0; i < size; ++i) {
final ClientTransactionItem item = callbacks.get(i); //item即是LaunchActivityItem
if (closestPreExecutionState != UNDEFINED) {
cycleToPath(r, closestPreExecutionState);
}
item.execute(mTransactionHandler, token, mPendingActions); //【1】
item.postExecute(mTransactionHandler, token, mPendingActions);
}
}
// /frameworks/base/core/java/android/app/ActivityThread.java
/**
* Extended implementation of activity launch. Used when server requests a launch or relaunch.
*/
@Override
public Activity handleLaunchActivity(ActivityClientRecord r,
PendingTransactionActions pendingActions, Intent customIntent) {
// Make sure we are running with the most recent config.
handleConfigurationChanged(null, null); //确保使用了最新的配置信息
final Activity a = performLaunchActivity(r, customIntent); //【关键操作】
if (a != null) {
r.createdConfig = new Configuration(mConfiguration);
} else { //如果launch activity失败,则finish Activity
// If there was an error, for any reason, tell the activity manager to stop us.
}
return a;
}
里面
函数里做了主要做了两件事:
①handleConfigurationChanged:确保启动的Activity使用的是最新的配置
②performLaunchActivity:启动Activity
// /frameworks/base/core/java/android/app/ActivityThread.java
/** Core implementation of activity launch. */
private Activity performLaunchActivity(ActivityClientRecord r, Intent customIntent) {
//从ActivityClientRecord中获取待启动Activity的信息
ActivityInfo aInfo = r.activityInfo;
ComponentName component = r.intent.getComponent(); //【1】获取ComponentName
ContextImpl appContext = createBaseContextForActivity(r); //【2】创建Context
Activity activity = null;
try {
java.lang.ClassLoader cl = appContext.getClassLoader();
activity = mInstrumentation.newActivity(
cl, component.getClassName(), r.intent); //【3】使用类加载器新建Activity
} catch (Exception e) {
}
try {
//【4】创建Application,也是通过类加载器来创建的,
//创建完毕后会通过调用Instrumentation.callApplicationOnCreate来调用Application的onCreate方法e
Application app = r.packageInfo.makeApplication(false, mInstrumentation);
if (activity != null) {
CharSequence title = r.activityInfo.loadLabel(appContext.getPackageManager());
Configuration config = new Configuration(mCompatConfiguration);
if (r.overrideConfig != null) {
config.updateFrom(r.overrideConfig); //应用配置信息
}
appContext.setOuterContext(activity); //【5】将新的Activity与新建的context关联
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);//attach方法中Activity会完成Window的创建并建立自己与Window的关联,这样当Window接收到外部输入事件后就可以将事件传递给Activity
}
r.setState(ON_CREATE); //记录当前Activity的状态为ON_CREATE
mActivities.put(r.token, r);
mInstrumentation.callActivityOnCreate(activity, r.state); //【6】调用Instrumentation.callActivityOnCreate执行onCreate流程
} catch (SuperNotCalledException e) {
} catch (Exception e) {
}
return activity;
}
,主要完成的工作:
ComponentName component:获取ComponentName
ContextImpl appContext:创建Context
Activity activity:新建Activity
Application app:创建Application
activity.attach:管理activity与context
callActivityOnCreate:启动Activity
其实这个函数非常重要,但是我们此时关注的是Activity的生命周期流程,所以还是直接看Instrumentation.callActivityOnCreate函数
// /frameworks/base/core/java/android/app/Instrumentation.java
public void callActivityOnCreate(Activity activity, Bundle icicle) {
prePerformCreate(activity);
activity.performCreate(icicle);
postPerformCreate(activity);
}
,此函数中有三个操作:
①prePerformCreate:create操作之前做的事
②activity.performCreate:create操作
③postPerformCreate:create操作之后做的事
// /frameworks/base/core/java/android/app/Activity.java
final void performCreate(Bundle icicle) {
performCreate(icicle, null);
}
final void performCreate(Bundle icicle, PersistableBundle persistentState) {
mCanEnterPictureInPicture = true;
restoreHasCurrentPermissionRequest(icicle);
if (persistentState != null) { //传入的参数persistentState =null
onCreate(icicle, persistentState);
} else {
onCreate(icicle); //调用了onCreate函数
}
writeEventLog(LOG_AM_ON_CREATE_CALLED, "performCreate");
mActivityTransitionState.readState(icicle);
mVisibleFromClient = !mWindow.getWindowStyle().getBoolean(
com.android.internal.R.styleable.Window_windowNoDisplay, false);
mFragments.dispatchActivityCreated(); //fragment的create处理
mActivityTransitionState.setEnterActivityOptions(this, getActivityOptions());
}
executeLifecycleState
先看源码:
// /frameworks/base/core/java/android/app/servertransaction/TransactionExecutor.java
private void executeLifecycleState(ClientTransaction transaction) {
final ActivityLifecycleItem lifecycleItem = transaction.getLifecycleStateRequest();
if (lifecycleItem == null) {
// No lifecycle request, return early.
return;
}
cycleToPath(r, lifecycleItem.getTargetState(), true /* excludeLastState */);
// Execute the final transition with proper parameters.
lifecycleItem.execute(mTransactionHandler, token, mPendingActions);
lifecycleItem.postExecute(mTransactionHandler, token, mPendingActions);
}
如前文所述,此处的ActivityLifecycleItem参数为ResumeActivityItem,所以该函数实际完成的操作:
(1) ResumeActivityItem.execute
(2)ResumeActivity.postExecute