1. 程式人生 > >新增Intent.FLAG_ACTIVITY_CLEAR_TOP 都做了些什麼

新增Intent.FLAG_ACTIVITY_CLEAR_TOP 都做了些什麼

背景

最近老是看到各種面試中的lanchMode和Intent Flag, 大多數分析停留在表面, 並且有些還自相矛盾。lz 最近
做一個需求需要用Intent flag, 查閱了下相關資料, 並從原始碼論證了原因。新增Intent.FLAG_ACTIVITY_CLEAR_TOP我們來看看系統是怎麼做的? 別問我怎麼找到原始碼的,我不告訴你是通過androidxref查詢的。

整體流程

private int startActivityUnchecked 整體的邏輯就在這個函式中了,邏輯也比較清楚,

  1. setInitialState(r, options, inTask, doResume, startFlags, sourceRecord, voiceSession, voiceInteractor);
    初始化lauchMode和Intent Flags

  2. computeLaunchingTaskFlags();

  3. computeSourceStack();

  4. mReusedActivity = getReusableIntentActivity(); 查詢可複用的activity

  5. 特殊Flag處理如本文的 FLAG_ACTIVITY_CLEAR_TOP

 private int startActivityUnchecked(final ActivityRecord r, ActivityRecord sourceRecord,
1025            IVoiceInteractionSession voiceSession, IVoiceInteractor voiceInteractor,
1026
int startFlags, boolean doResume, ActivityOptions options, TaskRecord inTask)
{ 1027 1028 setInitialState(r, options, inTask, doResume, startFlags, sourceRecord, voiceSession, 1029 voiceInteractor); 1030 1031 computeLaunchingTaskFlags(); 1032 1033 computeSourceStack(); 1034
1035 mIntent.setFlags(mLaunchFlags); 1036 1037 mReusedActivity = getReusableIntentActivity(); 1038 1039 final int preferredLaunchStackId = 1040 (mOptions != null) ? mOptions.getLaunchStackId() : INVALID_STACK_ID; 1041 1042 if (mReusedActivity != null) { ...... 1066 if ((mLaunchFlags & FLAG_ACTIVITY_CLEAR_TOP) != 0 1067 || mLaunchSingleInstance || mLaunchSingleTask) { 1068 // In this situation we want to remove all activities from the task up to the one 1069 // being started. In most cases this means we are resetting the task to its initial 1070 // state. 1071 final ActivityRecord top = mReusedActivity.task.performClearTaskForReuseLocked( 1072 mStartActivity, mLaunchFlags); 1073 if (top != null) { 1074 if (top.frontOfTask) { 1075 // Activity aliases may mean we use different intents for the top activity, 1076 // so make sure the task now has the identity of the new intent. 1077 top.task.setIntent(mStartActivity); 1078 } 1079 ActivityStack.logStartActivity(AM_NEW_INTENT, mStartActivity, top.task); 1080 top.deliverNewIntentLocked(mCallingUid, mStartActivity.intent, 1081 mStartActivity.launchedFromPackage); 1082 } 1083 } 1084 ....... //中間為嘛省略呢? 與我們主題討論的Intent.FLAG_ACTIVITY_CLEAR_TOP 相關度不大,其他的flag處理 1250 }

直接到第4步

image.png

註釋很詳細,不多說了,處理lanchMode和flag

第5步 處理FLAG_ACTIVITY_CLEAR_TOP

image.png

主要是查詢到對應的activity記錄,從後往前遍歷,模擬棧操作,然後找到目標activity, 將該activity棧頂的activity finish掉。 最後處理Activity, 如果不含有singletop 的intent flag 就finish掉該activity。