创建Application
Android中有一个ActivityThread类,这个类代表应用程序的主线程;Android在打开APP时会首先调用ActivityThread中的main方法,也就是APP进程的启动点;
public static void main(String[] args) {
...
Looper.prepareMainLooper();//1
// Find the value for {@link #PROC_START_SEQ_IDENT} if provided on the command line.
// It will be in the format "seq=114"
long startSeq = 0;
if (args != null) {
for (int i = args.length - 1; i >= 0; --i) {
if (args[i] != null && args[i].startsWith(PROC_START_SEQ_IDENT)) {
startSeq = Long.parseLong(
args[i].substring(PROC_START_SEQ_IDENT.length()));
}
}
}
ActivityThread thread = new ActivityThread();//2
thread.attach(false, startSeq);//3
...
Looper.loop();//4
throw new RuntimeException("Main thread loop unexpectedly exited");
}
在main方法中1和4是与启动Handler有关,这里不再赘述;2处创建了ActivityThread,紧接着3处调用了attach方法,意为连接,具体连接什么?我们分析下attach方法;
@UnsupportedAppUsage
private void attach(boolean system, long startSeq) {
...
if (!system) {
...
final IActivityManager mgr = ActivityManager.getService();//1
try {
mgr.attachApplication(mAppThread, startSeq);//2
} catch (RemoteException ex) {
throw ex.rethrowFromSystemServer();
}
...
} else {
...
}
...
}
在attach方法中,在注释1处,通过AIDL获取了AMS的代理对象IActivityManager ,实现了应用进程和系统进程通信;紧接着在注释2处调用了IActivityManager 的attachApplication方法,即跨进程调用了AMS的attachApplication方法;这里的意思是把Application与AMS连接起来,也就是把APP绑定到系统应用,具体怎么绑定的呢?在ActivityManagerService类中找到attachApplication方法,继续分析;
@Override
public final void attachApplication(IApplicationThread thread, long startSeq) {
if (thread == null) {
throw new SecurityException("Invalid application interface");
}
synchronized (this) {
int callingPid = Binder.getCallingPid();//1
final int callingUid = Binder.getCallingUid();//2
final long origId = Binder.clearCallingIdentity();
attachApplicationLocked(thread, callingPid, callingUid, startSeq);//3
Binder.restoreCallingIdentity(origId);
}
}
在注释1和2处系统分别给应用分配了pid和uid,在注释3处调用了叫attachApplicationLocked的方法,传入了pid和uid,同时也传入了ActivityThread的代理类IApplicationThread,继续往下看看attachApplicationLocked方法中做了什么?
@GuardedBy("this")
private boolean attachApplicationLocked(@NonNull IApplicationThread thread,
int pid, int callingUid, long startSeq) {
ProcessRecord app; //1
long startTime = SystemClock.uptimeMillis();
if (pid != MY_PID && pid >= 0) {
synchronized (mPidsSelfLocked) {
app = mPidsSelfLocked.get(pid); //2
}
}
...
if (app.instr != null) { //当前进程是否正在活动
thread.bindApplication(processName, appInfo, providers, app.instr.mClass,
profilerInfo, app.instr.mArguments, app.instr.mWatcher, app.instr.mUiAutomationConnection,
testMode, mBinderTransactionTrackingEnabled, enableTrackAllocation,
isRestrictedBackupMode || !normalMode, app.persistent, new Configuration(getGlobalConfiguration()),
app.compat, getCommonServicesLocked(app.isolated), mCoreSettingsObserver.getCoreSettingsLocked(),
buildSerial, isAutofillCompatEnabled); //3
} else {
//Application 绑定到当前线程
thread.bindApplication(processName, appInfo, providers, null, profilerInfo,
null, null, null, testMode, mBinderTransactionTrackingEnabled,
enableTrackAllocation, isRestrictedBackupMode || !normalMode, app.persistent,
new Configuration(getGlobalConfiguration()), app.compat, getCommonServicesLocked(app.isolated),
mCoreSettingsObserver.getCoreSettingsLocked(), buildSerial, isAutofillCompatEnabled); //4
}
...
//检测最可见的Activity是否在运行进程中等待,如果再则创建Activity
if (mStackSupervisor.attachApplicationLocked(app)) { //5
didSomething = true;
}
...
}
注释1处的ProcessRecord是个进程记录类,小伙伴们可以把这个类理解成为一个javabean,用来保存当前进程相关的一些信息(如pid、uip、ApplicationInfo等),在注释2中,根据pid获取到了这个类。
注释3和注释4都是绑定Application,通过AIDL调用了ActivityThread中的bindApplication方法,在这里可以看到,在AMS中系统只是给Application提供了基本信息,并没有创建Application,由此可以猜测Application创建是在ActivityThread中完成的,具体是不是这样呢,我们看看ActivityThread类的bindApplication方法
@Override
public final void bindApplication(String processName, ApplicationInfo appInfo,
ProviderInfoList providerList, ComponentName instrumentationName,
ProfilerInfo profilerInfo, Bundle instrumentationArgs,
IInstrumentationWatcher instrumentationWatcher,
IUiAutomationConnection instrumentationUiConnection, int debugMode,
boolean enableBinderTracking, boolean trackAllocation,
boolean isRestrictedBackupMode, boolean persistent, Configuration config,
CompatibilityInfo compatInfo, Map services, Bundle coreSettings,
String buildSerial, AutofillOptions autofillOptions,
ContentCaptureOptions contentCaptureOptions, long[] disabledCompatChanges) {
setCoreSettings(coreSettings);
AppBindData data = new AppBindData();
data.processName = processName;
data.appInfo = appInfo;
data.providers = providerList.getList();
data.instrumentationName = instrumentationName;
data.instrumentationArgs = instrumentationArgs;
data.instrumentationWatcher = instrumentationWatcher;
data.instrumentationUiAutomationConnection = instrumentationUiConnection;
data.debugMode = debugMode;
data.enableBinderTracking = enableBinderTracking;
data.trackAllocation = trackAllocation;
data.restrictedBackupMode = isRestrictedBackupMode;
data.persistent = persistent;
data.config = config;
data.compatInfo = compatInfo;
data.initProfilerInfo = profilerInfo;
data.buildSerial = buildSerial;
data.autofillOptions = autofillOptions;
data.contentCaptureOptions = contentCaptureOptions;
data.disabledCompatChanges = disabledCompatChanges;
sendMessage(H.BIND_APPLICATION, data);
}
bindApplication方法中把携带的参数封装成一个AppBindData对象data,最后用handler发送消息,并携带AppBindData数据;H是ActivityThread中的内部类,继承Handler。继续找到Handler处理消息的地方
public void handleMessage(Message msg) {
if (DEBUG_MESSAGES) Slog.v(TAG, ">>> handling: " + codeToString(msg.what));
switch (msg.what) {
case BIND_APPLICATION:
Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, "bindApplication");
AppBindData data = (AppBindData)msg.obj;
handleBindApplication(data);//1
Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);
break;
...
}
}
注释1处handleBindApplication方法
##ActivityThread
private void handleBindApplication(AppBindData data) {
...
//创建Application
app = data.info.makeApplication(data.restrictedBackupMode, null);
...
}
handleBindApplication方法中,调用了LoadedApk中的makeApplication方法。我们再来看看makeApplication的具体创建过程
@UnsupportedAppUsage
public Application makeApplication(boolean forceDefaultAppClass,
Instrumentation instrumentation) {
if (mApplication != null) {
return mApplication;
}
Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, "makeApplication");
Application app = null;
String appClass = mApplicationInfo.className;
if (forceDefaultAppClass || (appClass == null)) {
appClass = "android.app.Application";
}
try {
//获取加载器
final java.lang.ClassLoader cl = getClassLoader();
if (!mPackageName.equals("android")) {
Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER,
"initializeJavaContextClassLoader");
initializeJavaContextClassLoader();
Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);
}
...
//获取上下文
ContextImpl appContext = ContextImpl.createAppContext(mActivityThread, this);//1
//反射获取Application
app = mActivityThread.mInstrumentation.newApplication(
cl, appClass, appContext);//2
appContext.setOuterContext(app);
} catch (Exception e) {
if (!mActivityThread.mInstrumentation.onException(app, e)) {
Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);
throw new RuntimeException(
"Unable to instantiate application " + appClass
+ ": " + e.toString(), e);
}
}
mActivityThread.mAllApplications.add(app);
mApplication = app;
if (instrumentation != null) {
try {
instrumentation.callApplicationOnCreate(app);//3
} catch (Exception e) {
if (!instrumentation.onException(app, e)) {
Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);
throw new RuntimeException(
"Unable to create application " + app.getClass().getName()
+ ": " + e.toString(), e);
}
}
}
Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);
return app;
}
注释1创建了Application的上下文,也就是getApplicationContext()获取到的上下文,获取的是一个ContextImpl对象,ContextImpl 是Context的子类。注释2就是创建Application了,在makeApplication中通过类加载器和反射创建了Application;注释3调用了Application的onCreate方法。
Application启动可分为三步:
第一步,创建应用进程ActivityThread;
第二步,绑定应用程序和系统程序,也就是通过AIDL跨进程通信让系统进程分配pid和uid等应用信息;
第三步,创建Application,调用onCreate方法。
创建Activity
@GuardedBy("this")
private boolean attachApplicationLocked(@NonNull IApplicationThread thread,
int pid, int callingUid, long startSeq) {
...
// See if the top visible activity is waiting to run in this process...
//查看顶部可见活动是否正在等待在此进程中运行
if (normalMode) {
try {
if (mStackSupervisor.attachApplicationLocked(app)) {//1
didSomething = true;
}
} catch (Exception e) {
Slog.wtf(TAG, "Exception thrown launching activities in " + app, e);
badApp = true;
}
}
// Find any services that should be running in this process...
//查找此进程中应运行的任何服务
if (!badApp) {
try {
didSomething |= mServices.attachApplicationLocked(app, processName);
checkTime(startTime, "attachApplicationLocked: after mServices.attachApplicationLocked");
} catch (Exception e) {
Slog.wtf(TAG, "Exception thrown starting services in " + app, e);
badApp = true;
}
}
// Check if a next-broadcast receiver is in this process...
//查看此进程中应运行的广播接受者
if (!badApp && isPendingBroadcastProcessLocked(pid)) {
try {
didSomething |= sendPendingBroadcastsLocked(app);
checkTime(startTime, "attachApplicationLocked: after sendPendingBroadcastsLocked");
} catch (Exception e) {
// If the app died trying to launch the receiver we declare it 'bad'
Slog.wtf(TAG, "Exception thrown dispatching broadcasts in " + app, e);
badApp = true;
}
}
...
}
在绑定application后,AMS会查找此进程中应该运行的activity,服务已经广播接收者,分别进行创建;注释1处就是创建activity的起点。进入StackSupervisor类的attachApplicationLocked方法。
boolean attachApplicationLocked(ProcessRecord app) throws RemoteException {
...
//真正开始解锁Activity
if (realStartActivityLocked(activity, app,
top == activity /* andResume */, true /* checkConfig */)) {
didSomething = true;
}
...
}
在attachApplicationLocked方法中经过一系列的判断和检测最终调到了realStartActivityLocked方法,意为真正开始解锁Activity,方法传入activity信息和application信息;继续往下走;
final boolean realStartActivityLocked(ActivityRecord r, ProcessRecord app,
boolean andResume, boolean checkConfig) throws RemoteException {
...
// Create activity launch transaction.
//创建活动启动事务
final ClientTransaction clientTransaction = ClientTransaction.obtain(app.thread,
r.appToken);
//添加第一个创建Activity回调,也就是LaunchActivityItem
clientTransaction.addCallback(LaunchActivityItem.obtain(new Intent(r.intent),
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, mService.isNextTransitionForward(),
profilerInfo));
// Set desired final state. 设置所需的最终状态
final ActivityLifecycleItem lifecycleItem;
if (andResume) {
lifecycleItem = ResumeActivityItem.obtain(mService.isNextTransitionForward());
} else {
lifecycleItem = PauseActivityItem.obtain();
}
clientTransaction.setLifecycleStateRequest(lifecycleItem);//把最终生命周期放入Transaction,后面会用到
// Schedule transaction. 执行事务
mService.getLifecycleManager().scheduleTransaction(clientTransaction);
...
}
在realStartActivityLocked中开启了一个activity启动事务,事务中添加了LaunchActivityItem以用于后期创建时用,然后设置activity最终生命周期,开始执行任务;
void scheduleTransaction(ClientTransaction transaction) throws RemoteException {
final IApplicationThread client = transaction.getClient();
transaction.schedule();//1
if (!(client instanceof Binder)) {
// If client is not an instance of Binder - it's a remote call and at this point it is
// safe to recycle the object. All objects used for local calls will be recycled after
// the transaction is executed on client in ActivityThread.
transaction.recycle();
}
}
public void schedule() throws RemoteException {
mClient.scheduleTransaction(this);
}
mClient是ActivityThread的代理对象,用于跨进程调用ActivityThread的方法,接下来程序从系统进程走入应用进程;
@Override
public void scheduleTransaction(ClientTransaction transaction) throws RemoteException {
ActivityThread.this.scheduleTransaction(transaction);
}
继续往下走,进入ClientTransactionHandler类中的scheduleTransaction方法;
void scheduleTransaction(ClientTransaction transaction) {
transaction.preExecute(this);
sendMessage(ActivityThread.H.EXECUTE_TRANSACTION, transaction);
}
ClientTransactionHandler是ActivityThread的父类,和创建application一样,scheduleTransaction方法中发送了一个handler消息,任务作为消息被传送了出去;
case EXECUTE_TRANSACTION:
final ClientTransaction transaction = (ClientTransaction) msg.obj;
mTransactionExecutor.execute(transaction);//1
if (isSystem()) {
// Client transactions inside system process are recycled on the client side
// instead of ClientLifecycleManager to avoid being cleared before this
// message is handled.
transaction.recycle();
}
// TODO(lifecycler): Recycle locally scheduled transactions.
break;
注释1处继续往下走
public void execute(ClientTransaction transaction) {
final IBinder token = transaction.getActivityToken();
log("Start resolving transaction for client: " + mTransactionHandler + ", token: " + token);
executeCallbacks(transaction);//1 创建Activity 调用onCreate
executeLifecycleState(transaction);//2 其它生命周期的调用
mPendingActions.clear();
log("End resolving transaction");
}
进入TransactionExecutor类的execute方法,注释1处执行创建Activity,注释2处为调用Activity其它生命周期;先来看executeCallbacks方法;
@VisibleForTesting
public void executeCallbacks(ClientTransaction transaction) {
final List<ClientTransactionItem> callbacks = transaction.getCallbacks();
...
final int size = callbacks.size();
for (int i = 0; i < size; ++i) {
final ClientTransactionItem item = callbacks.get(i);//1
...
item.execute(mTransactionHandler, token, mPendingActions);//2
item.postExecute(mTransactionHandler, token, mPendingActions);
...
}
}
注释1处获取了ClientTransactionItem,这个item就是前面创建transaction 时传入的LaunchActivityItem,注释2处调用了LaunchActivityItem的execute方法,注意传入的参数mTransactionHandler其实就是ActivityThread;按照之前的尿性猜测一下,LaunchActivityItem的execute方法中还是不会创建activity,创建的方法应该在ActivityThread中,传入参数mTransactionHandler就是为了方便调用,是不是这样呢,继续往下看;
@Override
public void execute(ClientTransactionHandler client, IBinder token,
PendingTransactionActions pendingActions) {
Trace.traceBegin(TRACE_TAG_ACTIVITY_MANAGER, "activityStart");
ActivityClientRecord r = new ActivityClientRecord(token, mIntent, mIdent, mInfo,
mOverrideConfig, mCompatInfo, mReferrer, mVoiceInteractor, mState, mPersistentState,
mPendingResults, mPendingNewIntents, mIsForward,
mProfilerInfo, client);
client.handleLaunchActivity(r, pendingActions, null /* customIntent */);//1
Trace.traceEnd(TRACE_TAG_ACTIVITY_MANAGER);
}
注释1处果然调用了ActivityThread的handleLaunchActivity方法,找到这个方法
@Override
public Activity handleLaunchActivity(ActivityClientRecord r,
PendingTransactionActions pendingActions, Intent customIntent) {
...
final Activity a = performLaunchActivity(r, customIntent);//创建Activity
...
return a;
}
终于看到Activity 被创建出来了,performLaunchActivity就是创建Activity 的方法,具体怎么创建的,来看看performLaunchActivity方法;
private Activity performLaunchActivity(ActivityClientRecord r, Intent customIntent) {
...
ContextImpl appContext = createBaseContextForActivity(r);
Activity activity = null;
try {//1
java.lang.ClassLoader cl = appContext.getClassLoader();
activity = mInstrumentation.newActivity(
cl, component.getClassName(), r.intent);
StrictMode.incrementExpectedActivityCount(activity.getClass());
r.intent.setExtrasClassLoader(cl);
r.intent.prepareToEnterProcess();
if (r.state != null) {
r.state.setClassLoader(cl);
}
} catch (Exception e) {
if (!mInstrumentation.onException(activity, e)) {
throw new RuntimeException(
"Unable to instantiate activity " + component
+ ": " + e.toString(), e);
}
}
try {
...
if (activity != null) {
...
if (r.isPersistable()) {//2
mInstrumentation.callActivityOnCreate(activity, r.state, r.persistentState);
} else {
mInstrumentation.callActivityOnCreate(activity, r.state);
}
...
r.activity = activity;
}
r.setState(ON_CREATE);//3
mActivities.put(r.token, r);//4
} catch (SuperNotCalledException e) {
throw e;
} catch (Exception e) {
if (!mInstrumentation.onException(activity, e)) {
throw new RuntimeException(
"Unable to start activity " + component
+ ": " + e.toString(), e);
}
}
return activity;
}
注释1处可以看到和创建application类似,activity也是通过类加载器和反射的方式创建的;注释2处调用了activity的onCreate方法;注释3处把activity的生命周期状态置为ON_CREATE,在后面调用生命周期的时候还会出现;注释4是把activity加入的activity队列;至此activity创建完成,下面我们看看activity生命周期调用;
回到TransactionExecutor类的execute方法;
public void execute(ClientTransaction transaction) {
final IBinder token = transaction.getActivityToken();
log("Start resolving transaction for client: " + mTransactionHandler + ", token: " + token);
executeCallbacks(transaction);//1 创建Activity 调用onCreate
executeLifecycleState(transaction);//2 其它生命周期的调用
mPendingActions.clear();
log("End resolving transaction");
}
注释2处就是activity其它生命周期的方法;继续往下看
/** Transition to the final state if requested by the transaction. */
private void executeLifecycleState(ClientTransaction transaction) {
final ActivityLifecycleItem lifecycleItem = transaction.getLifecycleStateRequest();
...
// Cycle to the state right before the final requested state.
cycleToPath(r, lifecycleItem.getTargetState(), true /* excludeLastState */);//1
// Execute the final transition with proper parameters.
lifecycleItem.execute(mTransactionHandler, token, mPendingActions);
lifecycleItem.postExecute(mTransactionHandler, token, mPendingActions);
}
/** Transition the client between states. */
@VisibleForTesting
public void cycleToPath(ActivityClientRecord r, int finish) {
cycleToPath(r, finish, false /* excludeLastState */);
}
/**
* Transition the client between states with an option not to perform the last hop in the
* sequence. This is used when resolving lifecycle state request, when the last transition must
* be performed with some specific parameters.
*/
private void cycleToPath(ActivityClientRecord r, int finish,
boolean excludeLastState) {
final int start = r.getLifecycleState();
log("Cycle from: " + start + " to: " + finish + " excludeLastState:" + excludeLastState);
final IntArray path = mHelper.getLifecyclePath(start, finish, excludeLastState);//2
performLifecycleSequence(r, path);//3
}
这里主要看下注释1处的cycleToPath方法,经过层层调用走到注释2处的getLifecyclePath方法,传入的start, finish分别是activity的当前状态和目标状态,因为在创建activity的时候已经把状态设置成ON_CREATE了,所以start现在的值是ON_CREATE;来看一下getLifecyclePath方法;
@VisibleForTesting
public IntArray getLifecyclePath(int start, int finish, boolean excludeLastState) {
if (start == UNDEFINED || finish == UNDEFINED) {
throw new IllegalArgumentException("Can't resolve lifecycle path for undefined state");
}
if (start == ON_RESTART || finish == ON_RESTART) {
throw new IllegalArgumentException(
"Can't start or finish in intermittent RESTART state");
}
if (finish == PRE_ON_CREATE && start != finish) {
throw new IllegalArgumentException("Can only start in pre-onCreate state");
}
mLifecycleSequence.clear();
if (finish >= start) {
// just go there
for (int i = start + 1; i <= finish; i++) {
mLifecycleSequence.add(i);
}
} else { // finish < start, can't just cycle down
if (start == ON_PAUSE && finish == ON_RESUME) {
// Special case when we can just directly go to resumed state.
mLifecycleSequence.add(ON_RESUME);
} else if (start <= ON_STOP && finish >= ON_START) {
// Restart and go to required state.
// Go to stopped state first.
for (int i = start + 1; i <= ON_STOP; i++) {
mLifecycleSequence.add(i);
}
// Restart
mLifecycleSequence.add(ON_RESTART);
// Go to required state
for (int i = ON_START; i <= finish; i++) {
mLifecycleSequence.add(i);
}
} else {
// Relaunch and go to required state
// Go to destroyed state first.
for (int i = start + 1; i <= ON_DESTROY; i++) {
mLifecycleSequence.add(i);
}
// Go to required state
for (int i = ON_CREATE; i <= finish; i++) {
mLifecycleSequence.add(i);
}
}
}
// Remove last transition in case we want to perform it with some specific params.
if (excludeLastState && mLifecycleSequence.size() != 0) {
mLifecycleSequence.remove(mLifecycleSequence.size() - 1);
}
return mLifecycleSequence;
}
上面说到start值是在创建activity的时候设置的,那finish是在哪里设置的呢?还记得在创建启动activity任务时也给任务设置了ActivityLifecycleItem吧
final boolean realStartActivityLocked(ActivityRecord r, ProcessRecord app,
boolean andResume, boolean checkConfig) throws RemoteException {
...
// Set desired final state. 设置所需的最终状态
final ActivityLifecycleItem lifecycleItem;
if (andResume) {
lifecycleItem = ResumeActivityItem.obtain(mService.isNextTransitionForward());
} else {
lifecycleItem = PauseActivityItem.obtain();
}
...
}
finish的值就是在这时候确定的,此时的值应该是ON_RESUME,getLifecyclePath其实就是筛选出当前状态后一个状态,然后存入IntArray 返回;
回到cycleToPath方法,在得到activity下一个周期后,调用了performLifecycleSequence方法,activity生命周期方法就是在这里调用的,来看代码
/** Transition the client through previously initialized state sequence. */
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:
mTransactionHandler.handleLaunchActivity(r, mPendingActions,
null /* customIntent */);
break;
case ON_START:
mTransactionHandler.handleStartActivity(r, mPendingActions);
break;
case ON_RESUME:
mTransactionHandler.handleResumeActivity(r.token, false /* finalStateRequest */,
r.isForward, "LIFECYCLER_RESUME_ACTIVITY");
break;
case ON_PAUSE:
mTransactionHandler.handlePauseActivity(r.token, false /* finished */,
false /* userLeaving */, 0 /* configChanges */, mPendingActions,
"LIFECYCLER_PAUSE_ACTIVITY");
break;
case ON_STOP:
mTransactionHandler.handleStopActivity(r.token, false /* show */,
0 /* configChanges */, mPendingActions, false /* finalStateRequest */,
"LIFECYCLER_STOP_ACTIVITY");
break;
case ON_DESTROY:
mTransactionHandler.handleDestroyActivity(r.token, false /* finishing */,
0 /* configChanges */, false /* getNonConfigInstance */,
"performLifecycleSequence. cycling to:" + path.get(size - 1));
break;
case ON_RESTART:
mTransactionHandler.performRestartActivity(r.token, false /* start */);
break;
default:
throw new IllegalArgumentException("Unexpected lifecycle state: " + state);
}
}
}
可以看到不同的状态都有对应的方法调用生命周期,mTransactionHandler上文提到过就是ActivityThread,所以这些生命周期方法都是在ActivityThread中调用的;拿ON_RESUME为例,找到对应的handleResumeActivity方法;
@Override
public void handleResumeActivity(IBinder token, boolean finalStateRequest, boolean isForward, String reason) {
...
// TODO Push resumeArgs into the activity for consideration
final ActivityClientRecord r = performResumeActivity(token, finalStateRequest, reason);
...
}
到这里activity生命周期就调用了,performResumeActivity具体实现在这里就不赘述了,有兴趣可以自己看一下。
网友评论