我们来看一下Activity启动流程,当 A 调用 startActivity(intent); 启动 B 的时候,系统是如何帮我们打开一个新的Activity的?
下面我们来从源码分析(Api : 25):
1、首先我们来到Activity类中
@Override
public void startActivity(Intent intent) {
this.startActivity(intent, null);
}
@Override
public void startActivity(Intent intent, @Nullable Bundle options) {
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.ActivityResult ar =
// 关键是调用这句代码
mInstrumentation.execStartActivity(
this, mMainThread.getApplicationThread(), mToken, this,
intent, requestCode, options);
// ...
} else {
// ...
}
}
执行 mInstrumentation.execStartActivity方法,我们找到 mInstrumentation 为 Instrumentation这个类
2、我们现在来到Instrumentation类中
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 = ActivityManagerNative.getDefault()
.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;
}
这里 ActivityManagerNative.getDefault() 返回的是一个 IActivityManager 接口,并且 ActivityManagerNative是实现 IActivityManager 接口的
3、我们来到 ActivityManagerNative类中
public int startActivity(IApplicationThread caller, String callingPackage, Intent intent,
String resolvedType, IBinder resultTo, String resultWho, int requestCode,
int startFlags, ProfilerInfo profilerInfo, Bundle options) throws RemoteException {
// 典型的IPC机制,这里保存了一些数据
Parcel data = Parcel.obtain();
Parcel reply = Parcel.obtain();
data.writeInterfaceToken(IActivityManager.descriptor);
data.writeStrongBinder(caller != null ? caller.asBinder() : null);
data.writeString(callingPackage);
intent.writeToParcel(data, 0);
data.writeString(resolvedType);
data.writeStrongBinder(resultTo);
data.writeString(resultWho);
data.writeInt(requestCode);
data.writeInt(startFlags);
if (profilerInfo != null) {
data.writeInt(1);
profilerInfo.writeToParcel(data, Parcelable.PARCELABLE_WRITE_RETURN_VALUE);
} else {
data.writeInt(0);
}
if (options != null) {
data.writeInt(1);
options.writeToParcel(data, 0);
} else {
data.writeInt(0);
}
// IPC机制,发送一个消息,我们直接在本类中来搜 START_ACTIVITY_TRANSACTION,搜索服务端的代码
mRemote.transact(START_ACTIVITY_TRANSACTION, data, reply, 0);
reply.readException();
int result = reply.readInt();
reply.recycle();
data.recycle();
return result;
}
@Override
public boolean onTransact(int code, Parcel data, Parcel reply, int flags)
throws RemoteException {
switch (code) {
// 这里就是我们搜索到服务端代码入口
case START_ACTIVITY_TRANSACTION:
{
// 接收客户端传来的消息
data.enforceInterface(IActivityManager.descriptor);
IBinder b = data.readStrongBinder();
IApplicationThread app = ApplicationThreadNative.asInterface(b);
String callingPackage = data.readString();
Intent intent = Intent.CREATOR.createFromParcel(data);
String resolvedType = data.readString();
IBinder resultTo = data.readStrongBinder();
String resultWho = data.readString();
int requestCode = data.readInt();
int startFlags = data.readInt();
ProfilerInfo profilerInfo = data.readInt() != 0
? ProfilerInfo.CREATOR.createFromParcel(data) : null;
Bundle options = data.readInt() != 0
? Bundle.CREATOR.createFromParcel(data) : null;
// 启动Activity,ActivityManagerNative是一个抽象类的,所以这里调用ActivityManagerService中的startActivity
int result = startActivity(app, callingPackage, intent, resolvedType,
resultTo, resultWho, requestCode, startFlags, profilerInfo, options);
reply.writeNoException();
reply.writeInt(result);
return true;
}
// ...
}
4、我们来到 ActivityManagerService 类中
@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());
}
@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) {
// 这里调用ActivityStarter类中的startActivityMayWait
return mActivityStarter.startActivityMayWait(caller, -1, callingPackage, intent,
resolvedType, null, null, resultTo, resultWho, requestCode, startFlags,
profilerInfo, null, null, bOptions, false, userId, null, null);
}
5、我们来到 ActivityStarter 类中
final 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, IActivityManager.WaitResult outResult, Configuration config,
Bundle bOptions, boolean ignoreTargetSecurity, int userId,
IActivityContainer iContainer, TaskRecord inTask) {
// ...
int res = startActivityLocked(caller, intent, ephemeralIntent, resolvedType,
aInfo, rInfo, voiceSession, voiceInteractor,
resultTo, resultWho, requestCode, callingPid,
callingUid, callingPackage, realCallingPid, realCallingUid, startFlags,
options, ignoreTargetSecurity, componentSpecified, outRecord, container,
inTask);
// ...
return res;
}
final int startActivityLocked(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,
ActivityOptions options, boolean ignoreTargetSecurity, boolean componentSpecified,
ActivityRecord[] outActivity, ActivityStackSupervisor.ActivityContainer container,
TaskRecord inTask) {
// ...
int err = startActivityUnchecked(r, sourceRecord, voiceSession, voiceInteractor, startFlags,
true, options, inTask);
return err;
}
private int startActivityUnchecked(final ActivityRecord r, ActivityRecord sourceRecord,
IVoiceInteractionSession voiceSession, IVoiceInteractor voiceInteractor,
int startFlags, boolean doResume, ActivityOptions options, TaskRecord inTask) {
// ...
// mSupervisor: ActivityStackSupervisor
mSupervisor.resumeFocusedStackTopActivityLocked(mTargetStack, mStartActivity,
mOptions);
// ...
return START_SUCCESS;
}
6、我们来到 ActivityStackSupervisor 类中
boolean resumeFocusedStackTopActivityLocked(
ActivityStack targetStack, ActivityRecord target, ActivityOptions targetOptions) {
if (targetStack != null && isFocusedStack(targetStack)) {
// targetStack : ActivityStack
return targetStack.resumeTopActivityUncheckedLocked(target, targetOptions);
}
// ...
return false;
}
7、我们来到 ActivityStack 类中
boolean resumeTopActivityUncheckedLocked(ActivityRecord prev, ActivityOptions options) {
// ...
boolean result = false;
try {
// ...
// 关键调用这句代码
result = resumeTopActivityInnerLocked(prev, options);
} finally {
mStackSupervisor.inResumeTopActivity = false;
}
return result;
}
private boolean resumeTopActivityInnerLocked(ActivityRecord prev, ActivityOptions options) {
// ...
if (mResumedActivity != null) {
// 此处就会调用暂停方法
pausing |= startPausingLocked(userLeaving, false, next, dontWaitForPause);
}
//mStackSupervisor : ActivityStackSupervisor,这里就会调用新建方法
mStackSupervisor.startSpecificActivityLocked(next, true, true);
return true;
}
final boolean startPausingLocked(boolean userLeaving, boolean uiSleeping,
ActivityRecord resuming, boolean dontWait) {
// ...
// prev.app.thread为 ActivityThread
prev.app.thread.schedulePauseActivity(prev.appToken, prev.finishing,
userLeaving, prev.configChangeFlags, dontWait);
// ...
return true;
}
8、我们先来看暂停的方法,我们来到 ActivityThread 类中
public final void schedulePauseActivity(IBinder token, boolean finished,
boolean userLeaving, int configChanges, boolean dontReport) {
int seq = getLifecycleSeq();
// 发送了一个消息,消息key: PAUSE_ACTIVITY,我们来搜这个key
sendMessage(
finished ? H.PAUSE_ACTIVITY_FINISHING : H.PAUSE_ACTIVITY,
token,
(userLeaving ? USER_LEAVING : 0) | (dontReport ? DONT_REPORT : 0),
configChanges,
seq);
}
case PAUSE_ACTIVITY: {
// 关键调用方法
handlePauseActivity((IBinder) args.arg1, false,
(args.argi1 & USER_LEAVING) != 0, args.argi2,
(args.argi1 & DONT_REPORT) != 0, args.argi3);
maybeSnapshot();
Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);
} break;
private void handlePauseActivity(IBinder token, boolean finished,
boolean userLeaving, int configChanges, boolean dontReport, int seq) {
// ...
performPauseActivity(token, finished, r.isPreHoneycomb(), "handlePauseActivity");
// ...
}
final Bundle performPauseActivity(ActivityClientRecord r, boolean finished,
boolean saveState, String reason) {
// ...
performPauseActivityIfNeeded(r, reason);
// ...
return !r.activity.mFinished && saveState ? r.state : null;
}
private void performPauseActivityIfNeeded(ActivityClientRecord r, String reason) {
// ...
// mInstrumentation: Instrumentation
mInstrumentation.callActivityOnPause(r.activity);
// ...
}
9、我们来到Instrumentation类中:
public void callActivityOnPause(Activity activity) {
activity.performPause();
}
10、我们来到Activity类中
final void performPause() {
// ...
// 终于看到了一个我们比较熟悉的方法,到这里调用了A的暂停方法
onPause();
// ...
mResumed = false;
}
11、还记得我们在第7步中还有一个方法没走嘛? 现在我们回到 第7步中的ActivityStack 的resumeTopActivityInnerLocked方法中,在暂停方法下面还有一个新建方法:mStackSupervisor.startSpecificActivityLocked(next, true, true);
我们来到ActivityStackSupervisor类中
void startSpecificActivityLocked(ActivityRecord r,
boolean andResume, boolean checkConfig) {
// ...
// 关键代码
realStartActivityLocked(r, app, andResume, checkConfig);
// ...
}
final boolean realStartActivityLocked(ActivityRecord r, ProcessRecord app,
boolean andResume, boolean checkConfig) throws RemoteException {
// ...
// 关键代码,app.thread:ActivityThread
app.thread.scheduleLaunchActivity(new Intent(r.intent), r.appToken,
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);
// ...
return true;
}
12、我们再次来到 ActivityThread 类中
@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) {
// ...
// 关键代码,发送一个消息,消息key为 LAUNCH_ACTIVITY,我们来搜 LAUNCH_ACTIVITY
sendMessage(H.LAUNCH_ACTIVITY, r);
}
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);
// 关键代码
handleLaunchActivity(r, null, "LAUNCH_ACTIVITY");
Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);
} break;
private void handleLaunchActivity(ActivityClientRecord r, Intent customIntent, String reason) {
// ...
// 关键代码
Activity a = performLaunchActivity(r, customIntent);
if (a != null) {
// ...
// 关键代码
handleResumeActivity(r.token, false, r.isForward,
!r.activity.mFinished && !r.startsNotResumed, r.lastProcessedSeq, reason);
}
// 关键代码
Looper.myQueue().addIdleHandler(new Idler());
}
private Activity performLaunchActivity(ActivityClientRecord r, Intent customIntent) {
// System.out.println("##### [" + System.currentTimeMillis() + "] ActivityThread.performLaunchActivity(" + r + ")");
// mInstrumentation: Instrumentation
mInstrumentation.callActivityOnCreate(activity, r.state);
return activity;
}
13、我们再次来到Instrumentation类中:
public void callActivityOnCreate(Activity activity, Bundle icicle,
PersistableBundle persistentState) {
prePerformCreate(activity);
activity.performCreate(icicle, persistentState);
postPerformCreate(activity);
}
14、我们再次来到Activity类中
final void performCreate(Bundle icicle) {
restoreHasCurrentPermissionRequest(icicle);
// 终于看到了我们的onCreate方法
onCreate(icicle);
mActivityTransitionState.readState(icicle);
performCreateCommon();
}
15、我们再次回到12 的 ActivityThread的handleLaunchActivity方法中,继续执行handleResumeActivity方法
final void handleResumeActivity(IBinder token,
boolean clearHide, boolean isForward, boolean reallyResume, int seq, String reason) {
r = performResumeActivity(token, clearHide, reason);
}
public final ActivityClientRecord performResumeActivity(IBinder token,
boolean clearHide, String reason) {
// ...
r.activity.performResume();
return r;
}
16、我们再次来到Activity类中
final void performResume() {
// ...
performRestart();
// ...
// mInstrumentation: Instrumentation
mInstrumentation.callActivityOnResume(this);
}
final void performRestart() {
performStart();
}
final void performStart() {
// mInstrumentation: Instrumentation
mInstrumentation.callActivityOnStart(this);
}
17、我们再次来到Instrumentation类中:
public void callActivityOnStart(Activity activity) {
// 在这里看到了我们的onStart方法
activity.onStart();
}
public void callActivityOnResume(Activity activity) {
// 在这里看到了我们的onResume方法
activity.onResume();
}
18、我们再次回到12 的 ActivityThread的handleLaunchActivity方法中,继续执行Looper.myQueue().addIdleHandler(new Idler());方法
private class Idler implements MessageQueue.IdleHandler {
@Override
public final boolean queueIdle() {
// ...
// 这里的am就是ActivityManagerService
IActivityManager am = ActivityManagerNative.getDefault();
am.activityIdle(a.token, a.createdConfig, stopProfiling);
// ...
}
}
19、我们再次来到ActivityManagerService 类中:
@Override
public final void activityIdle(IBinder token, Configuration config, boolean stopProfiling) {
// ...
// 这里的mStackSupervisor:ActivityStackSupervisor
ActivityRecord r = mStackSupervisor.activityIdleInternalLocked(token, false, config);
// ...
}
20、我们再次来到 ActivityStackSupervisor 类中:
final ActivityRecord activityIdleInternalLocked(final IBinder token, boolean fromTimeout,
Configuration config) {
// ...
// 这里的stack: ActivityStack
stack.stopActivityLocked(r);
// ...
return r;
}
21、我们来到 ActivityStack 类中
final void stopActivityLocked(ActivityRecord r) {
r.app.thread.scheduleStopActivity(r.appToken, r.visible, r.configChangeFlags);
}
22、我们再次来到ActivityThread类中
public final void scheduleStopActivity(IBinder token, boolean showWindow,
int configChanges) {
int seq = getLifecycleSeq();
if (DEBUG_ORDER) Slog.d(TAG, "stopActivity " + ActivityThread.this
+ " operation received seq: " + seq);
sendMessage(
// 发送一个消息STOP_ACTIVITY_SHOW,我们来搜这个STOP_ACTIVITY_SHOW
showWindow ? H.STOP_ACTIVITY_SHOW : H.STOP_ACTIVITY_HIDE,
token, 0, configChanges, seq);
}
case STOP_ACTIVITY_SHOW: {
Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, "activityStop");
SomeArgs args = (SomeArgs) msg.obj;
// 关键方法
handleStopActivity((IBinder) args.arg1, true, args.argi2, args.argi3);
Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);
} break;
private void handleStopActivity(IBinder token, boolean show, int configChanges, int seq) {
// 关键方法
performStopActivityInner(r, info, show, true, "handleStopActivity");
}
private void performStopActivityInner(ActivityClientRecord r,
StopInfo info, boolean keepShown, boolean saveState, String reason) {
r.activity.performStop(false /*preserveWindow*/);
}
23、我们再次来到Activity类中
final void performStop(boolean preserveWindow) {
mInstrumentation.callActivityOnStop(this);
}
24、我们再次来到Instrumentation类中:
public void callActivityOnStop(Activity activity) {
activity.onStop();
}
总结:
A启动B方法顺序: A的onPause -> B的onCreate -> B的onStart方法 -> B的onResume -> A的onStop