概述: 在Android系统中,Activity是应用程序的四大组件之一,在开发Android应用时无时无刻都在使用它们。但是它们的启动过程是怎么样的?Activity的什么周期方法到底是怎么被执行?本篇将结合源码(7.0.0_r1)进行分析。
先来看看启动调用的时序图
源码:packages/apps/Launcher3/src/com/android/launcher3/Launcher.java
public class Launcher extends Activity implements View .OnClickListener , OnLongClickListener , LauncherModel .Callbacks ,View .OnTouchListener , PageSwitchListener , LauncherProviderChangeListener { ...省略代码专用... public void onClick (View v) { ...省略代码专用... if (v instanceof Workspace) { if (mWorkspace.isInOverviewMode()) { showWorkspace(true ); } return ; } if (v instanceof CellLayout) { if (mWorkspace.isInOverviewMode()) { showWorkspace(mWorkspace.indexOfChild(v), true ); } } Object tag = v.getTag(); if (tag instanceof ShortcutInfo) { onClickAppShortcut(v); } else if (tag instanceof FolderInfo) { if (v instanceof FolderIcon) { onClickFolderIcon(v); } } else if (v == mAllAppsButton) { onClickAllAppsButton(v); } else if (tag instanceof AppInfo) { startAppShortcutOrInfoActivity(v); } else if (tag instanceof LauncherAppWidgetInfo) { if (v instanceof PendingAppWidgetHostView) { onClickPendingWidget((PendingAppWidgetHostView) v); } } } ...省略代码专用... }
Android
中桌面的应用程序都是由Launcher
启动的,其中Launcher
本身也是一个应用,当应用程序安装完成后都会在桌面创建相应的应用程序图标,点击这个图标,Launcher
就会将其启动起来。桌面其实用了一个RecyclerView
来构建,具体请看AllAppsContainerView
源码。当我们点击图标的时候,则直接执行onClickAppShortcut
方法,来看其代码
源码:packages/apps/Launcher3/src/com/android/launcher3/Launcher.java
protected void onClickAppShortcut (final View v) { ...省略代码专用... final ShortcutInfo shortcut = (ShortcutInfo) tag; ...省略代码专用... if ((v instanceof BubbleTextView) && shortcut.isPromise() && !shortcut.hasStatusFlag(ShortcutInfo.FLAG_INSTALL_SESSION_ACTIVE)) { showBrokenAppInstallDialog( shortcut.getTargetComponent().getPackageName(), new DialogInterface.OnClickListener() { public void onClick (DialogInterface dialog, int id) { startAppShortcutOrInfoActivity(v); } }); return ; } startAppShortcutOrInfoActivity(v); if (mLauncherCallbacks != null ) { mLauncherCallbacks.onClickAppShortcut(v); } }
根据注释可以看到调用了startAppShortcutOrInfoActivity
方法,继续来看
源码:packages/apps/Launcher3/src/com/android/launcher3/Launcher.java
@Thunk void startAppShortcutOrInfoActivity (View v) { ...省略代码专用... boolean success = startActivitySafely(v, intent, tag); mStats.recordLaunch(v, intent, shortcut); ...省略代码专用... }
这里调用的是startActivitySafely
方法。
源码:packages/apps/Launcher3/src/com/android/launcher3/Launcher.java
public boolean startActivitySafely (View v, Intent intent, Object tag) { boolean success = false ; ...省略代码专用... try { success = startActivity(v, intent, tag); } catch (ActivityNotFoundException e) { Toast.makeText(this , R.string.activity_not_found, Toast.LENGTH_SHORT).show(); Log.e(TAG, "Unable to launch. tag=" + tag + " intent=" + intent, e); } return success; }
其内部调用的就是startActivity
方法。
源码:packages/apps/Launcher3/src/com/android/launcher3/Launcher.java
private boolean startActivity (View v, Intent intent, Object tag) { intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); try { ...省略代码专用... if (user == null || user.equals(UserHandleCompat.myUserHandle())) { StrictMode.VmPolicy oldPolicy = StrictMode.getVmPolicy(); try { StrictMode.setVmPolicy(new StrictMode.VmPolicy.Builder().detectAll() .penaltyLog().build()); startActivity(intent, optsBundle); } finally { StrictMode.setVmPolicy(oldPolicy); } } else { launcherApps.startActivityForProfile(intent.getComponent(), user, intent.getSourceBounds(), optsBundle); } return true ; } catch (SecurityException e) { ...省略代码专用... } return false ; }
注释1处可以看出新开的Activity
是在新的任务栈里面。注释2处调用Activity
的startActivity
方法
源码:frameworks/base/core/java/android/app/Activity.java
Override public void startActivity (Intent intent, @Nullable Bundle options) { if (options != null ) { startActivityForResult(intent, -1 , options); } else { startActivityForResult(intent, -1 ); } }
源码:frameworks/base/core/java/android/app/Activity.java
public void startActivityForResult (@RequiresPermission Intent intent, int requestCode, @Nullable Bundle options) { if (mParent == null ) { Instrumentation.ActivityResult ar = mInstrumentation.execStartActivity( this , mMainThread.getApplicationThread(), mToken, this , intent, requestCode, options); ...省略代码专用... } else { ...省略代码专用... } }
mParent
是Activity
类型的成员变量,表示当前Activity
的父类。因为目前根Activity
还没有创建出来,则mParent == null
成立。接着调用Instrumentation
的execStartActivity
方法。execStartActivity
方法的代码如下所示。
源码:frameworks/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; Uri referrer = target != null ? target.onProvideReferrer() : null ; if (referrer != null ) { intent.putExtra(Intent.EXTRA_REFERRER, referrer); } ...省略代码专用... 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
来获取ActivityManageService
(后续简称为AMS)的代理对象,接着调用它的startActivity
方法。
源码:frameworks/base/core/java/android/app/ActivityManagerNative.java
static public IActivityManager getDefault () { return gDefault.get(); }
private static final Singleton<IActivityManager> gDefault = new Singleton<IActivityManager>() { protected IActivityManager create () { IBinder b = ServiceManager.getService("activity" ); if (false ) { Log.v("ActivityManager" , "default service binder = " + b); } IActivityManager am = asInterface(b); if (false ) { Log.v("ActivityManager" , "default service = " + am); } return am; } };
getDefault
方法调用了gDefault
的get
方法,我们接着往下看,gDefault
是一个单例Singleton
。注释1处得到名为”activity”
的Service
代理对象,实质就是ActivityManagerService
的代理对象。接着在注释2处将它封装成ActivityManagerProxy
(以后简称为AMP)类型对象,并将它保存到gDefault
中,此后调用ActivityManagerNative
的getDefault
方法就会直接获得AMS的代理AMP对象。 回到Instrumentation类的execStartActivity方法中,从上面得知就是调用AMP的startActivity,其中AMP是ActivityManagerNative的内部类,代码如下所示。
源码:frameworks/base/core/java/android/app/ActivityManagerNative.java$ActivityManagerProxy
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 { 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 ); } mRemote.transact(START_ACTIVITY_TRANSACTION, data, reply, 0 ); reply.readException(); int result = reply.readInt(); reply.recycle(); data.recycle(); return result; }
首先会将传入的参数写入到Parcel
类型的data
中。在注释1处通过IBinder
对象mRemote
向AMS发送一个START_ACTIVITY_TRANSACTION
类型的进程间通信请求。那么服务端AMS就会从Binder
线程池中读取我们客户端发来的数据,最终会调用ActivityManagerNative
的onTransact
方法中执行,如下所示。
源码:frameworks/base/core/java/android/app/ActivityManagerNative.java
@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 ; int result = startActivity(app, callingPackage, intent, resolvedType, resultTo, resultWho, requestCode, startFlags, profilerInfo, options); reply.writeNoException(); reply.writeInt(result); return true ; } ...省略代码专用... } }
onTransact
中会调用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()); }
AMS的startActivity
方法中直接返回了startActivityAsUser
方法:
源码:frameworks/base/services/core/java/com/android/server/am/ActivityManagerService.java
@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) { enforceNotIsolatedCaller("startActivity" ); userId = mUserController.handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(), userId, false , ALLOW_FULL_ONLY, "startActivity" , null ); return mActivityStarter.startActivityMayWait(caller, -1 , callingPackage, intent, resolvedType, null , null , resultTo, resultWho, requestCode, startFlags, profilerInfo, null , null , bOptions, false , userId, null , null ); }
startActivityAsUser
方法中又返回了mActivityStarter
的startActivityMayWait
方法,代码如下所示。
源码:frameworks/base/services/core/java/com/android/server/am/ActivityStarter.java
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; } }
内部又调用了startActivityLocked
方法,代码如下所示。
源码:frameworks/base/services/core/java/com/android/server/am/ActivityStarter.java
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) { ...省略代码专用... doPendingActivityLaunchesLocked(false ); ...省略代码专用... return err; }
startActivityLocked
函数代码非常多,我们只需要关注doPendingActivityLaunchesLocked
方法,代码如下所示。
源码:frameworks/base/services/core/java/com/android/server/am/ActivityStarter.java
final void doPendingActivityLaunchesLocked (boolean doResume) { while (!mPendingActivityLaunches.isEmpty()) { final PendingActivityLaunch pal = mPendingActivityLaunches.remove(0 ); final boolean resume = doResume && mPendingActivityLaunches.isEmpty(); try { final int result = startActivityUnchecked( pal.r, pal.sourceRecord, null , null , pal.startFlags, resume, null , null ); postStartActivityUncheckedProcessing( pal.r, result, mSupervisor.mFocusedStack.mStackId, mSourceRecord, mTargetStack); } catch (Exception e) { Slog.e(TAG, "Exception during pending activity launch pal=" + pal, e); pal.sendErrorResult(e.getMessage()); } } }
接着又调用startActivityUnchecked
方法:
源码:frameworks/base/services/core/java/com/android/server/am/ActivityStarter.java
private int startActivityUnchecked (final ActivityRecord r, ActivityRecord sourceRecord, IVoiceInteractionSession voiceSession, IVoiceInteractor voiceInteractor, int startFlags, boolean doResume, ActivityOptions options, TaskRecord inTask) { ...省略代码专用... mSupervisor.resumeFocusedStackTopActivityLocked(); ...省略代码专用... return START_SUCCESS; }
startActivityUnchecked
方法中调用了ActivityStackSupervisor
类型的mSupervisor
的resumeFocusedStackTopActivityLocked
方法,如下所示。 源码:frameworks/base/services/core/java/com/android/server/am/ActivityStackSupervisor.java
boolean resumeFocusedStackTopActivityLocked ( ActivityStack targetStack, ActivityRecord target, ActivityOptions targetOptions) { if (targetStack != null && isFocusedStack(targetStack)) { return targetStack.resumeTopActivityUncheckedLocked(target, targetOptions); } final ActivityRecord r = mFocusedStack.topRunningActivityLocked(); if (r == null || r.state != RESUMED) { mFocusedStack.resumeTopActivityUncheckedLocked(null , null ); } return false ; }
在注释1处又调用了ActivityStack
类型mFocusedStack
的resumeTopActivityUncheckedLocked
方法:
源码:frameworks/base/services/core/java/com/android/server/am/ActivityStack.java
boolean resumeTopActivityUncheckedLocked (ActivityRecord prev, ActivityOptions options) { ...省略代码专用... try { ...省略代码专用... result = resumeTopActivityInnerLocked(prev, options); } finally { mStackSupervisor.inResumeTopActivity = false ; } return result; }
紧接着查看ActivityStack
的resumeTopActivityInnerLocked
方法:
源码:frameworks/base/services/core/java/com/android/server/am/ActivityStack.java
private boolean resumeTopActivityInnerLocked (ActivityRecord prev, ActivityOptions options) { ...省略代码专用... final ActivityRecord next = topRunningActivityLocked(); ...省略代码专用... if (next.app != null && next.app.thread != null ) { ...省略代码专用... } else { ...省略代码专用... mStackSupervisor.startSpecificActivityLocked(next, true , true ); } ...省略代码专用... if (DEBUG_STACK) mStackSupervisor.validateTopActivitiesLocked(); return true ; }
resumeTopActivityInnerLocked
方法代码非常多,我们只需要关注调用了ActivityStackSupervisor
类型mStackSupervisor
的startSpecificActivityLocked
方法,代码如下所示。 源码:frameworks/base/services/core/java/com/android/server/am/ActivityStackSupervisor.java
void startSpecificActivityLocked (ActivityRecord r, boolean andResume, boolean checkConfig) { ProcessRecord app = mService.getProcessRecordLocked(r.processName, r.info.applicationInfo.uid, true ); r.task.stack.setLaunchTime(r); if (app != null && app.thread != null ) { try { if ((r.info.flags&ActivityInfo.FLAG_MULTIPROCESS) == 0 || !"android" .equals(r.info.packageName)) { app.addPackage(r.info.packageName, r.info.applicationInfo.versionCode, mService.mProcessStats); } realStartActivityLocked(r, app, andResume, checkConfig); return ; } catch (RemoteException e) { Slog.w(TAG, "Exception when starting activity " + r.intent.getComponent().flattenToShortString(), e); } } mService.startProcessLocked(r.processName, r.info.applicationInfo, true , 0 , "activity" , r.intent.getComponent(), false , false , true ); }
在注释1处如果当前Activity
所在的Application
运行的话,会执行注释2处的代码。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 { ...省略代码专用... 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 ; }
这里的app.thread
指的是IApplicationThread
,它的实现是ActivityThread
的内部类ApplicationThread
,其中ApplicationThread
继承了ApplicationThreadNative
,而ApplicationThreadNative
继承了Binder
并实现了IApplicationThread
接口。在应用程序进程启动时会创建ActivityThread
实例。ActivityThread
作为应用程序进程的核心类,它是如何启动应用程序Activity
的呢?接着往下看。接着查看ApplicationThread
的scheduleLaunchActivity
方法,代码如下所示。
源码:frameworks/base/core/java/android/app/ActivityThread.java
@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(); 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); }
scheduleLaunchActivity
方法会将启动Activity
的参数封装成ActivityClientRecord
,再将ActivityClientRecord
通过sendMessage
方法向应用进程的主线程发送类型为LAUNCH_ACTIVITY
的消息,sendMessage
方法的代码如下所示。
源码:frameworks/base/core/java/android/app/ActivityThread.java
private void sendMessage (int what, Object obj, int arg1, int arg2, boolean async) {...省略代码专用... mH.sendMessage(msg); }
这里mH
指的是H
,它是ActivityThread
的内部类并继承Handler
,H
的代码如下所示。
源码:frameworks/base/core/java/android/app/ActivityThread.java
private class H extends Handler { public static final int LAUNCH_ACTIVITY = 100 ; public static final int PAUSE_ACTIVITY = 101 ; ...省略代码专用... public void handleMessage (Message msg) { if (DEBUG_MESSAGES) Slog.v(TAG, ">>> handling: " + codeToString(msg.what)); 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); handleLaunchActivity(r, null , "LAUNCH_ACTIVITY" ); Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER); } break ; case RELAUNCH_ACTIVITY: { Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, "activityRestart" ); ActivityClientRecord r = (ActivityClientRecord)msg.obj; handleRelaunchActivity(r); Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER); } break ; ...省略代码专用... }}}
查看H
的handleMessage
方法中对LAUNCH_ACTIVITY
的处理,在注释1处将传过来的msg
的成员变量obj
转换为ActivityClientRecord
。 在注释2处通过getPackageInfoNoCheck
方法获得LoadedApk
类型的对象并赋值给ActivityClientRecord
的成员变量packageInfo
。应用程序进程要启动Activity
时需要将该Activity
所属的APK加载进来,而LoadedApk
就是用来描述已加载的APK文件。 在注释3处调用handleLaunchActivity
方法,代码如下所示。
源码:frameworks/base/core/java/android/app/ActivityThread.java
private void handleLaunchActivity (ActivityClientRecord r, Intent customIntent, String reason) { ...省略代码专用... Activity a = performLaunchActivity(r, customIntent); if (a != null ) { r.createdConfig = new Configuration(mConfiguration); reportSizeConfigurations(r); Bundle oldState = r.state; handleResumeActivity(r.token, false , r.isForward, !r.activity.mFinished && !r.startsNotResumed, r.lastProcessedSeq, reason); if (!r.activity.mFinished && r.startsNotResumed) { performPauseActivityIfNeeded(r, reason); if (r.isPreHoneycomb()) { r.state = oldState; } } } else { try { ActivityManagerNative.getDefault() .finishActivity(r.token, Activity.RESULT_CANCELED, null , Activity.DONT_FINISH_TASK_WITH_ACTIVITY); } catch (RemoteException ex) { throw ex.rethrowFromSystemServer(); } } }
注释1处的performLaunchActivity
方法用来启动Activity
,注释2处的代码用来将Activity
的状态置为Resume
。如果该Activity
为null
则会通知ActivityManager
停止启动Activity
。来查看performLaunchActivity
方法做了什么:
源码:frameworks/base/core/java/android/app/ActivityThread.java
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(); ...省略代码专用... Activity activity = null ; try { java.lang.ClassLoader cl = r.packageInfo.getClassLoader(); activity = mInstrumentation.newActivity( cl, component.getClassName(), r.intent); ...省略代码专用... } } catch (Exception e) { ...省略代码专用... } try { Application app = r.packageInfo.makeApplication(false , mInstrumentation); ...省略代码专用... if (activity != null ) { Context appContext = createBaseContextForActivity(r, activity); ...省略代码专用... } 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); ...省略代码专用... if (r.isPersistable()) { mInstrumentation.callActivityOnCreate(activity, r.state, r.persistentState); } else { mInstrumentation.callActivityOnCreate(activity, r.state); } ...省略代码专用... } return activity; }
注释1处用来获取ActivityInfo
,在注释2处获取APK文件的描述类LoadedApk
。注释3处获取要启动的Activity
的ComponentName
类,ComponentName
类中保存了该Activity
的包名和类名。注释4处根据ComponentName
中存储的Activity
类名,用类加载器来创建该Activity
的实例。注释5处用来创建Application
,makeApplication
方法内部会调用Application
的onCreate
方法。注释6处用来创建要启动Activity
的上下文环境。注释7处调用Activity
的attach方法初始化Activity
,attach
方法中会创建Window
对象(PhoneWindow
)并与Activity
自身进行关联。注释8处会调用Instrumentation
的callActivityOnCreate
方法来启动Activity
:
源码:frameworks/base/core/java/android/app/Instrumentation.java
public void callActivityOnCreate (Activity activity, Bundle icicle, PersistableBundle persistentState) { prePerformCreate(activity); activity.performCreate(icicle, persistentState); postPerformCreate(activity); }
注释1处调用了Activity
的performCreate
方法,代码如下所示。
源码:frameworks/base/core/java/android/app/Activity.java
final void performCreate (Bundle icicle) { restoreHasCurrentPermissionRequest(icicle); onCreate(icicle); mActivityTransitionState.readState(icicle); performCreateCommon(); }
performCreate
方法中会调用Activity
的onCreate
方法,这样Activity
就启动了,即应用程序就启动了。