一,写在前面
Activity是Android四大组件之一,用于直接跟用户进行交互,本篇文章将介绍Activity的启动流程。用户启动Activity的方式大致有两种:一种是在桌面点击应用程序的图标,进入应用程序的主界面;另一种是在应用程序中,进入一个新的Activity。前者,桌面其实是系统应用launcher的界面,点击应用程序图标,会进行应用程序的主界面,实质是从一个应用的Activity进入另一个应用Activity。
因此,不管是从桌面进入应用主界面,还是在应用里进入一个新的Activity,最终都会调用Activity$startActivity方法。
值得一提的是,Android 5.0,7.0等版本中启动Activity的源码有点小差异,版本的升级只是对代码做了一些封装,最终都会把启动Activity的任务交给ApplicationThread来处理。
二,Activity工作流程的前半部分析
查看Activity$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);
}
}
查看Activity$startActivityForResult源码:
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);
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);
}
}
}
第5行,调用了方法Instrumentation$execStartActivity,因为mParent为null。
第6行,mMainThread是一个ActivityThread对象,该对象初始化在当前Activity的attach方法中。
attach方法是在启动Activity之前被调用,本篇文章后面会给出解释。attach方法主要是注册一些接口,给一些变量初始化值,其中就创建了PhoneWindow的实例,为创建WindowManagerImpl对象做准备。通过WindowManager可以添加,删除,更新窗口,从代码角度来说 ,增加,删除,更新操作的是View。
前面提到mMainThread是一个ActivityThread对象,mMainThread.getApplicationThread()返回的是一个ApplicationThread对象,ApplicationThread是ActivityThread的内部类。
查看ApplicationThread源码如下:
public final class ActivityThread {
final ApplicationThread mAppThread = new ApplicationThread();
//...code
private class ApplicationThread extends IApplicationThread.Stub {
//...code
}
}
回到Activity$startActivityForResult方法,第5行,调用了方法Instrumentation$execStartActivity。
查看Instrumentation$execStartActivity的源码:
public ActivityResult execStartActivity(
Context who, IBinder contextThread, IBinder token, Activity target,
Intent intent, int requestCode, Bundle options) {
IApplicationThread whoThread = (IApplicationThread) contextThread;
try {
intent.migrateExtraStreamToClipData();
intent.prepareToLeaveProcess(who);
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源码:
/**
* @hide
*/
public static IActivityManager getService() {
return IActivityManagerSingleton.get();
}
//继续查看
private static final Singleton<IActivityManager> IActivityManagerSingleton =
new Singleton<IActivityManager>() {
@Override
protected IActivityManager create() {
final IBinder b = ServiceManager.getService(Context.ACTIVITY_SERVICE);
final IActivityManager am = IActivityManager.Stub.asInterface(b);
return am;
}
};
//...code
}
public abstract class Singleton<T> {
private T mInstance;
protected abstract T create();
public final T get() {
synchronized (this) {
if (mInstance == null) {
mInstance = create();
}
return mInstance;
}
}
}
继续查看create方法的具体实现,IBinder b = ServiceManager.getService(Context.ACTIVITY_SERVICE)获取一个关联了系统服务ActivityManagerService的Binder对象;IActivityManager.Stub.asInterface(b)返回一个IActivityManager的代理对象,基于Binder机制,通过调用代理对象的方法,使得系统服务ActivityManagerService对应的方法被调用。可以猜测ActivityManagerService肯定继承了IActivityManager.Stub,事实也确实如此。
ActivityManagerService源码如下:
public class ActivityManagerService extends IActivityManager.Stub
implements Watchdog.Monitor, BatteryStatsImpl.BatteryCallback {
//...code
}
三,启动Activity的操作交给ActivityManagerService处理
查看 ActivityManagerService$startActivity源码:
@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) {
enforceNotIsolatedCaller("startActivity");
userId = mUserController.handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(),
userId, false, ALLOW_FULL_ONLY, "startActivity", null);
// TODO: Switch to user app stacks here.
return mActivityStarter.startActivityMayWait(caller, -1, callingPackage, intent,
resolvedType, null, null, resultTo, resultWho, requestCode, startFlags,
profilerInfo, null, null, bOptions, false, userId, null, null,
"startActivityAsUser");
}
查看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, WaitResult outResult,
Configuration globalConfig, Bundle bOptions, boolean ignoreTargetSecurity, int userId,
IActivityContainer iContainer, TaskRecord inTask, String reason) {
//...code
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, reason);
//...code
}
//继续查看
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, String reason) {
//...code
mLastStartActivityResult = startActivity(caller, intent, ephemeralIntent, resolvedType,
aInfo, rInfo, voiceSession, voiceInteractor, resultTo, resultWho, requestCode,
callingPid, callingUid, callingPackage, realCallingPid, realCallingUid, startFlags,
options, ignoreTargetSecurity, componentSpecified, mLastStartActivityRecord,
container, inTask);
//...code
}
//继续查看
private int startActivity(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) {
//...code
doPendingActivityLaunchesLocked(false);
//...code
}
//继续查看
final void doPendingActivityLaunchesLocked(boolean doResume) {
//...code
startActivity(pal.r, pal.sourceRecord, null, null, pal.startFlags, resume, null,
null, null /*outRecords*/);
//...code
}
//继续查看
private int startActivity(final ActivityRecord r, ActivityRecord sourceRecord,
IVoiceInteractionSession voiceSession, IVoiceInteractor voiceInteractor,
int startFlags, boolean doResume, ActivityOptions options, TaskRecord inTask,
ActivityRecord[] outActivity) {
//...code
result = startActivityUnchecked(r, sourceRecord, voiceSession, voiceInteractor,
startFlags, doResume, options, inTask, outActivity);
//...code
}
//继续查看
// Note: This method should only be called from {@link startActivity}.
private int startActivityUnchecked(final ActivityRecord r, ActivityRecord sourceRecord,
IVoiceInteractionSession voiceSession, IVoiceInteractor voiceInteractor,
int startFlags, boolean doResume, ActivityOptions options, TaskRecord inTask,
ActivityRecord[] outActivity) {
//...code
mSupervisor.resumeFocusedStackTopActivityLocked();
//...code
}
查看ActivityStackSupervisor源码如下:
boolean resumeFocusedStackTopActivityLocked() {
return resumeFocusedStackTopActivityLocked(null, null, null);
}
//继续查看
boolean resumeFocusedStackTopActivityLocked(
ActivityStack targetStack, ActivityRecord target, ActivityOptions targetOptions) {
//...code
mFocusedStack.resumeTopActivityUncheckedLocked(null, null);
//...code
}
mFocusedStack是一个ActivityStack对象;
ActivityStack源码如下:
boolean resumeTopActivityUncheckedLocked(ActivityRecord prev, ActivityOptions options) {
if (mStackSupervisor.inResumeTopActivity) {
//...code
result = resumeTopActivityInnerLocked(prev, options);
//...code
}
//继续查看
private boolean resumeTopActivityInnerLocked(ActivityRecord prev, ActivityOptions options) {
//...code
mStackSupervisor.startSpecificActivityLocked(next, true, true);
//...code
}
查看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
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
}
前面介绍ApplicationThread继承了IApplicationThread.Stub,并提出ApplicationThread重写接口IApplicationThread的抽象方法在哪里被调用。有意思的是,app.thread调用scheduleLaunchActivity方法,通过Binder机制,会使ApplicationThread$scheduleLaunchActivity方法被调用。
于是,基于Binder机制,实现了一次进程间的通信,将启动Activity的操作交给了ApplicationThread类。
四,启动Activity的操作,交给ApplicationThread来处理
查看ApplicationThread$scheduleLaunchActivity方法源码如下:
@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);
}
第34行,调用ActivityThread$sendMessage方法,查看其源码如下:
private void sendMessage(int what, Object obj) {
sendMessage(what, obj, 0, 0, false);
}
//继续查看
private void sendMessage(int what, Object obj, int arg1, int arg2, boolean async) {
if (DEBUG_MESSAGES) Slog.v(
TAG, "SCHEDULE " + what + " " + mH.codeToString(what)
+ ": " + arg1 + " / " + obj);
Message msg = Message.obtain();
msg.what = what;
msg.obj = obj;
msg.arg1 = arg1;
msg.arg2 = arg2;
if (async) {
msg.setAsynchronous(true);
}
mH.sendMessage(msg);
}
查看H$handleMessage源码如下:
private class H extends Handler {
//...code
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;
//...code
}
第10行,调用ActivityThread$getPackageInfoNoCheck方法,返回一个LoadedApk对象,并将该对象封装到ActivityClientRecord的packgeInfo字段中。
第11行,调用ActivityThread$handleLaunchActivity方法启动Activity;
查看ActivityThread$handleLaunchActivity源码如下:
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);
//...
} else {
// If there was an error, for any reason, tell the activity manager to stop us.
try {
ActivityManager.getService()
.finishActivity(r.token, Activity.RESULT_CANCELED, null,
Activity.DONT_FINISH_TASK_WITH_ACTIVITY);
} catch (RemoteException ex) {
throw ex.rethrowFromSystemServer();
}
}
}
第11行,若a不为空,则调用handleResumeActivity方法,内部会调用Activity$onResume方法。具体的代码流程还是比较好跟的,由于不是本篇的重点,有兴趣的哥们可以自己去研究。
第16行,当a为空,也就是创建Activity的实例出错了,走else语句。ActivityManager.getService()前面已经分析过了,返回IActivityManager的代理对象,调用该代理对象的方法,会向系统服务ActivityManagerService发送请求,基于Binder机制,最终会调用ActivityManagerService$finishActivity方法。
也就是说,当创建Activity实例出错后,停止启动Activity的具体操作交给ActivityManagerService来处理。
回到启动Activity的流程,查看ActivityThread$performLaunchActivity源码如下:
private Activity performLaunchActivity(ActivityClientRecord r, Intent customIntent) {
// System.out.println("##### [" + System.currentTimeMillis() + "] ActivityThread.performLaunchActivity(" + r + ")");
ActivityInfo aInfo = r.activityInfo;
if (r.packageInfo == null) {
r.packageInfo = getPackageInfo(aInfo.applicationInfo, r.compatInfo,
Context.CONTEXT_INCLUDE_CODE);
}
ComponentName component = r.intent.getComponent();
if (component == null) {
component = r.intent.resolveActivity(
mInitialApplication.getPackageManager());
r.intent.setComponent(component);
}
if (r.activityInfo.targetActivity != null) {
component = new ComponentName(r.activityInfo.packageName,
r.activityInfo.targetActivity);
}
ContextImpl appContext = createBaseContextForActivity(r);
Activity activity = null;
//...code
java.lang.ClassLoader cl = appContext.getClassLoader();
if (appContext.getApplicationContext() instanceof Application) {
activity = ((Application) appContext.getApplicationContext())
.instantiateActivity(cl, component.getClassName(), r.intent);
}
if (activity == null) {
activity = mInstrumentation.newActivity(
cl, component.getClassName(), r.intent);
}
//...code
Application app = r.packageInfo.makeApplication(false, mInstrumentation);
//...code
if (activity != null) {
//...code
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);
//...code
mInstrumentation.callActivityOnCreate(activity, r.state);
//...code
}
return activity;
}
1,获取要启动的Activity的ComponentName对象:里面包含了包名,类名相关的信息;
2,创建Activity的上下文环境:即创建了ContextImpl对象;
3,创建Activity的实例:调用Instrumentation$newActivity方法,并使用类加载器创建Activity对象;
4,创建Application对象;
5,调用Activity$attach方法:初始化Activity类里的一些数据;
6,启动Activity:调用Instrumentation$callActivityOnCreate方法;
分析ActivityThread$performLaunchActivity方法:
步骤2,创建了Activity的上下文环境,ContextImpl是抽象类Context的实现类,有关Context的操作的具体实现,大多数由ContextImpl完成。
查看ActivityThread$createBaseContextForActivity源码如下:
private ContextImpl createBaseContextForActivity(ActivityClientRecord r) {
//...code
ContextImpl appContext = ContextImpl.createActivityContext(
this, r.packageInfo, r.activityInfo, r.token, displayId, r.overrideConfig);
//...code
return appContext;
}
static ContextImpl createActivityContext(ActivityThread mainThread,
LoadedApk packageInfo, ActivityInfo activityInfo, IBinder activityToken, int displayId,
Configuration overrideConfiguration) {
//...code
ContextImpl context = new ContextImpl(null, mainThread, packageInfo, activityInfo.splitName,
activityToken, null, 0, classLoader);
//...code
}
步骤3,创建了一个Activity的实例。
查看Instrumentation$newActivity源码如下:
public Activity newActivity(ClassLoader cl, String className,
Intent intent)
throws InstantiationException, IllegalAccessException,
ClassNotFoundException {
return (Activity)cl.loadClass(className).newInstance();
}
通过ClassLoader创建Activity的实例。
步骤4,创建了Application对象,具体分析往下看呗~
查看LoadedApk$makeApplication方法源码如下:
public Application makeApplication(boolean forceDefaultAppClass,
Instrumentation instrumentation) {
if (mApplication != null) {
return mApplication;
}
Application app = null;
//...
app = mActivityThread.mInstrumentation.newApplication(
cl, appClass, appContext);
//...
mApplication = app;
instrumentation.callApplicationOnCreate(app);
//...
return app;
}
第3行,当mApplication不为null时,也就是Application对象已经存在时,直接返回mApplication。很显然Application是一个单例对象,一个应用程序中只存在一个Application对象。
第11行,当应用程序内存中没有Application对象时,创建一个Application对象。跟Activity一样,都是通过类加载器ClassLoader来创建实例。具体代码就不再展示,有兴趣哥们可以去验证。
第16行,将Application对象app赋给字段mApplication。
第18行,调用Application的onCreate方法。
查看Instrumentation$callApplicationOnCreate方法源码:
public void callApplicationOnCreate(Application app) {
app.onCreate();
}
步骤5,调用Activity$attach方法初始化数据。
查看Activity$attach方法源码:
final void attach(Context context, ActivityThread aThread,
Instrumentation instr, IBinder token, int ident,
Application application, Intent intent, ActivityInfo info,
CharSequence title, Activity parent, String id,
NonConfigurationInstances lastNonConfigurationInstances,
Configuration config, String referrer, IVoiceInteractor voiceInteractor,
Window window) {
attachBaseContext(context);
mFragments.attachHost(null /*parent*/);
mWindow = new PhoneWindow(this, window);
mWindow.setWindowControllerCallback(this);
mWindow.setCallback(this);
mWindow.setOnWindowDismissedCallback(this);
mWindow.getLayoutInflater().setPrivateFactory(this);
if (info.softInputMode != WindowManager.LayoutParams.SOFT_INPUT_STATE_UNSPECIFIED) {
mWindow.setSoftInputMode(info.softInputMode);
}
if (info.uiOptions != 0) {
mWindow.setUiOptions(info.uiOptions);
}
mUiThread = Thread.currentThread();
mMainThread = aThread;
mInstrumentation = instr;
mToken = token;
mIdent = ident;
mApplication = application;
mIntent = intent;
mReferrer = referrer;
mComponent = intent.getComponent();
mActivityInfo = info;
mTitle = title;
mParent = parent;
mEmbeddedID = id;
mLastNonConfigurationInstances = lastNonConfigurationInstances;
if (voiceInteractor != null) {
if (lastNonConfigurationInstances != null) {
mVoiceInteractor = lastNonConfigurationInstances.voiceInteractor;
} else {
mVoiceInteractor = new VoiceInteractor(voiceInteractor, this, this,
Looper.myLooper());
}
}
mWindow.setWindowManager(
(WindowManager)context.getSystemService(Context.WINDOW_SERVICE),
mToken, mComponent.flattenToString(),
(info.flags & ActivityInfo.FLAG_HARDWARE_ACCELERATED) != 0);
if (mParent != null) {
mWindow.setContainer(mParent.getWindow());
}
mWindowManager = mWindow.getWindowManager();
mCurrentConfig = config;
}
第12行,创建了窗口对象PhoneWindow;
第13~15行,给窗口对象注册监听接口;
第23~37行,初始化一些变量的值;
第47行,通过窗口Window创建WindowManagerImpl的实例;
第54行,将47行创建的WindowManagerImpl的实例,设置给变量mWindowManager;
步骤6,调用Instrumentation$callActivityOnCreate方法启动Activity。
查看Instrumentation$callActivityOnCreate源码:
public void callActivityOnCreate(Activity activity, Bundle icicle) {
prePerformCreate(activity);
activity.performCreate(icicle);
postPerformCreate(activity);
}
查看Activity$performCreate源码如下:
final void performCreate(Bundle icicle) {
restoreHasCurrentPermissionRequest(icicle);
onCreate(icicle);
mActivityTransitionState.readState(icicle);
performCreateCommon();
}
到这里,Activity的启动流程就分析完毕了^_^