您的位置:首页 > 移动开发 > Android开发

Android活动的生命周期之正常生命周期分析(二)

2018-01-26 00:16 316 查看
借鉴开发艺术

当活动A启动了活动B,他们两个的生命周期方法是这样调用的:

A:onPause

B:onCreate

B:onStart

B:onResume

A:onStop

启动Activity的请求会由Instrumentation来处理,它通过Binder向AMS发送请求(ActivityManagerService),AMS内部维护一个ActivityStack并负责栈内的活动的状态同步,AMS通过ActivityThread去同步Activity的状态从而完成生命周期的方法调用

ActivityStack中的resumeTopActivityInnerLocked方法

boolean pausing = mStackSupervisor.pauseBackStacks(userLeaving, next, false);
if (mResumedActivity != null) {
if (DEBUG_STATES) Slog.d(TAG_STATES,
"resumeTopActivityLocked: Pausing " + mResumedActivity);
pausing |= startPausingLocked(userLeaving, false, next, false);
}
if (pausing && !resumeWhilePausing) {

关键点:这里的pauseBackStacks的最后一个参数的意思是,不等待原Activity的onPause就直接调用新Activity的生命周期,这里传入false,就代表是必须要进行这样一个等待的。

ActivityStackSupervisor中的realStartActivityLocked的方法

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);

这里的app.thread就是IApplicationThread,而IApplicationThread的具体实现是AppliactionThread,所以这里等于调用了AppliactionThread的scheduleLaunchActivity方法。而这个方法会先后完成新Activity的启动生命周期

scheduleLaunchActivity方法最终调用的handleLaunchActivity方法会进行生命周期的调用

private void handleLaunchActivity(ActivityClientRecord r, Intent customIntent, String reason) {
// If we are getting ready to gc after going to the background, well
// we are back active so skip it.
unscheduleGcIdler();
mSomeActivitiesChanged = true;

if (r.profilerInfo != null) {
mProfiler.setProfiler(r.profilerInfo);
mProfiler.startProfiling();
}

// Make sure we are running with the most recent config.
handleConfigurationChanged(null, null);

if (localLOGV) Slog.v(
TAG, "Handling launch of " + r);

// Initialize before creating the activity
WindowManagerGlobal.initialize();

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.st

performLaunchActivity(r, customIntent)完成了onCreate、onStart的调用

handleResumeActivity完成了onResume的调用

通过这个现象我们可以得出一个结论就是,如果在onPause中可以进行资源释放,但是必须轻量,不然会阻塞新activity的显示;推荐在onStop中进行资源的释放,但是不能太过重量级。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: