本文是 Android 系統(tǒng)學(xué)習(xí)系列文章中的第三章節(jié)的內(nèi)容,在前面的文章 Android 應(yīng)用進(jìn)程啟動(dòng)流程 講了 Android 是如何啟動(dòng)的,在這篇文章里,將詳細(xì)說明 Activity 生命周期的實(shí)現(xiàn)原理,onCreate、onResume、onPause 等主要生命周期回調(diào)是如何實(shí)現(xiàn)的,ActivityManangerService 在里面扮演的角色。對(duì)此系列感興趣的同學(xué),可以收藏這個(gè)鏈接 Android 系統(tǒng)學(xué)習(xí),也可以點(diǎn)擊 http://www.woaitqs.cc/feed.xml 進(jìn)行訂閱。
背景知識(shí)介紹
這篇文章中涉及到 Binder 的設(shè)計(jì)實(shí)現(xiàn),如果對(duì)這一塊不是很熟悉的話,建議閱讀后續(xù)代碼時(shí),先看看下面的鏈接的內(nèi)容,特別是 AIDL 的實(shí)現(xiàn)。
- Android Binder 完全解析(一)概述
- Android Binder 完全解析(二)設(shè)計(jì)詳解
- Android Binder 完全解析(三)AIDL實(shí)現(xiàn)原理分析
- ActivityThread: 運(yùn)行在應(yīng)用進(jìn)程的主線程上,響應(yīng) ActivityManangerService 啟動(dòng)、暫停Activity,廣播接收等消息。
- ActivityThread.mH: 繼承自 Handler,用于發(fā)送組件相關(guān)的事件消息。
- ActivityThread.ApplicationThread: Binder 對(duì)象, 通過 ApplicationThreadProxy 的構(gòu)造函數(shù)注入進(jìn)去,作為 ActivityThread 的內(nèi)部類,響應(yīng)具體的 ActivityManagerService 的方法請(qǐng)求。
- ApplicationThreadProxy: Binder Proxy 對(duì)象,傳遞到 ActivityManagerService 中,當(dāng) ActivityManagerService 需要讓 Activity 做相應(yīng)諸如啟動(dòng)、銷毀等事情時(shí),會(huì)通過 ActivityThread.ApplicationThread 執(zhí)行具體的業(yè)務(wù)邏輯。
- Instrumentation: Android 提供的用于監(jiān)聽 Activity 與系統(tǒng)交互的機(jī)制。
- ActivityManagerService: Android 核心的組件服務(wù),用于管理控制各類組件。
從實(shí)際的例子出發(fā),會(huì)更方便理解,這里以從列表頁面(以下簡稱 From Activity)跳轉(zhuǎn)到詳情頁面(以下簡稱 To Activity)為例,說明在這個(gè)過程中發(fā)生的事情。
Activity 生命周期實(shí)現(xiàn)
1)From Activity 請(qǐng)求 ActivityManageService 啟動(dòng) To Activity
首先當(dāng)點(diǎn)擊 From Activity 中的列表頁時(shí),通過下面的代碼發(fā)送 Intent,啟動(dòng) To Activity。
Intent intent = new Intent(context, Detail.class);
intent.putInt(Const.REST_ID, id);
startActivity(intent);
這段代碼會(huì)執(zhí)行到 Activity 的 startActivity
方法,Activity 中也有多個(gè)不同簽名的 startActivity
,都會(huì)執(zhí)行到 startActivityForResult
這個(gè)方法,扼要的代碼如下:
public void startActivityForResult(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());
}
// ...
cancelInputsAndStartExitTransition(options);
} 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);
}
}
}
無論 Parent 是否為空,最后都是通過 Instrumentation 來執(zhí)行啟動(dòng)的任務(wù),Instrumentation 是 Android 設(shè)計(jì)者提供出來的中間層,方便開發(fā)者監(jiān)聽系統(tǒng)各種與 Application 的交互,同時(shí)也對(duì)測試工作很有幫助,接下來看看 Instrumentation 的具體代碼。
Instrumentation 在提供相應(yīng)的監(jiān)聽邏輯后,調(diào)用了 ActivityManagerNative 來執(zhí)行相應(yīng)的邏輯,如下所示。
public ActivityResult execStartActivity(
Context who, IBinder contextThread, IBinder token, Activity target,
Intent intent, int requestCode, Bundle options) {
...
try {
intent.migrateExtraStreamToClipData();
intent.prepareToLeaveProcess();
int result = ActivityManagerNative.getDefault()
.startActivity(whoThread, who.getBasePackageName(), intent,
intent.resolveTypeIfNeeded(who.getContentResolver()),
token, target != null ? target.mEmbeddedID : null,
requestCode, , null, options);
checkStartActivityResult(result, intent);
} catch (RemoteException e) {
throw new RuntimeException("Failure from system", e);
}
return null;
}
這里先看看 getDefault
的實(shí)現(xiàn),看看里面返回的是什么?
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;
}
};
這里看到返回的是 ServiceManager.getService,ServiceManager 在 Framework 充當(dāng)了 DNS 的作用,通過 ServiceManager 可以找到其他的系統(tǒng)服務(wù),這里返回的正是名為的 activity 的 服務(wù)。在前面提供的鏈接 Android Binder 完全解析(三)AIDL實(shí)現(xiàn)原理分析 中,也講到了 ServiceManager 的實(shí)現(xiàn),會(huì)更詳細(xì)些。
接下來看看 asInterface 的實(shí)現(xiàn),這不正是很標(biāo)準(zhǔn)的 AIDL 實(shí)現(xiàn)嗎?傳入的 obj 對(duì)象正是鼎鼎大名的 ActivityManageService
, 這里通過 ActivityManagerProxy 進(jìn)行代理,將接口暴露到應(yīng)用層,這樣對(duì)于調(diào)用出于 System_server 進(jìn)程的方法時(shí),就如同在本地調(diào)用一樣。
static public IActivityManager asInterface(IBinder obj) {
if (obj == null) {
return null;
}
IActivityManager in =
(IActivityManager)obj.queryLocalInterface(descriptor);
if (in != null) {
return in;
}
return new ActivityManagerProxy(obj);
}
在 ActivityManagerProxy 中對(duì) startActivity 進(jìn)行轉(zhuǎn)發(fā)的代碼如下所示:
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;
}
這里采用的方式正是 Binder 的調(diào)用方式,在 ActivityManagerProxy 中持有了 ActivityManagerService 提供的 Binder 接口,所有的命令都是通過這個(gè) Binder 進(jìn)行消息發(fā)送的,在客戶端進(jìn)程調(diào)用 startActivity
時(shí),會(huì)調(diào)用到 ActivityManagerService 的 startActivity
方法里面,在進(jìn)行一些列的處理后,會(huì)執(zhí)行到 ActivityStackSupervisor 的 startActivityMayWait
方法里面,繼而調(diào)用到 startActivityLocked
方法中。
至此為止,在 From Activity 的啟動(dòng) Activity 請(qǐng)求,已經(jīng)傳遞到 ActivityManagerService
中。
2)ActivityManagerService 響應(yīng)啟動(dòng)請(qǐng)求
首先調(diào)用到 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 options) {
return startActivityAsUser(caller, callingPackage, intent, resolvedType, resultTo,
resultWho, requestCode, startFlags, profilerInfo, options,
UserHandle.getCallingUserId());
}
其后進(jìn)入到 startActivityAsUser 方法里面,在這個(gè)方法中,將邏輯移交到 ActivityStackSupervisor
中去。
@Override
public final int startActivityAsUser(IApplicationThread caller, String callingPackage,
Intent intent, String resolvedType, IBinder resultTo, String resultWho, int requestCode,
int startFlags, ProfilerInfo profilerInfo, Bundle options, int userId) {
enforceNotIsolatedCaller("startActivity");
userId = handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(), userId,
false, ALLOW_FULL_ONLY, "startActivity", null);
// TODO: Switch to user app stacks here.
return mStackSupervisor.startActivityMayWait(caller, -1, callingPackage, intent,
resolvedType, null, null, resultTo, resultWho, requestCode, startFlags,
profilerInfo, null, null, options, false, userId, null, null);
}
這里的 mStackSupervisor 就是 ActivityStackSupervisor , 這個(gè)類在 Android 4.4 以后才引入的,用于管理 ActivityStack。對(duì)于前面舉得這個(gè)例子,方法的運(yùn)行 Trace 會(huì)沿著下面的方法來執(zhí)行。
ActivityManagerService.startActivity()
ActvityiManagerService.startActivityAsUser()
ActivityStackSupervisor.startActivityMayWait()
ActivityStackSupervisor.startActivityLocked()
ActivityStackSupervisor.startActivityUncheckedLocked()
ActivityStackSupervisor.startActivityLocked()
ActivityStackSupervisor.resumeTopActivitiesLocked()
ActivityStackSupervisor.resumeTopActivityInnerLocked()
里面的邏輯非常復(fù)雜,也不在今天主要講的范圍內(nèi),這里只做簡單介紹。
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 config,
Bundle options, boolean ignoreTargetSecurity, int userId,
IActivityContainer iContainer, TaskRecord inTask) {
...
int res = startActivityLocked(caller, intent, resolvedType, aInfo,
voiceSession, voiceInteractor, resultTo, resultWho,
requestCode, callingPid, callingUid, callingPackage,
realCallingPid, realCallingUid, startFlags, options, ignoreTargetSecurity,
componentSpecified, null, container, inTask);
...
return res;
}
在 startActivityMayWait 中,會(huì)去查看是否存在相應(yīng)的Activity,如果同時(shí)存在多個(gè)相應(yīng)的 Activity,彈出一個(gè)對(duì)話框,讓用戶進(jìn)行選擇。
final int startActivityLocked(IApplicationThread caller,
Intent intent, String resolvedType, ActivityInfo aInfo,
IVoiceInteractionSession voiceSession, IVoiceInteractor voiceInteractor,
IBinder resultTo, String resultWho, int requestCode,
int callingPid, int callingUid, String callingPackage,
int realCallingPid, int realCallingUid, int startFlags, Bundle options,
boolean ignoreTargetSecurity, boolean componentSpecified, ActivityRecord[] outActivity,
ActivityContainer container, TaskRecord inTask) {
int err = ActivityManager.START_SUCCESS;
...
err = startActivityUncheckedLocked(r, sourceRecord, voiceSession, voiceInteractor,
startFlags, true, options, inTask);
...
return err;
}
在 startActivityLocked 和 startActivityUncheckedLocked 方法里, 建立了相應(yīng)的 ActivityRecord 對(duì)象,加入到 TaskRecord 中,并根據(jù)相應(yīng)的 LaunchMode 和 Flag 進(jìn)行相應(yīng)的進(jìn)棧出棧處理,所有的細(xì)節(jié)都在這兩個(gè)方法里面,就不在展開了。關(guān)于 Activity 的棧,這里有一篇很好的文章,可供翻閱,Understand Android Activity's launchMode: standard, singleTop, singleTask and singleInstance,還有一個(gè)不錯(cuò)的 PPT,講解關(guān)于 LaunchMode 中的一些坑,Manipulating Android tasks and back stack。
最后執(zhí)行到 startActivityLocked,調(diào)用 resumeTopActivitiesLocked 方法。
final void startActivityLocked(ActivityRecord r, boolean newTask,
boolean doResume, boolean keepCurTransition, Bundle options) {
// ...
if (doResume) {
mStackSupervisor.resumeTopActivitiesLocked(this, r, options);
}
}
經(jīng)過一些方法的參數(shù)處理后,執(zhí)行 resume 代碼邏輯,在 resumeTopActivityInnerLocked 方法里。
private boolean resumeTopActivityInnerLocked(ActivityRecord prev, Bundle options) {
...
if (mResumedActivity != null) {
if (DEBUG_STATES) Slog.d(TAG_STATES,
"resumeTopActivityLocked: Pausing " + mResumedActivity);
pausing |= startPausingLocked(userLeaving, false, true, dontWaitForPause);
} ...
return true;
}
在啟動(dòng)下一個(gè) Activity,需要將上一個(gè) Activity 暫停掉,這在面試中也經(jīng)常問到,大家可以注意下。上面的代碼也也驗(yàn)證了先行 pause 的邏輯,在下面的章節(jié)中看看是如何暫停 From Activity的。
3)暫停 From Activity
final boolean startPausingLocked(boolean userLeaving, boolean uiSleeping, boolean resuming,
boolean dontWait) {
...
if (prev.app != null && prev.app.thread != null) {
if (DEBUG_PAUSE) Slog.v(TAG_PAUSE, "Enqueueing pending pause: " + prev);
try {
EventLog.writeEvent(EventLogTags.AM_PAUSE_ACTIVITY,
prev.userId, System.identityHashCode(prev),
prev.shortComponentName);
mService.updateUsageStats(prev, false);
prev.app.thread.schedulePauseActivity(prev.appToken, prev.finishing,
userLeaving, prev.configChangeFlags, dontWait);
} catch (Exception e) {
// Ignore exception, if process died other code will cleanup.
Slog.w(TAG, "Exception thrown during pause", e);
mPausingActivity = null;
mLastPausedActivity = null;
mLastNoHistoryActivity = null;
}
} else {
mPausingActivity = null;
mLastPausedActivity = null;
mLastNoHistoryActivity = null;
}
...
}
startPausingLocked 的方法里面調(diào)用了 prev.app.thread.schedulePauseActivity 這個(gè)方法,其中這里的 thread,是上文中傳遞過去的 IApplicationThread,這里指的是 ApplicationThreadProxy 對(duì)象。這里和前面調(diào)用 ActivityManageService 的方式相同,也是采用的 Binder 框架,將要具體的數(shù)據(jù)通過 Parcable 傳遞到 ActivityThread.ApplicationThread 中,接下來看看 ActivityThread 中 schedulePauseActivity的具體實(shí)現(xiàn)。
public final void schedulePauseActivity(IBinder token, boolean finished,
boolean userLeaving, int configChanges, boolean dontReport) {
sendMessage(
finished ? H.PAUSE_ACTIVITY_FINISHING : H.PAUSE_ACTIVITY,
token,
(userLeaving ? 1 : 0) | (dontReport ? 2 : 0),
configChanges);
}
這里的 sendMessage 方法,是通過 ActivityThread 的 mH 這個(gè)類來進(jìn)行 Message 的發(fā)放,這里傳遞的消息是 PAUSE_ACTIVITY_FINISHING,我們看看 ActivityThread 是如何處理這個(gè)消息的。
case PAUSE_ACTIVITY_FINISHING:
Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, "activityPause");
handlePauseActivity((IBinder)msg.obj, true, (msg.arg1&1) != 0, msg.arg2,
(msg.arg1&1) != 0);
Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);
break;
邏輯還藏在 handlePauseActivity 里面,就接著往下看。
private void handlePauseActivity(IBinder token, boolean finished,
boolean userLeaving, int configChanges, boolean dontReport) {
ActivityClientRecord r = mActivities.get(token);
if (r != null) {
//Slog.v(TAG, "userLeaving=" + userLeaving + " handling pause of " + r);
if (userLeaving) {
performUserLeavingActivity(r);
}
r.activity.mConfigChangeFlags |= configChanges;
performPauseActivity(token, finished, r.isPreHoneycomb());
// Make sure any pending writes are now committed.
if (r.isPreHoneycomb()) {
QueuedWork.waitToFinish();
}
// Tell the activity manager we have paused.
if (!dontReport) {
try {
ActivityManagerNative.getDefault().activityPaused(token);
} catch (RemoteException ex) {
}
}
mSomeActivitiesChanged = true;
}
}
final Bundle performPauseActivity(ActivityClientRecord r, boolean finished,
boolean saveState) {
// ...
mInstrumentation.callActivityOnPause(r.activity);
// ...
return !r.activity.mFinished && saveState ? r.state : null;
}
又來到了 Instrumentation 這個(gè)類里面,前文也提到這個(gè)類監(jiān)聽著應(yīng)用與系統(tǒng)發(fā)生的通信,看來它還是挺盡職的。
public void callActivityOnPause(Activity activity) {
activity.performPause();
}
這里執(zhí)行的方法是 Activity.performPause,這應(yīng)該就是這次 Pause 流程的終點(diǎn)了。
final void performPause() {
mDoReportFullyDrawn = false;
mFragments.dispatchPause();
mCalled = false;
onPause();
mResumed = false;
if (!mCalled && getApplicationInfo().targetSdkVersion
>= android.os.Build.VERSION_CODES.GINGERBREAD) {
throw new SuperNotCalledException(
"Activity " + mComponent.toShortString() +
" did not call through to super.onPause()");
}
mResumed = false;
}
果然,我們熟悉的 onPause 回調(diào)就放在這里,到此 Pause 過程就完成了,現(xiàn)在接著回到 handlePauseActivity 里面去,還有方法沒有執(zhí)行完成。
private void handlePauseActivity(IBinder token, boolean finished,
boolean userLeaving, int configChanges, boolean dontReport) {
ActivityClientRecord r = mActivities.get(token);
if (r != null) {
// ...
if (!dontReport) {
try {
ActivityManagerNative.getDefault().activityPaused(token);
} catch (RemoteException ex) {
}
}
mSomeActivitiesChanged = true;
}
}
在執(zhí)行完成 Pause 過程后,繼續(xù)通過 ActivityManagerNative 執(zhí)行 ActivityManagerService 的 activityPause 方法,這個(gè)機(jī)制與前面的過程相同。從這里可以看到,ActivityThread 和 ActivityManagerService 互相持有著雙方的把柄,不,是 Binder 對(duì)象,Binder 機(jī)制使得在跨進(jìn)程調(diào)用的時(shí)候,和同進(jìn)程的方法調(diào)用沒有什么區(qū)別。
4)啟動(dòng) To Activity
@Override
public final void activityPaused(IBinder token) {
final long origId = Binder.clearCallingIdentity();
synchronized(this) {
ActivityStack stack = ActivityRecord.getStackLocked(token);
if (stack != null) {
stack.activityPausedLocked(token, false);
}
}
Binder.restoreCallingIdentity(origId);
}
Activity 的 pause 方法,也是通過 Stack 來完成,這樣便于進(jìn)行棧管理,來看看具體的實(shí)現(xiàn)。
final void activityPausedLocked(IBinder token, boolean timeout) {
//...
if (DEBUG_STATES) Slog.v(TAG_STATES, "Moving to PAUSED: " + r
+ (timeout ? " (due to timeout)" : " (pause complete)"));
completePauseLocked(true);
//...
}
private void completePauseLocked(boolean resumeNext) {
//...
if (resumeNext) {
final ActivityStack topStack = mStackSupervisor.getFocusedStack();
if (!mService.isSleepingOrShuttingDown()) {
mStackSupervisor.resumeTopActivitiesLocked(topStack, prev, null);
} else {
mStackSupervisor.checkReadyForSleepLocked();
ActivityRecord top = topStack.topRunningActivityLocked(null);
if (top == null || (prev != null && top != prev)) {
// If there are no more activities available to run,
// do resume anyway to start something. Also if the top
// activity on the stack is not the just paused activity,
// we need to go ahead and resume it to ensure we complete
// an in-flight app switch.
mStackSupervisor.resumeTopActivitiesLocked(topStack, null, null);
}
}
}
//...
}
接下來繼續(xù)經(jīng)過如下的調(diào)用棧
resumeTopActivitiesLocked
ActivityStack.resumeTopActivityLocked()
resumeTopActivityInnerLocked
startSpecificActivityLocked
最后調(diào)到了 startSpecificActivityLocked 方法里面來。
void startSpecificActivityLocked(ActivityRecord r,
boolean andResume, boolean checkConfig) {
// Is this activity's application already running?
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)) {
// Don't add this if it is a platform component that is marked
// to run in multiple processes, because this is actually
// part of the framework so doesn't make sense to track as a
// separate apk in the process.
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);
}
// If a dead object exception was thrown -- fall through to
// restart the application.
}
mService.startProcessLocked(r.processName, r.info.applicationInfo, true, 0,
"activity", r.intent.getComponent(), false, false, true);
}
這個(gè)方法存在兩個(gè)分支,當(dāng)對(duì)應(yīng)的應(yīng)用進(jìn)程存在時(shí),直接執(zhí)行 realStartActivityLocked 方法,否者就先新建應(yīng)用進(jìn)程。關(guān)于新建應(yīng)用進(jìn)程的事宜,在我的這篇博客http://www.woaitqs.cc/2016/06/21/activity-service.html里面,說得相對(duì)詳細(xì),這里就不再詳細(xì)說明了,其實(shí)在進(jìn)程啟動(dòng)完畢后,最后也會(huì)調(diào)用到 realStartActivityLocked 到這個(gè)方法里面來。
app.thread.scheduleLaunchActivity(new Intent(r.intent), r,
System.identityHashCode(r),
r.info, r.icicle, results, newIntents, !andResume,
mService.isNextTransitionForward());
在 realStartActivityLocked 方法中,同樣也是通過 ApplicationThreadProxy 進(jìn)行遠(yuǎn)程方法調(diào)用,最后會(huì)執(zhí)行到 ActivityThread 的scheduleLaunchActivity 的方法中來,在下面的代碼里面,可以看出 Binder 調(diào)用。
public final void scheduleLaunchActivity(Intent intent, IBinder token, int ident,
ActivityInfo info, Bundle state, List<ResultInfo> pendingResults,
List<Intent> pendingNewIntents, boolean notResumed, boolean isForward)
throws RemoteException {
Parcel data = Parcel.obtain();
data.writeInterfaceToken(IApplicationThread.descriptor);
intent.writeToParcel(data, 0);
data.writeStrongBinder(token);
data.writeInt(ident);
info.writeToParcel(data, 0);
data.writeBundle(state);
data.writeTypedList(pendingResults);
data.writeTypedList(pendingNewIntents);
data.writeInt(notResumed ? 1 : 0);
data.writeInt(isForward ? 1 : 0);
mRemote.transact(SCHEDULE_LAUNCH_ACTIVITY_TRANSACTION, data, null,
IBinder.FLAG_ONEWAY);
data.recycle();
}
和 Pause 的過程相同,只是這里發(fā)送的消息是 LAUNCH_ACTIVITY,我們看看在這一塊是如何處理的。
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);
Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);
handleLaunchActivity 的具體實(shí)現(xiàn)如下:
private final void handleLaunchActivity(ActivityClientRecord r, Intent customIntent) {
//......
Activity a = performLaunchActivity(r, customIntent);
if (a != null) {
r.createdConfig = new Configuration(mConfiguration);
Bundle oldState = r.state;
handleResumeActivity(r.token, false, r.isForward);
//......
} else {
//......
}
}
這里有兩個(gè)重要的方法,分別是 performLaunchActivity 和 handleResumeActivity 方法。
先看看 performLaunchActivity 方法,這里由幾個(gè)重要的部分組成。
收集相應(yīng)的組件信息。
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);
}
通過上面得到的組件信息,得到要具體啟動(dòng)的 Activity,這里的 Activity 是通過反射構(gòu)建出的對(duì)象。
Activity activity = null;
try {
java.lang.ClassLoader cl = r.packageInfo.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);
}
}
如果沒有相應(yīng)的 Application 信息,則會(huì)先建立相應(yīng)的 Application。
Application app = r.packageInfo.makeApplication(false, mInstrumentation);
接著把 Activity 對(duì)象,attach 到相應(yīng)的運(yùn)行環(huán)境上面去。
activity.attach(appContext, this, getInstrumentation(), r.token,
r.ident, app, r.intent, r.activityInfo, title, r.parent,
r.embeddedID, r.lastNonConfigurationInstance,
r.lastNonConfigurationChildInstances, config);
最后,又是通過 Instrumentation 調(diào)用了 Activity 的 onCreate 方法。
mInstrumentation.callActivityOnCreate(activity, r.state);
到此為止,Activity 完成了啟動(dòng)。
5)Activity 的 onResume 方法,和 onDestroy 方法
ActivityStack.resumeTopActivityLocked()
ActivityStack.resumeTopInnerLocked()
IApplicationThread.scheduleResumeActivity()
ActivityThread.scheduleResumeActivity()
ActivityThread.sendMessage()
ActivityTherad.H.sendMessage()
ActivityThread.H.handleMessage()
ActivityThread.H.handleResumeMessage()
Activity.performResume()
Activity.performRestart()
Instrumentation.callActivityOnRestart()
Activity.onRestart()
Activity.performStart()
Instrumentation.callActivityOnStart()
Activity.onStart()
Instrumentation.callActivityOnResume()
Activity.onResume()
Activity.finish()
ActivityManagerNative.getDefault().finishActivity()
ActivityManagerService.finishActivity()
ActivityStack.requestFinishActivityLocked()
ActivityStack.finishActivityLocked()
ActivityStack.startPausingLocked()
onResume 回調(diào)和當(dāng) Activity 銷毀時(shí)的 onDestroy 回調(diào)都與前面的過程大同小異,這里就只列舉相應(yīng)的方法棧,不再繼續(xù)描述。
總結(jié)
可以看到,Activity 的生命周期并不是一個(gè)類就可以簡單完成的,在這其中需要多個(gè)模塊之間進(jìn)行通信合作,才能做到現(xiàn)在的效果。里面涉及到兩種 Android 中常見的通信方式,分別是 Binder 機(jī)制和 Handler 機(jī)制。其中 Binder 機(jī)制用于 ActivityThread 和 ActivityManagerService 進(jìn)行進(jìn)程間通信,而 Handler 機(jī)制,則用在 ActivityThread 中,使得 ActivityThread 在合適的時(shí)機(jī)能處理相應(yīng)的生命周期。
文檔信息
- 版權(quán)聲明:自由轉(zhuǎn)載-非商用-非衍生-保持署名(創(chuàng)意共享3.0許可證)
- 發(fā)表日期:2016年7月20日
- 社交媒體:weibo.com/woaitqs
- Feed訂閱:www.woaitqs.cc/feed.xml