Activty是Android四大组件之一,是大家用的最多的组件,今天我们来了解下Activity的启动过程
首先来大致了解总体启动流程
步骤具体内容:
1、Launcher进程通过Binder驱动想ActivityManagerServcie类发起startActivity请求;
2、ActivityManagerService类接收到请求后,向ActivityStack类发送启动Activity的请求;
3、ActivityStack类记录启动Activity的信息 & 调整Activity栈将其置于栈顶、通过Binder驱动将Activity的启动信息传递到AplicationThread线程中(即Binder线程)
4、AplicationThread线程通过Handler将Activity的启动信息发送到主线程ActivityThread;
5、主线程类接收到该信息 & 请求后,通过类加载器ClassLoader机制加载相应的Activity类,调用Activity的onreate(),最后启动完毕
详细解析,从startActivity开始
Intent intent11 = new Intent(this, ThreadPoolDemoActivity.class);
startActivity(intent11);
进入startActivity源码:
@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 {
// Note we want to go through this call for compatibility with
// applications that may have overridden the method.
startActivityForResult(intent, -1);
}
}
通过源码可以看到,startActivity()实际调用的是startActivityForResult(Intent intent),接着进入startActivityForResult(intent, -1)
public void startActivityForResult(@RequiresPermission Intent intent, int requestCode) {
startActivityForResult(intent, requestCode, null);
}
public void startActivityForResult(@RequiresPermission Intent intent, int requestCode,
@Nullable Bundle options) {
//一般的Activity的mParent都为null,其用在ActivityGroup,可以在一个界面里嵌套多个
//Activity。随着版本的升级,在API13以后ActivityGroup就废弃掉了
if (mParent == null) {
//如果options为null话,ActivityManager.getService().getActivityOptions(mToken)
//获取
options = transferSpringboardActivityOptions(options);
//这里才是启动Activity的入口
Instrumentation.ActivityResult ar =
mInstrumentation.execStartActivity(
this, mMainThread.getApplicationThread(), mToken, this,
intent, requestCode, options);
if (ar != null) {
mMainThread.sendActivityResult(
mToken, mEmbeddedID, requestCode, ar.getResultCode(),
ar.getResultData());
}
if (requestCode >= 0) {
// If this start is requesting a result, we can avoid making
// the activity visible until the result is received. Setting
// this code during onCreate(Bundle savedInstanceState) or onResume() will keep the
// activity hidden during this time, to avoid flickering.
// This can only be done when a result is requested because
// that guarantees we will get information back when the
// activity is finished, no matter what happens to it.
mStartedActivity = true;
}
cancelInputsAndStartExitTransition(options);
// TODO Consider clearing/flushing other event sources and events for child windows.
} else {
if (options != null) {
mParent.startActivityFromChild(this, intent, requestCode, options);
} else {
// Note we want to go through this method for compatibility with
// existing applications that may have overridden it.
mParent.startActivityFromChild(this, intent, requestCode);
}
}
}
启动activity会调用这个方法 Instrumentation.ActivityResult ar =mInstrumentation.execStartActivity(this, mMainThread.getApplicationThread(), mToken, this,intent, requestCode, options);会传入mMainThread.getAoolicationThread(),
public ActivityResult execStartActivity(
Context who, IBinder contextThread, IBinder token, Activity target,
Intent intent, int requestCode, Bundle options) {
//核心功能在这个whoThread中完成,其内部scheduleLaunchActivity方法用于完成activity的打开
IApplicationThread whoThread = (IApplicationThread) contextThread;
Uri referrer = target != null ? target.onProvideReferrer() : null;
if (referrer != null) {
intent.putExtra(Intent.EXTRA_REFERRER, referrer);
}
if (mActivityMonitors != null) {
synchronized (mSync) {
//先遍历查找是否存在该Activity
final int N = mActivityMonitors.size();
for (int i=0; i= 0 ? am.getResult() : null;
}
break;
}
}
}
}
try {
intent.migrateExtraStreamToClipData();
intent.prepareToLeaveProcess(who);
//在这里启动Activity,其核心为whoThread启动Activity
int result = ActivityManager.getService()
.startActivity(whoThread, who.getBasePackageName(), intent,
intent.resolveTypeIfNeeded(who.getContentResolver()),
token, target != null ? target.mEmbeddedID : null,
requestCode, 0, null, options);
//异常检测,并跑出异常
checkStartActivityResult(result, intent);
} catch (RemoteException e) {
throw new RuntimeException("Failure from system", e);
}
return null;
}
继续进入ActivityManager.getService().startActivity()如下源码:
@Override
4516 public final int startActivity(IApplicationThread caller, String callingPackage,
4517 Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode,
4518 int startFlags, ProfilerInfo profilerInfo, Bundle bOptions) {
4519 return startActivityAsUser(caller, callingPackage, intent, resolvedType, resultTo,
4520 resultWho, requestCode, startFlags, profilerInfo, bOptions,
4521 UserHandle.getCallingUserId());
4522 }
4523
4524 @Override
4525 public final int startActivityAsUser(IApplicationThread caller, String callingPackage,
4526 Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode,
4527 int startFlags, ProfilerInfo profilerInfo, Bundle bOptions, int userId) {
4528 enforceNotIsolatedCaller("startActivity");
4529 userId = mUserController.handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(),
4530 userId, false, ALLOW_FULL_ONLY, "startActivity", null);
4531 // TODO: Switch to user app stacks here.
4532 return mActivityStarter.startActivityMayWait(caller, -1, callingPackage, intent,
4533 resolvedType, null, null, resultTo, resultWho, requestCode, startFlags,
4534 profilerInfo, null, null, bOptions, false, userId, null, "startActivityAsUser");
4535 }
4536
下面进入ActivityStarter类,startActivityMayWait方法的实现
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, WaitResult outResult,
Configuration globalConfig, Bundle bOptions, boolean ignoreTargetSecurity, int userId,
TaskRecord inTask, String reason) {
....
int res = startActivityLocked(caller, intent, ephemeralIntent, resolvedType,
aInfo, rInfo, voiceSession, voiceInteractor,
resultTo, resultWho, requestCode, callingPid,
callingUid, callingPackage, realCallingPid, realCallingUid, startFlags,
options, ignoreTargetSecurity, componentSpecified, outRecord, inTask,
reason);
...
return res;
}
int startActivityLocked(IApplicationThread caller, Intent intent, Intent ephemeralIntent,
264 String resolvedType, ActivityInfo aInfo, ResolveInfo rInfo,
265 IVoiceInteractionSession voiceSession, IVoiceInteractor voiceInteractor,
266 IBinder resultTo, String resultWho, int requestCode, int callingPid, int callingUid,
267 String callingPackage, int realCallingPid, int realCallingUid, int startFlags,
268 ActivityOptions options, boolean ignoreTargetSecurity, boolean componentSpecified,
269 ActivityRecord[] outActivity, TaskRecord inTask, String reason) {
270
271 if (TextUtils.isEmpty(reason)) {
272 throw new IllegalArgumentException("Need to specify a reason.");
273 }
274 mLastStartReason = reason;
275 mLastStartActivityTimeMs = System.currentTimeMillis();
276 mLastStartActivityRecord[0] = null;
277
278 mLastStartActivityResult = startActivity(caller, intent, ephemeralIntent, resolvedType,
279 aInfo, rInfo, voiceSession, voiceInteractor, resultTo, resultWho, requestCode,
280 callingPid, callingUid, callingPackage, realCallingPid, realCallingUid, startFlags,
281 options, ignoreTargetSecurity, componentSpecified, mLastStartActivityRecord,
282 inTask);
283
284 if (outActivity != null) {
285 // mLastStartActivityRecord[0] is set in the call to startActivity above.
286 outActivity[0] = mLastStartActivityRecord[0];
287 }
288
289 // Aborted results are treated as successes externally, but we must track them internally.
290 return mLastStartActivityResult != START_ABORTED ? mLastStartActivityResult : START_SUCCESS;
291 }
private int startActivity(final ActivityRecord r, ActivityRecord sourceRecord,
989 IVoiceInteractionSession voiceSession, IVoiceInteractor voiceInteractor,
990 int startFlags, boolean doResume, ActivityOptions options, TaskRecord inTask,
991 ActivityRecord[] outActivity) {
992 int result = START_CANCELED;
993 try {
994 mService.mWindowManager.deferSurfaceLayout();
995 result = startActivityUnchecked(r, sourceRecord, voiceSession, voiceInteractor,
996 startFlags, doResume, options, inTask, outActivity);
997 } finally {
998 // If we are not able to proceed, disassociate the activity from the task. Leaving an
999 // activity in an incomplete state can lead to issues, such as performing operations
1000 // without a window container.
1001 if (!ActivityManager.isStartResultSuccessful(result)
1002 && mStartActivity.getTask() != null) {
1003 mStartActivity.getTask().removeActivity(mStartActivity);
1004 }
1005 mService.mWindowManager.continueSurfaceLayout();
1006 }
1007
1008 postStartActivityProcessing(r, result, mSupervisor.getLastStack().mStackId, mSourceRecord,
1009 mTargetStack);
1010
1011 return result;
1012 }
private int startActivityUnchecked(final ActivityRecord r, ActivityRecord sourceRecord,
IVoiceInteractionSession voiceSession, IVoiceInteractor voiceInteractor,
int startFlags, boolean doResume, ActivityOptions options, TaskRecord inTask,
ActivityRecord[] outActivity) {
....
mTargetStack.startActivityLocked(mStartActivity, topFocused, newTask, mKeepCurTransition, mOptions);
if (mDoResume) {
final ActivityRecord topTaskActivity =
mStartActivity.getTask().topRunningActivityLocked();
if (!mTargetStack.isFocusable()
|| (topTaskActivity != null && topTaskActivity.mTaskOverlay
&& mStartActivity != topTaskActivity)) {
// If the activity is not focusable, we can't resume it, but still would like to // make sure it becomes visible as it starts (this will also trigger entry
// animation). An example of this are PIP activities.
// Also, we don't want to resume activities in a task that currently has an overlay
// as the starting activity just needs to be in the visible paused state until the
// over is removed.
mTargetStack.ensureActivitiesVisibleLocked(null, 0, !PRESERVE_WINDOWS);
// Go ahead and tell window manager to execute app transition for this activity
// since the app transition will not be triggered through the resume channel.
mWindowManager.executeAppTransition();
} else {
// If the target stack was not previously focusable (previous top running activity
// on that stack was not visible) then any prior calls to move the stack to the
// will not update the focused stack. If starting the new activity now allows the
// task stack to be focusable, then ensure that we now update the focused stack
// accordingly.
if (mTargetStack.isFocusable() &&!mSupervisor.isFocusedStack(mTargetStack)) {
mTargetStack.moveToFront("startActivityUnchecked");
}
mSupervisor.resumeFocusedStackTopActivityLocked(mTargetStack, mStartActivity,mOptions);
}
} else {
mTargetStack.addRecentActivityLocked(mStartActivity);
}
mSupervisor.updateUserStackLocked(mStartActivity.userId, mTargetStack);
mSupervisor.handleNonResizableTaskIfNeeded(mStartActivity.getTask(), preferredLaunchStackId, preferredLaunchDisplayId, mTargetStack.mStackId);
}
private int startActivityUnchecked(final ActivityRecord r, ActivityRecord sourceRecord,
IVoiceInteractionSession voiceSession, IVoiceInteractor voiceInteractor,
int startFlags, boolean doResume, ActivityOptions options, TaskRecord inTask,
ActivityRecord[] outActivity) {
....
mTargetStack.startActivityLocked(mStartActivity, topFocused, newTask, mKeepCurTransition, mOptions);
if (mDoResume) {
final ActivityRecord topTaskActivity =
mStartActivity.getTask().topRunningActivityLocked();
if (!mTargetStack.isFocusable()
|| (topTaskActivity != null && topTaskActivity.mTaskOverlay
&& mStartActivity != topTaskActivity)) {
// If the activity is not focusable, we can't resume it, but still would like to // make sure it becomes visible as it starts (this will also trigger entry
// animation). An example of this are PIP activities.
// Also, we don't want to resume activities in a task that currently has an overlay
// as the starting activity just needs to be in the visible paused state until the
// over is removed.
mTargetStack.ensureActivitiesVisibleLocked(null, 0, !PRESERVE_WINDOWS);
// Go ahead and tell window manager to execute app transition for this activity
// since the app transition will not be triggered through the resume channel.
mWindowManager.executeAppTransition();
} else {
// If the target stack was not previously focusable (previous top running activity
// on that stack was not visible) then any prior calls to move the stack to the
// will not update the focused stack. If starting the new activity now allows the
// task stack to be focusable, then ensure that we now update the focused stack
// accordingly.
if (mTargetStack.isFocusable() &&!mSupervisor.isFocusedStack(mTargetStack)) {
mTargetStack.moveToFront("startActivityUnchecked");
}
mSupervisor.resumeFocusedStackTopActivityLocked(mTargetStack, mStartActivity,mOptions);
}
} else {
mTargetStack.addRecentActivityLocked(mStartActivity);
}
mSupervisor.updateUserStackLocked(mStartActivity.userId, mTargetStack);
mSupervisor.handleNonResizableTaskIfNeeded(mStartActivity.getTask(), preferredLaunchStackId, preferredLaunchDisplayId, mTargetStack.mStackId);
}
private int startActivityUnchecked(final ActivityRecord r, ActivityRecord sourceRecord,
IVoiceInteractionSession voiceSession, IVoiceInteractor voiceInteractor,
int startFlags, boolean doResume, ActivityOptions options, TaskRecord inTask,
ActivityRecord[] outActivity) {
....
mTargetStack.startActivityLocked(mStartActivity, topFocused, newTask, mKeepCurTransition, mOptions);
if (mDoResume) {
final ActivityRecord topTaskActivity =
mStartActivity.getTask().topRunningActivityLocked();
if (!mTargetStack.isFocusable()
|| (topTaskActivity != null && topTaskActivity.mTaskOverlay
&& mStartActivity != topTaskActivity)) {
// If the activity is not focusable, we can't resume it, but still would like to // make sure it becomes visible as it starts (this will also trigger entry
// animation). An example of this are PIP activities.
// Also, we don't want to resume activities in a task that currently has an overlay
// as the starting activity just needs to be in the visible paused state until the
// over is removed.
mTargetStack.ensureActivitiesVisibleLocked(null, 0, !PRESERVE_WINDOWS);
// Go ahead and tell window manager to execute app transition for this activity
// since the app transition will not be triggered through the resume channel.
mWindowManager.executeAppTransition();
} else {
// If the target stack was not previously focusable (previous top running activity
// on that stack was not visible) then any prior calls to move the stack to the
// will not update the focused stack. If starting the new activity now allows the
// task stack to be focusable, then ensure that we now update the focused stack
// accordingly.
if (mTargetStack.isFocusable() &&!mSupervisor.isFocusedStack(mTargetStack)) {
mTargetStack.moveToFront("startActivityUnchecked");
}
mSupervisor.resumeFocusedStackTopActivityLocked(mTargetStack, mStartActivity,mOptions);
}
} else {
mTargetStack.addRecentActivityLocked(mStartActivity);
}
mSupervisor.updateUserStackLocked(mStartActivity.userId, mTargetStack);
mSupervisor.handleNonResizableTaskIfNeeded(mStartActivity.getTask(), preferredLaunchStackId, preferredLaunchDisplayId, mTargetStack.mStackId);
}
mSupervisor是一个ActivityStackSupervisor对象;
查看ActivityStackSupervisor源码如下:
void startSpecificActivityLocked(ActivityRecord r,
boolean andResume, boolean checkConfig) {
//...code
realStartActivityLocked(r, app, andResume, checkConfig);
//...code
}
//继续查看
final boolean realStartActivityLocked(ActivityRecord r, ProcessRecord app,
boolean andResume, boolean checkConfig) throws RemoteException {
//...code
final MergedConfiguration mergedConfiguration = new MergedConfiguration(
mService.getGlobalConfiguration(), r.getMergedOverrideConfiguration());
r.setLastReportedConfiguration(mergedConfiguration);
logIfTransactionTooLarge(r.intent, r.icicle);
app.thread.scheduleLaunchActivity(new Intent(r.intent), r.appToken,
System.identityHashCode(r), r.info,
// TODO: Have this take the merged configuration instead of separate global
// and override configs.
mergedConfiguration.getGlobalConfiguration(),
mergedConfiguration.getOverrideConfiguration(), r.compat,
r.launchedFromPackage, task.voiceInteractor, app.repProcState, r.icicle,
r.persistentState, results, newIntents, !andResume,
mService.isNextTransitionForward(), profilerInfo);
//...code
}
这里实现的app.thread.scheduleLaunchActivity(),是ActivityThread类中的方法,其代码实现如下:
进入sendMessage(),传入的H.LAUNCH_ACTIVITY
看看这个Handler是在哪里,H是ActivityThread的一个内部类
LAUNCH_ACTIVITY这里调用了handlLaunchActivity,进入里面看看
private void handleLaunchActivity(ActivityClientRecord r, Intent customIntent, String reason) {
2834 // If we are getting ready to gc after going to the background, well
2835 // we are back active so skip it.
2836 unscheduleGcIdler();
2837 mSomeActivitiesChanged = true;
2838
2839 if (r.profilerInfo != null) {
2840 mProfiler.setProfiler(r.profilerInfo);
2841 mProfiler.startProfiling();
2842 }
2843
2844 // Make sure we are running with the most recent config.
2845 handleConfigurationChanged(null, null);
2846
2847 if (localLOGV) Slog.v(
2848 TAG, "Handling launch of " + r);
2849
2850 // Initialize before creating the activity
2851 if (!ThreadedRenderer.sRendererDisabled) {
2852 GraphicsEnvironment.earlyInitEGL();
2853 }
2854 WindowManagerGlobal.initialize();
2855 //这里返回了一个Activity,应该就是创建了该Activity,稍等进入看看
2856 Activity a = performLaunchActivity(r, customIntent);
2857
2858 if (a != null) {
2859 r.createdConfig = new Configuration(mConfiguration);
2860 reportSizeConfigurations(r);
2861 Bundle oldState = r.state;
2862 handleResumeActivity(r.token, false, r.isForward,
2863 !r.activity.mFinished && !r.startsNotResumed, r.lastProcessedSeq, reason);
2864
2865 if (!r.activity.mFinished && r.startsNotResumed) {
2866 // The activity manager actually wants this one to start out paused, because it
2867 // needs to be visible but isn't in the foreground. We accomplish this by going
2868 // through the normal startup (because activities expect to go through onResume()
2869 // the first time they run, before their window is displayed), and then pausing it.
2870 // However, in this case we do -not- need to do the full pause cycle (of freezing
2871 // and such) because the activity manager assumes it can just retain the current
2872 // state it has.
2873 performPauseActivityIfNeeded(r, reason);
2874
2875 // We need to keep around the original state, in case we need to be created again.
2876 // But we only do this for pre-Honeycomb apps, which always save their state when
2877 // pausing, so we can not have them save their state when restarting from a paused
2878 // state. For HC and later, we want to (and can) let the state be saved as the
2879 // normal part of stopping the activity.
2880 if (r.isPreHoneycomb()) {
2881 r.state = oldState;
2882 }
2883 }
2884 } else {
2885 // If there was an error, for any reason, tell the activity manager to stop us.
2886 try {
2887 ActivityManager.getService()
2888 .finishActivity(r.token, Activity.RESULT_CANCELED, null,
2889 Activity.DONT_FINISH_TASK_WITH_ACTIVITY);
2890 } catch (RemoteException ex) {
2891 throw ex.rethrowFromSystemServer();
2892 }
2893 }
2894 }
进入 performLaunchActivity(),看看是如何进行创建的
private Activity performLaunchActivity(ActivityClientRecord r, Intent customIntent) {
2645 // System.out.println("##### [" + System.currentTimeMillis() + "] ActivityThread.performLaunchActivity(" + r + ")");
2646 //获取Activity的信息
2647 ActivityInfo aInfo = r.activityInfo;
2648 if (r.packageInfo == null) {
2649 r.packageInfo = getPackageInfo(aInfo.applicationInfo, r.compatInfo,
2650 Context.CONTEXT_INCLUDE_CODE);
2651 }
//从intent中获取启动activity的参数
2652
2653 ComponentName component = r.intent.getComponent();
2654 if (component == null) {
2655 component = r.intent.resolveActivity(
2656 mInitialApplication.getPackageManager());
2657 r.intent.setComponent(component);
2658 }
2659
2660 if (r.activityInfo.targetActivity != null) {
2661 component = new ComponentName(r.activityInfo.packageName,
2662 r.activityInfo.targetActivity);
2663 }
2664 //Activity的集成类是Context,这里获取到Context的实现类ContextImpl
2665 ContextImpl appContext = createBaseContextForActivity(r);
2666 Activity activity = null;
2667 try {
// 获取JAVA的类加载器
2668 java.lang.ClassLoader cl = appContext.getClassLoader();
//将目标activity的类通过类名加载进来并调用newInstance来实例化一个对象,
//其实就是通过Activity的无参构造方法来new一个activity的对象
2669 activity = mInstrumentation.newActivity(
2670 cl, component.getClassName(), r.intent);
2671 StrictMode.incrementExpectedActivityCount(activity.getClass());
2672 r.intent.setExtrasClassLoader(cl);
2673 r.intent.prepareToEnterProcess();
2674 if (r.state != null) {
2675 r.state.setClassLoader(cl);
2676 }
2677 } catch (Exception e) {
2678 if (!mInstrumentation.onException(activity, e)) {
2679 throw new RuntimeException(
2680 "Unable to instantiate activity " + component
2681 + ": " + e.toString(), e);
2682 }
2683 }
2684
2685 try {
2686 Application app = r.packageInfo.makeApplication(false, mInstrumentation);
2687
2688 if (localLOGV) Slog.v(TAG, "Performing launch of " + r);
2689 if (localLOGV) Slog.v(
2690 TAG, r + ": app=" + app
2691 + ", appName=" + app.getPackageName()
2692 + ", pkg=" + r.packageInfo.getPackageName()
2693 + ", comp=" + r.intent.getComponent().toShortString()
2694 + ", dir=" + r.packageInfo.getAppDir());
2695
2696 if (activity != null) {
2697 CharSequence title = r.activityInfo.loadLabel(appContext.getPackageManager());
2698 Configuration config = new Configuration(mCompatConfiguration);
2699 if (r.overrideConfig != null) {
2700 config.updateFrom(r.overrideConfig);
2701 }
2702 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Launching activity "
2703 + r.activityInfo.name + " with config " + config);
2704 Window window = null;
2705 if (r.mPendingRemoveWindow != null && r.mPreserveWindow) {
2706 window = r.mPendingRemoveWindow;
2707 r.mPendingRemoveWindow = null;
2708 r.mPendingRemoveWindowManager = null;
2709 }
2710 appContext.setOuterContext(activity);
//activity调用attach进行初始化数据
2711 activity.attach(appContext, this, getInstrumentation(), r.token,
2712 r.ident, app, r.intent, r.activityInfo, title, r.parent,
2713 r.embeddedID, r.lastNonConfigurationInstances, config,
2714 r.referrer, r.voiceInteractor, window, r.configCallback);
2715
2716 if (customIntent != null) {
2717 activity.mIntent = customIntent;
2718 }
2719 r.lastNonConfigurationInstances = null;
2720 checkAndBlockForNetworkAccess();
2721 activity.mStartedActivity = false;
//获取activity的主题,并设置主题
2722 int theme = r.activityInfo.getThemeResource();
2723 if (theme != 0) {
2724 activity.setTheme(theme);
2725 }
2726
2727 activity.mCalled = false;
//在这里调用了回调onCreate方法,activity就被启动了
2728 if (r.isPersistable()) {
2729 mInstrumentation.callActivityOnCreate(activity, r.state, r.persistentState);
2730 } else {
2731 mInstrumentation.callActivityOnCreate(activity, r.state);
2732 }
2733 if (!activity.mCalled) {
2734 throw new SuperNotCalledException(
2735 "Activity " + r.intent.getComponent().toShortString() +
2736 " did not call through to super.onCreate()");
2737 }
2738 r.activity = activity;
2739 r.stopped = true;
2740 if (!r.activity.mFinished) {
2741 activity.performStart();
2742 r.stopped = false;
2743 }
2744 if (!r.activity.mFinished) {
2745 if (r.isPersistable()) {
2746 if (r.state != null || r.persistentState != null) {
2747 mInstrumentation.callActivityOnRestoreInstanceState(activity, r.state,
2748 r.persistentState);
2749 }
2750 } else if (r.state != null) {
2751 mInstrumentation.callActivityOnRestoreInstanceState(activity, r.state);
2752 }
2753 }
2754 if (!r.activity.mFinished) {
2755 activity.mCalled = false;
2756 if (r.isPersistable()) {
2757 mInstrumentation.callActivityOnPostCreate(activity, r.state,
2758 r.persistentState);
2759 } else {
2760 mInstrumentation.callActivityOnPostCreate(activity, r.state);
2761 }
2762 if (!activity.mCalled) {
2763 throw new SuperNotCalledException(
2764 "Activity " + r.intent.getComponent().toShortString() +
2765 " did not call through to super.onPostCreate()");
2766 }
2767 }
2768 }
2769 r.paused = true;
2770
2771 mActivities.put(r.token, r);
2772
2773 } catch (SuperNotCalledException e) {
2774 throw e;
2775
2776 } catch (Exception e) {
2777 if (!mInstrumentation.onException(activity, e)) {
2778 throw new RuntimeException(
2779 "Unable to start activity " + component
2780 + ": " + e.toString(), e);
2781 }
2782 }
2783
2784 return activity;
2785 }
调用Instrumentation类中callActivityOnCreate方法
public void callActivityOnCreate(Activity activity, Bundle icicle) {
1213 prePerformCreate(activity);
1214 activity.performCreate(icicle);
1215 postPerformCreate(activity);
1216 }
Activity类中performCreate方法
final void performCreate(Bundle icicle) {
7000 performCreate(icicle, null);
7001 }
7002
7003 final void performCreate(Bundle icicle, PersistableBundle persistentState) {
7004 mCanEnterPictureInPicture = true;
7005 restoreHasCurrentPermissionRequest(icicle);
//最终看到了onCreate方法了吧
7006 if (persistentState != null) {
7007 onCreate(icicle, persistentState);
7008 } else {
7009 onCreate(icicle);
7010 }
7011 mActivityTransitionState.readState(icicle);
7012
7013 mVisibleFromClient = !mWindow.getWindowStyle().getBoolean(
7014 com.android.internal.R.styleable.Window_windowNoDisplay, false);
7015 mFragments.dispatchActivityCreated();
7016 mActivityTransitionState.setEnterActivityOptions(this, getActivityOptions());
7017 }
看到了onCreate方法,至此activity的启动流程就完成了,activity的生命周期的各种状态的切换由ApplicationThread内部完成
这个在线看源码还是挺好的在线看Android源码