1.概述
基于Android9.0(SDK 28)源码。
关键类:
ActivityThred
ApplicationThread
ActivityManagerService
ProcessRecord 进程信息
ActivityRecord Activity信息
ActivityStack
ActivityStackSupervisor
LoadApk
2.Activity类中流程分析
2.1 Activity->startActivity()
@Override
public void startActivity(Intent intent, @Nullable Bundle options) {
if (options != null) {
startActivityForResult(intent, -1, options);
} else {
//startActivity(Intent):requestCode是-1了
startActivityForResult(intent, -1); //2.2 Activity->startActivityForResult()
}
}
2.2 Activity->startActivityForResult()
//requestCode=-1
public void startActivityForResult(@RequiresPermission Intent intent, int requestCode, Bundle options) {
...
//转调到Instrumentation的execStartActivity()
Instrumentation.ActivityResult ar =
mInstrumentation.execStartActivity(this, mMainThread.getApplicationThread(), mToken,
this, intent, requestCode, options);
...
}
- mMainThread.getApplicationThread():
mMainThread是ActivityThread类型的实例,getApplicationThread获取的是ActivityThread的内部类ApplicationThread类型的实例,ApplicationThread实际上也是IPC调用,对应的AIDL文件是IApplicationThread.aidl。
3 Instrumentation类中流程
Activity->startActivityForResult()方法中转调到了Instrumentation->execStartActivity():
public ActivityResult execStartActivity(Context who, IBinder contextThread, IBinder token, Activity target,
Intent intent, int requestCode, Bundle options) {
IApplicationThread whoThread = (IApplicationThread) contextThread;
...
//result是执行启动后的结果,类似于错误码,标记不同的错误类型
//从这里调用了ActivityManagerService的startActivity(),是ipc调用,ActivityManager.getService()是通过单例模式实现的
int result = ActivityManager.getService().startActivity(whoThread, who.getBasePackageName(), intent,
intent.resolveTypeIfNeeded(who.getContentResolver()),
token, target != null ? target.mEmbeddedID : null,
requestCode, 0, null, options);
//根据AMS启动Activity的result值,进行错误的处理,如果启动失败会抛出各种类型的异常,成功则直接return
checkStartActivityResult(result, intent);
}
public class ActivityManagerService extends IActivityManager.Stub implements Watchdog.Monitor, BatteryStatsImpl.BatteryCallback {
...
}
- ActivityManager.getService().startActivity()这个调用,是将whoThread(ActivityThread.ApplicationThread)接口引用传到了AMS中。
- ActivityManager.getService()实际上获取的是AMS的实例。
4 转到SystemServer进程中:ActivityManagerService->startActivity()
AMS中startActivity()最后会转调到startActivityAsUser():
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, boolean validateIncomingUser) {
...
//这里先转调ActivityStartController进行userId检查
userId = mActivityStartController.checkTargetUser(userId, validateIncomingUser, Binder.getCallingPid(),
Binder.getCallingUid(), "startActivityAsUser");
//又转调到ActivityStarter的execute()方法
return mActivityStartController.obtainStarter(intent, "startActivityAsUser")
.setCaller(caller)
.setCallingPackage(callingPackage)
.setResolvedType(resolvedType)
.setResultTo(resultTo)
.setResultWho(resultWho)
.setRequestCode(requestCode)
.setStartFlags(startFlags)
.setProfilerInfo(profilerInfo)
.setActivityOptions(bOptions)
.setMayWait(userId) //mRequest.mayWait = true;会直接将mayWait标记为true
.execute();
}
2.5 ActivityStarter->execute(),会继续调用到ActivityStarter->startActivityMayWait()方法
- 2.5.1 ActivityStarter->startActivityMayWait()
private 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, SafeActivityOptions options, boolean ignoreTargetSecurity,
int userId, TaskRecord inTask, String reason,
boolean allowPendingRemoteAnimationRegistryLookup) {
...
//转调startActivity()
int res = startActivity(caller, intent, ephemeralIntent, resolvedType, aInfo, rInfo,
voiceSession, voiceInteractor, resultTo, resultWho, requestCode, callingPid,
callingUid, callingPackage, realCallingPid, realCallingUid, startFlags, options,
ignoreTargetSecurity, componentSpecified, outRecord, inTask, reason,
allowPendingRemoteAnimationRegistryLookup);
...
}
- 2.5.2 ActivityStarter->startActivity():
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,
SafeActivityOptions options, boolean ignoreTargetSecurity, boolean componentSpecified,
ActivityRecord[] outActivity, TaskRecord inTask, String reason,
boolean allowPendingRemoteAnimationRegistryLookup) {
mLastStartActivityResult = startActivity(caller, intent, ephemeralIntent, resolvedType,
aInfo, rInfo, voiceSession, voiceInteractor, resultTo, resultWho, requestCode,
callingPid, callingUid, callingPackage, realCallingPid, realCallingUid, startFlags,
options, ignoreTargetSecurity, componentSpecified, mLastStartActivityRecord,
inTask, allowPendingRemoteAnimationRegistryLookup);
return getExternalResult(mLastStartActivityResult);
}
- 2.5.3 ActivityStarter->startActivity():
private int startActivity(IApplicationThread caller, Intent intent, Intent ephemeralIntent,...) {
//这里startActivity()传入的Bundle类型的option参数由ActivityOptions进行管理了
final Bundle verificationBundle = options != null ? options.popAppVerificationBundle() : null;
ProcessRecord callerApp = null;
return startActivity(r, sourceRecord, voiceSession, voiceInteractor, startFlags,
true /* doResume */, checkedOptions, inTask, outActivity);
- 2.5.4 ActivityStarter->startActivity():
private int startActivity(final ActivityRecord r, ActivityRecord sourceRecord,
IVoiceInteractionSession voiceSession, IVoiceInteractor voiceInteractor,
int startFlags, boolean doResume, ActivityOptions options, TaskRecord inTask,
ActivityRecord[] outActivity) {
int result = START_CANCELED;
result = startActivityUnchecked(r, sourceRecord, voiceSession, voiceInteractor, startFlags, doResume, options, inTask, outActivity);
return result;
}
- 2.5.5 ActivityStarter-> startActivityUnchecked():
private int startActivityUnchecked(final ActivityRecord r, ActivityRecord sourceRecord,
IVoiceInteractionSession voiceSession, IVoiceInteractor voiceInteractor,
int startFlags, boolean doResume, ActivityOptions options, TaskRecord inTask,
ActivityRecord[] outActivity) {
if (mStartActivity.resultTo == null && mInTask == null && !mAddingToTask
&& (mLaunchFlags & FLAG_ACTIVITY_NEW_TASK) != 0) {
newTask = true;
result = setTaskFromReuseOrCreateNewTask(taskToAffiliate, topStack);
} else if (mSourceRecord != null) {
result = setTaskFromSourceRecord();
} else if (mInTask != null) {
result = setTaskFromInTask();
} else {
setTaskToCurrentTopOrCreateNewTask();
}
if (mDoResume) {
final ActivityRecord topTaskActivity = mStartActivity.getTask().topRunningActivityLocked();
if (!mTargetStack.isFocusable()
|| (topTaskActivity != null && topTaskActivity.mTaskOverlay
&& mStartActivity != topTaskActivity)) {
mTargetStack.ensureActivitiesVisibleLocked(null, 0, !PRESERVE_WINDOWS);
mService.mWindowManager.executeAppTransition();
} else {
//流程转调到ActivityStackSupervisor类的resumeFocusedStackTopActivity()方法
mSupervisor.resumeFocusedStackTopActivityLocked(mTargetStack, mStartActivity,
mOptions);
}
}
}
- mSupervisor:ActivityStackSupervisor,Activity栈的管理者。
3.ActivityStackSupervisor中的流程
- 3.1 ActivityStackSupervisor::resumeFocusedStackTopActivityLocked():
boolean resumeFocusedStackTopActivityLocked(
ActivityStack targetStack, ActivityRecord target, ActivityOptions targetOptions) {
//获取要启动Activity所在栈的栈顶的不是处于停止状态的Activiy的ActivityRecord
final ActivityRecord r = mFocusedStack.topRunningActivityLocked();
if (r == null || !r.isState(RESUMED)) {
mFocusedStack.resumeTopActivityUncheckedLocked(null, null);
} else if (r.isState(RESUMED)) {
// Kick off any lingering app transitions form the MoveTaskToFront operation.
mFocusedStack.executeAppTransition(targetOptions);
}
return false;
}
4.ActivityStack中的流程
4.1ActivityStack->resumeTopActivityUncheckedLocked()
boolean resumeTopActivityUncheckedLocked(ActivityRecord prev, ActivityOptions options) {
...
boolean result = false;
result = resumeTopActivityInnerLocked(prev, options);
return result;
}
4.2ActivityStack->resumeTopActivityInnerLocked()
private boolean resumeTopActivityInnerLocked(ActivityRecord prev, ActivityOptions options) {
final ActivityRecord next = topRunningActivityLocked(true /* focusableOnly */);
if (next.app != null && next.app.thread != null) {
mStackSupervisor.startSpecificActivityLocked(next, true, true);
}
}
4.3 ActivityStackSupervisor->startSpecificActivityLocked()
void startSpecificActivityLocked(ActivityRecord r, boolean andResume, boolean checkConfig) {
//用进程名拿到ProcessRecord实例
ProcessRecord app = mService.getProcessRecordLocked(r.processName, r.info.applicationInfo.uid, true);
if (app != null && app.thread != null) {
realStartActivityLocked(r, app, andResume, checkConfig);
}
}
4.4 ActivityStackSupervisor->realStartActivityLocked()
final boolean realStartActivityLocked(ActivityRecord r, ProcessRecord app, boolean andResume,
boolean checkConfig) throws RemoteException {
final TaskRecord task = r.getTask();
final ActivityStack stack = task.getStack();
// 创建一个启动Activity的事务,并且将applicationThread传给ClienTransaction类中
final ClientTransaction clientTransaction = ClientTransaction.obtain(app.thread, r.appToken);
clientTransaction.addCallback(LaunchActivityItem.obtain(new Intent(r.intent),
System.identityHashCode(r), r.info,
mergedConfiguration.getGlobalConfiguration(),
mergedConfiguration.getOverrideConfiguration(), r.compat,
r.launchedFromPackage, task.voiceInteractor, app.repProcState,
r.icicle, r.persistentState, results, newIntents,
mService.isNextTransitionForward(), profilerInfo));
final ActivityLifecycleItem lifecycleItem;
if (andResume) {
lifecycleItem = ResumeActivityItem.obtain(mService.isNextTransitionForward());
} else {
lifecycleItem = PauseActivityItem.obtain();
}
clientTransaction.setLifecycleStateRequest(lifecycleItem);
//1.以事务的形式转发
mService.getLifecycleManager().scheduleTransaction(clientTransaction);
}
- 1.这里的mService就是AMS实例,mService.getLifecycleManager()获取的mLifecycleManager是在ActivityManagerService的构造函数中new出来的
4.5 ClientLifecycleManager->scheduleTransaction()
//ClientLifecycleManager::scheduleTransaction(),ClientTransaction实现了Parcelable接口,所以支持跨进程传输
void scheduleTransaction(ClientTransaction transaction) throws RemoteException {
final IApplicationThread client = transaction.getClient();
//ClinetTransaction会直接调用IApplicationThread的scheduleTransaction(ClinetTrasaction),
//IApplicationThread的实现类是ActivityThread的内部类ApplicationThread
transaction.schedule();
if (!(client instanceof Binder)) {
transaction.recycle();
}
}
- ClientTransaction
//ActivityStackSupervisor->realStartActivityLocked()中: ClientTransaction.obtain(app.thread, r.appToken)的app.thread对象
private IApplicationThread mClient;
public IApplicationThread getClient() {
return mClient;
}
public void schedule() throws RemoteException {
mClient.scheduleTransaction(this);
}
ApplicationThread->scheduleTransaction()
@Override
public void scheduleTransaction(ClientTransaction transaction) throws RemoteException {
//ActivityThread中并没有scheduleTransaction()方法实现代码,
//其实是调用了父类ClientTransactionHandler::scheduleTransaction()方法
ActivityThread.this.scheduleTransaction(transaction);
}
ClientTransactionHandler::scheduleTransaction()方法
//ActivityThread是继承自ClientTransactionHandler
class ActivityThread extends ClientTransactionHandler {}
void scheduleTransaction(ClientTransaction transaction) {
transaction.preExecute(this);
//将事务发到H(Handler)了
sendMessage(ActivityThread.H.EXECUTE_TRANSACTION, transaction);
}
//H::handleMessgae()
case EXECUTE_TRANSACTION:
final ClientTransaction transaction = (ClientTransaction) msg.obj;
//执行了TransactionExecutor的execute方法,会执行一个executeCallbacks(),
//然后调用cycleToPath(),最终会调用到performLifecycleSequence()
mTransactionExecutor.execute(transaction);
if (isSystem()) {
transaction.recycle();
}
break;
}
TransactionExecutor::execute()->executeLifecycleState()->cycleToPath()->performLifecycleSequence()
//performLifecycleSequence(),通过TransactionHandler就可以回调到ActivityThread的各种生命周期方法了
private void performLifecycleSequence(ActivityClientRecord r, IntArray path) {
final int size = path.size();
for (int i = 0, state; i < size; i++) {
state = path.get(i);
log("Transitioning to state: " + state);
switch (state) {
case ON_CREATE:
//调用ActivityThread的handleLaunchActivity,会进一步调用创建Activity实例,回调Activity的onCreate方法等
mTransactionHandler.handleLaunchActivity(r, mPendingActions,null);
break;
case ON_START:
//onStart()
mTransactionHandler.handleStartActivity(r, mPendingActions);
break;
case ON_RESUME:
//onResume()
mTransactionHandler.handleResumeActivity(r.token, false ,r.isForward, "LIFECYCLER_RESUME_ACTIVITY");
break;
case ON_PAUSE:
//onPause()
mTransactionHandler.handlePauseActivity(r.token, false , false , 0 ,
mPendingActions, "LIFECYCLER_PAUSE_ACTIVITY");
break;
case ON_STOP:
//onStop()
mTransactionHandler.handleStopActivity(r.token, false,
0, mPendingActions, false ,"LIFECYCLER_STOP_ACTIVITY");
break;
case ON_DESTROY:
//onDestroy()
mTransactionHandler.handleDestroyActivity(r.token, false ,
0, false ,"performLifecycleSequence. cycling to:" + path.get(size - 1));
break;
case ON_RESTART:
//onRestart()
mTransactionHandler.performRestartActivity(r.token, false );
break;
default:
throw new IllegalArgumentException("Unexpected lifecycle state: " + state);
}
}
从上述代码可以看出,ClientTrasactionHandler最后通过TransactionExecutor真正发起Activity的各种生命周期方法的调用,如果在创建Activity实例时,Application实例未被创建,就会先创建Application实例,二者都是通过类全限定名和ClassLoader完成实例的创建。
ActivityThread中的启动流程
- Activity启动的核心方法: ActivityThread::performLaunchActivity()
//android.app.ActivityThread#performLaunchActivity
private Activity performLaunchActivity(ActivityClientRecord r, Intent customIntent) {
//这个Context是Activity级别的
ContextImpl appContext = createBaseContextForActivity(r);
//1.使用Instrumentation和ClassLoader采用反射方式创建Activity实例
Activity activity = null;
java.lang.ClassLoader cl = appContext.getClassLoader();
activity = mInstrumentation.newActivity(cl, component.getClassName(), r.intent);
r.intent.setExtrasClassLoader(cl);
r.intent.prepareToEnterProcess();
if (r.state != null) {
r.state.setClassLoader(cl);
//2.获取Application实例,如果为null同样会同样使用反射和classsLoader创建实例,是使用Instrumentation创建的,具体实现代码在:android.app.LoadedApk#makeApplication()
Application app = r.packageInfo.makeApplication(false, mInstrumentation);
...
//3.初始化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, r.configCallback);
//4.Activity,Application都创建完成了,转调Activity的onCreate()方法
if (r.isPersistable()) {
mInstrumentation.callActivityOnCreate(activity, r.state, r.persistentState);
} else {
mInstrumentation.callActivityOnCreate(activity, r.state);
}
}
ContextImpl的创建时机,是怎么和Activity关联起来的?Activity重写的getSystemService()方法最终中间是由ContextImpl转调的,但是没有看大ContextImpl是怎么传到Activity内的。
//android.app.ActivityThread#performLaunchActivity()中有一段代码是这样:
private Activity performLaunchActivity(ActivityClientRecord r, Intent customIntent) {
ContextImpl appContext = createBaseContextForActivity(r);
...
//这里将创建的ContextImpl实例传给了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, r.configCallback);
}
Activity对象的创建过程
在ActivityThread::performLaunchActivity()中,调用了Instrumentation#newActivity()方法,这个就是开始创建Activity实例的开始。
//android.app.Instrumentation#newActivity(java.lang.ClassLoader, java.lang.String, android.content.Intent)
public Activity newActivity(ClassLoader cl, String className,
Intent intent)
throws InstantiationException, IllegalAccessException,
ClassNotFoundException {
String pkg = intent != null && intent.getComponent() != null
? intent.getComponent().getPackageName() : null;
return getFactory(pkg).instantiateActivity(cl, className, intent);
}
AppComponentFactory->instantiateActivity:直接通过反射创建Activity对象
public @NonNull Activity instantiateActivity(@NonNull ClassLoader cl, @NonNull String className,
@Nullable Intent intent)
throws InstantiationException, IllegalAccessException, ClassNotFoundException {
return (Activity) cl.loadClass(className).newInstance();
}
Application对象的创建过程:LoadApk->makeApplication()
public Application makeApplication(boolean forceDefaultAppClass, Instrumentation instrumentation) {
if (mApplication != null) {
return mApplication;
}
Application app = null;
String appClass = mApplicationInfo.className;
//如果className为null就默认为android.app.Application
if (forceDefaultAppClass || (appClass == null)) {
appClass = "android.app.Application";
}
java.lang.ClassLoader cl = getClassLoader();
if (!mPackageName.equals("android")) {
initializeJavaContextClassLoader(); //检查创建PathClassLoader对象
}
ContextImpl appContext = ContextImpl.createAppContext(mActivityThread, this);
app = mActivityThread.mInstrumentation.newApplication(
cl, appClass, appContext);
appContext.setOuterContext(app);
}
参考文献
[1]http://gityuan.com/2016/03/12/start-activity/
[2]Android开发艺术探索,任玉刚
[3]Android进阶解密,刘望舒