編輯:關於 Android 程式設計
Activity 作為 Android 的顯示元件,在整個開發體系裡佔有舉足輕重的地位。在寫了一段時間 Android 之後,我對 Activity 的七大生命週期以及它究竟是如何被啟動的產生了濃厚興趣。老實說,為了讀通這條流程,我補了不少前置知識,也投入了不少時間。
延續上一篇關於 Window 建立的源碼閱讀,這裡先放上我自己畫出的 Activity 啟動理解圖:

這個過程牽涉到的類別不少:Activity、Instrumentation、ActivityManagerService、ActivityStackSupervisor、ActivityStack、WindowManagerService、ActivityThread、ActivityRecord、TaskRecord、ProcessRecord、Intent、PackageManagerService 等。
我們平常啟動 Activity 的寫法大致如下:
Intent i = new Intent(preActivity.this, MainActivity.class); startActivity(i);
可以說 startActivity() 就是啟動活動的入口。看看 Android 5.0 下它是怎麼運作的:
public void startActivity(Intent intent) {
this.startActivity(intent, null);
}
這裡又呼叫了參數不同的 startActivity() 重載版本。往下追會發現,Activity 中所有 startActivity 最終都彙整到 startActivityForResult():
@Override
public void startActivity(Intent intent, @Nullable Bundle options) {
if (options != null) {
startActivityForResult(intent, -1, options);
} else {
startActivityForResult(intent, -1);
}
}
真正在整條流程中起作用的是 startActivityForResult:
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());
}
...
} else {
mParent.startActivityFromChild(this, intent, requestCode, options);
}
}
這段程式碼完成了幾件事:
1. 若父 Activity 為空,則建立 Instrumentation.ActivityResult,並把啟動工作交給工具類 Instrumentation 的 execStartActivity 處理。
2. mMainThread 指的是 ActivityThread 類別,也就是 App 運行所在的行程。它會把請求碼丟給 Handler 處理,最後又回到 Activity 的 dispatchActivityResult() 來處理活動之間的資料回傳。
void dispatchActivityResult(String who, int requestCode, int resultCode, Intent data) {
mFragments.noteStateNotSaved();
if (who == null) {
onActivityResult(requestCode, resultCode, data);
} else {
Fragment frag = mFragments.findFragmentByWho(who);
if (frag != null) {
frag.onActivityResult(requestCode, resultCode, data);
}
}
}
最終會回到我們熟悉的 onActivityResult()。當我們需要把結果回傳給上一個 Activity 時,不正是要事先約定 requestCode,並覆寫 onActivityResult() 嗎?從這幾段源碼可以提煉出兩個實務結論:設定 requestCode 時盡量避開 -1,以免與系統內部碼衝突而引發非預期的錯誤;而回傳後的處理邏輯應該寫在 onActivityResult 中。
下面是一個簡短的示範。第一個 Activity 設定 requestCode 與 Intent,並覆寫 onActivityResult():
public class MainActivity extends Activity {
private Button button;
private static final int RESULT_CODE = 2;
private static final int RESULT_OK = 1;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
button = (Button) findViewById(R.id.opennext);
button.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View arg0) {
Intent i = new Intent(MainActivity.this, NextActivity.class);
startActivityForResult(i, RESULT_CODE);
}
});
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
switch (requestCode) {
case RESULT_CODE:
if (resultCode == RESULT_OK) {
String returnString = data.getStringExtra("data");
Log.e("data of return", returnString);
}
break;
default:
break;
}
}
}
第二個 Activity 以 setResult() 設定 resultCode 與 Intent,最後呼叫 finish() 讓自己出棧、回到上一個 Activity:
public class NextActivity extends Activity {
private Button button;
private static final int RESULT_OK = 1;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.next);
button = (Button) findViewById(R.id.goback);
button.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View arg0) {
Intent i = new Intent();
i.putExtra("data", "data of goback");
setResult(RESULT_OK, i);
finish();
}
});
}
}
讀過源碼之後,整個過程會清晰許多。
3. 若尚未有頂層 DecorView,則加以建立,並啟動子 Activity;若有進場動畫,也在這裡套用。
在 Android 中,Instrumentation 扮演 Activity 與 ActivityManagerService(AMS)之間的中繼角色。之所以需要這麼一個中介,是因為它本身就是單元測試框架的核心類別,內部擁有大量生命週期與行為的回呼函式,讓測試能從中斷點驗證實作是否符合預期。
這裡先不談自動化測試,只關注 Activity 在 Instrumentation 中的行進。Activity 會呼叫 Instrumentation 的 execStartActivity:
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, 0, null, options);
checkStartActivityResult(result, intent);
} catch (RemoteException e) {
}
return null;
}
首先判斷 mActivityMonitors 是否為空,不為空則走監聽器流程(透過 addMonitor 註冊,用於監控 Activity 是否啟動成功),這部分可以暫時略過。接著工作被遞交給 AMS 處理:
ActivityManagerNative.getDefault()
.startActivity(whoThread, who.getBasePackageName(), intent, ...);
同時 checkStartActivityResult 會檢查 AndroidManifest 中是否已正確註冊。
為什麼要如此層層轉手?這與 Android 的框架設計有關(以下為個人見解)。Android 早期是單一使用者的系統,與傳統 Linux 的多使用者模型不同——Linux 區分系統使用者、根使用者與一般使用者,各有不同的檔案操作權限;Android 則是「一個應用對應一組 UID 與 PID」。值得注意的是,一個應用可以對應一個 UID 但多個 PID;而透過在 manifest 中設定 android:sharedUserId,兩個應用也能共享同一個 UID 來交換資料。
UID、PID 這類資訊由 system_server 中的 UserManagerService、ProcessRecord、PackageManagerService 等元件統一管控。應用必須透過 Binder IPC 跨行程存取 AMS(位於 system_server),集中管理反而能減少頻繁的 IPC 往返,降低資源消耗。當然這只是一個面向,Android 對四大元件模型的強化也是同樣重要的原因。(Android 4.2 之後加入了多使用者機制。)
ActivityManagerNative.getDefault() 這個呼叫其實就是在取用 AMS。看看它的定義:
public abstract class ActivityManagerNative extends Binder implements IActivityManager
這是一個繼承 Binder 的抽象類別,而 IActivityManager 是繼承 IInterface 的介面,AMS 則繼承了 ActivityManagerNative——這不就是標準的 Binder 三件套結構嗎?
private static final SingletongDefault = new Singleton () { protected IActivityManager create() { IBinder b = ServiceManager.getService("activity"); IActivityManager am = asInterface(b); return am; } };
Singleton 是單例模式的封裝,已初始化就直接回傳。由此可以確定,接下來會跨行程把任務轉交給 AMS 的 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());
}
@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);
return mStackSupervisor.startActivityMayWait(caller, -1, callingPackage, intent,
resolvedType, null, null, resultTo, resultWho, requestCode, startFlags,
profilerInfo, null, null, options, userId, null, null);
}
這兩個方法會先透過 Binder 的 native 方法 getCallingUid 取得對應的 userId,然後把工作交給 ActivityStackSupervisor。
這個類別直譯就是「活動堆疊的監督者」,顧名思義,負責監控 Activity 堆疊並做出對應處理。來看 startActivityMayWait:
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, int userId, IActivityContainer iContainer, TaskRecord inTask) {
if (intent != null && intent.hasFileDescriptors()) {
throw new IllegalArgumentException("File descriptors passed in Intent");
}
boolean componentSpecified = intent.getComponent() != null;
intent = new Intent(intent); // 不修改呼叫方的物件
ActivityInfo aInfo = resolveActivity(intent, resolvedType, startFlags, profilerInfo, userId);
ActivityContainer container = (ActivityContainer) iContainer;
synchronized (mService) {
final int realCallingPid = Binder.getCallingPid();
final int realCallingUid = Binder.getCallingUid();
...
final ActivityStack stack;
if (container == null || container.mStack.isOnHomeDisplay()) {
stack = getFocusedStack();
} else {
stack = container.mStack;
}
final long origId = Binder.clearCallingIdentity();
int res = startActivityLocked(caller, intent, resolvedType, aInfo,
voiceSession, voiceInteractor, resultTo, resultWho, requestCode,
callingPid, callingUid, callingPackage, realCallingPid, realCallingUid,
startFlags, options, componentSpecified, null, container, inTask);
Binder.restoreCallingIdentity(origId);
...
return res;
}
}
方法很長,這裡做了裁剪但不影響理解。開頭先取得真正的 PID 與 UID;接著檢查 ActivityContainer 是否為空、其棧頂是否為桌面;然後檢視 configChanges 標誌位並在 ActivityStack 中做相應處理。真正的重活在 startActivityLocked。
startActivityLocked 做了什麼?大致說明我的理解:
final int startActivityLocked(IApplicationThread caller, Intent intent,
String resolvedType, ActivityInfo aInfo, ..., IBinder resultTo,
String resultWho, int requestCode, int callingPid, int callingUid,
String callingPackage, int realCallingPid, int realCallingUid,
int startFlags, Bundle options, boolean componentSpecified,
ActivityRecord[] outActivity, ActivityContainer container, TaskRecord inTask) {
int err = ActivityManager.START_SUCCESS;
ProcessRecord callerApp = null;
if (caller != null) {
callerApp = mService.getRecordForAppLocked(caller);
if (callerApp != null) {
callingPid = callerApp.pid;
callingUid = callerApp.info.uid;
} else {
err = ActivityManager.START_PERMISSION_DENIED;
}
}
ActivityRecord sourceRecord = null;
ActivityRecord resultRecord = null;
if (resultTo != null) {
sourceRecord = isInAnyStackLocked(resultTo);
if (sourceRecord != null) {
if (requestCode >= 0 && !sourceRecord.finishing) {
resultRecord = sourceRecord;
}
}
}
...
err = startActivityUncheckedLocked(r, sourceRecord, voiceSession, voiceInteractor,
startFlags, true, options, inTask);
return err;
}
這裡透過 ActivityThread 取得 PID,並從 manifest 中註冊過的 ActivityInfo 取得對應的 UID。這個方法的核心作用是確定「哪個 Activity 要開啟哪個 Activity」,因此你會看到 resultTo 與 resultWho 被用來辨識來源與結果接收者,並記錄進 ActivityRecord。
ActivityRecord r = new ActivityRecord(mService, callerApp, callingUid, callingPackage,
intent, resolvedType, aInfo, mService.mConfiguration,
resultRecord, resultWho, requestCode, componentSpecified, this, container, options);
resultTo 不為空時,會在顯示中的 ActivityStack 取得棧頂作為來源 Activity;接著由後續邏輯確定要啟動的目標,並最終交給:
startActivityUncheckedLocked(r, sourceRecord, voiceSession, voiceInteractor,
startFlags, true, options, inTask);
這個方法主要處理四種啟動模式的初步判斷,把啟動 flag 套用到目標 Activity。由於篇幅關係,這裡只截取正常啟動(非 singleTop、singleInstance,且非建立第一個 Activity)的關鍵片段:
else if (sourceRecord != null) {
if (!addingToTask && (launchFlags & Intent.FLAG_ACTIVITY_CLEAR_TOP) != 0) {
ActivityRecord top = sourceTask.performClearTaskLocked(r, launchFlags);
keepCurTransition = true;
if (top != null) {
top.deliverNewIntentLocked(callingUid, r.intent);
targetStack.mLastPausedActivity = null;
if (doResume) {
targetStack.resumeTopActivityLocked(null);
}
return ActivityManager.START_DELIVERED_TO_TOP;
}
} else if (!addingToTask && (launchFlags & Intent.FLAG_ACTIVITY_REORDER_TO_FRONT) != 0) {
final ActivityRecord top = sourceTask.findActivityInHistoryLocked(r);
if (top != null) {
top.task.moveActivityToFrontLocked(top);
top.deliverNewIntentLocked(callingUid, r.intent);
if (doResume) {
targetStack.resumeTopActivityLocked(null);
}
return ActivityManager.START_DELIVERED_TO_TOP;
}
}
}
這裡由兩個 Intent 標誌位分支:FLAG_ACTIVITY_CLEAR_TOP 對應「從既有 Activity 開啟新 Activity 時的預設行為」,而 REORDER_TO_FRONT 則是「把歷史上已存在的 Activity 提到最前面」。最後會呼叫目標 ActivityStack 的 resumeTopActivityLocked(null) 繼續往後處理。若對其他啟動模式有興趣,建議自行翻閱源碼。
final boolean resumeTopActivityLocked(ActivityRecord prev, Bundle options) {
if (inResumeTopActivity) {
return false; // 避免遞迴
}
boolean result = false;
try {
inResumeTopActivity = true;
result = resumeTopActivityInnerLocked(prev, options);
} finally {
inResumeTopActivity = false;
}
return result;
}
工作被交給 resumeTopActivityInnerLocked,同樣過長,只關注主流程:
final boolean resumeTopActivityInnerLocked(ActivityRecord prev, Bundle options) {
// 從 mTaskHistory 取得下一個要啟動的 ActivityRecord
ActivityRecord next = topRunningActivityLocked(null);
if (next.app != null && next.app.thread != null) {
next.state = ActivityState.RESUMED;
mResumedActivity = next;
...
try {
next.app.thread.scheduleResumeActivity(next.appToken,
next.app.repProcState, mService.isNextTransitionForward(),
resumeAnimOptions);
} catch (Exception e) {
// 由於行程不存在而拋出異常,實際工作改交給 startSpecificActivityLocked
mStackSupervisor.startSpecificActivityLocked(next, true, false);
return true;
}
}
}
這裡先取 mTaskHistory 尾端,取得下一個 Activity 的 TaskRecord 後嘗試 resume;此時必然拋出異常,實際工作便落到 mStackSupervisor.startSpecificActivityLocked。
看看 startSpecificActivityLocked 怎麼完成收尾:
void startSpecificActivityLocked(ActivityRecord r, boolean andResume, boolean checkConfig) {
// 該 Activity 的應用是否已在運行?
ProcessRecord app = mService.getProcessRecordLocked(
r.processName, r.info.applicationInfo.uid, true);
r.task.stack.setLaunchTime(r);
if (app != null && app.thread != null) {
try {
realStartActivityLocked(r, app, andResume, checkConfig);
return;
} catch (RemoteException e) {
Slog.w(TAG, "Exception when starting activity", e);
}
}
mService.startProcessLocked(r.processName, r.info.applicationInfo, true, 0,
"activity", r.intent.getComponent(), false, false, true);
}
它先判斷 ActivityThread 是否為空,再交給 realStartActivityLocked;後者整理參數後交棒:
app.thread.scheduleLaunchActivity(new Intent(r.intent), r.appToken,
System.identityHashCode(r), r.info, new Configuration(mService.mConfiguration),
r.compat, r.task.voiceInteractor, app.repProcState, r.icicle,
r.persistentState, results, newIntents, !andResume,
mService.isNextTransitionForward(), profilerInfo);
app.thread 是 IApplicationThread,這裡又進行了一次 IPC,把參數交回 ActivityThread 所在行程。
這兩個類別都在處理 Activity 的任務堆疊,也就是把新啟動或即將啟動的 Activity 放到棧頂。但只順著上面的流程讀,仍容易霧裡看花,這裡做個整理。
顧名思義,ActivityStackSupervisor 負責監督 ActivityStack,並在其中協調 TaskRecord、ActivityStack、ActivityRecord(以及 ProcessRecord)之間的關係。
翻開源碼會發現,ActivityStack 並沒有使用真正的 Stack 資料結構,而是:
/** The back history of all previous (and possibly still running) activities. */ private ArrayListmTaskHistory = new ArrayList ();
也就是透過操作這個 TaskRecord 串列來模擬任務堆疊的效果。註解寫得很清楚:它保存了回退歷程中所有先前的活動,包含仍在運行中的部分。而 TaskRecord 內部也有一個類似的串列:
/** List of all activities in the task arranged in history order */ final ArrayList mActivities;
這裡放的是任務中所有活動,也就是我們直覺認知的「任務堆疊內容」。
回頭看它們如何貫穿整個流程。在 startActivityLocked 中,值得注意的兩個參數是 IBinder resultTo 與 String resultWho,分別指定了來源 Activity 與目標 Activity:
if (resultTo != null) {
sourceRecord = isInAnyStackLocked(resultTo);
if (sourceRecord != null && requestCode >= 0 && !sourceRecord.finishing) {
resultRecord = sourceRecord;
}
}
ActivityRecord isInAnyStackLocked(IBinder token) {
int numDisplays = mActivityDisplays.size();
for (int displayNdx = 0; displayNdx < numDisplays; ++displayNdx) {
ArrayList stacks = mActivityDisplays.valueAt(displayNdx).mStacks;
for (int stackNdx = stacks.size() - 1; stackNdx >= 0; --stackNdx) {
final ActivityRecord r = stacks.get(stackNdx).isInStackLocked(token);
if (r != null) {
return r;
}
}
}
return null;
}
接著建立代表目標的 ActivityRecord,兩端的資訊就齊備了。那麼 ActivityRecord 在其中扮演什麼角色?它負責保存 Activity 運行時的資訊:誰啟動了它、它啟動了誰、屬於哪個 PID、對應哪個 TaskRecord 等等。這裡要與 manifest 標籤對應的 ActivityInfo 明確區分開來。
確定好「從哪裡來、往哪裡去」之後,startActivityUncheckedLocked 中還有這一段:
final TaskRecord sourceTask = sourceRecord.task;
targetStack = sourceTask.stack;
targetStack.moveToFront();
final TaskRecord topTask = targetStack.topTask();
if (topTask != sourceTask) {
targetStack.moveTaskToFrontLocked(sourceTask, r, options);
} else {
mWindowManager.moveTaskToTop(topTask.taskId);
}
moveToFront() 就是取得 mTaskHistory 的頂端(串列尾端)。接著 performClearTaskLocked 會比對 TaskRecord 中所有 Activity 的 realActivity,找出可重複利用的那一個:
final ActivityRecord performClearTaskLocked(ActivityRecord newR, int launchFlags) {
int numActivities = mActivities.size();
for (int activityNdx = numActivities - 1; activityNdx >= 0; --activityNdx) {
ActivityRecord r = mActivities.get(activityNdx);
if (r.realActivity.equals(newR.realActivity)) {
// 把覆蓋在它上面的 Activity 全部 finish 掉
...
return ret;
}
}
return null;
}
最後 mWindowManager.setAppStartingWindow 會準備好後續 attach Window 時所需的參數。整體流程大致是:找出堆疊中的來源 Activity,建立代表目標 Activity 的 ActivityRecord,剩下的就交回 ActivityThread 完成實際建立。

從上圖也可以看出,啟動與被啟動的 Activity 之間其實是一個單向鏈結串列的資料模型。
主要工作回到原本的行程完成,此時呼叫的是 Application 內部類別的 scheduleLaunchActivity:
public final void scheduleLaunchActivity(Intent intent, IBinder token, int ident,
ActivityInfo info, Configuration curConfig, CompatibilityInfo compatInfo,
IVoiceInteractor voiceInteractor, int procState, Bundle state,
PersistableBundle persistentState, List pendingResults,
List pendingNewIntents, boolean notResumed, boolean isForward,
ProfilerInfo profilerInfo) {
updateProcessState(procState, false);
ActivityClientRecord r = new ActivityClientRecord();
r.token = token;
r.ident = ident;
r.intent = intent;
r.activityInfo = info;
r.state = state;
...
sendMessage(H.LAUNCH_ACTIVITY, r);
}
接下來丟給 Handler 的 handleLaunchActivity 集中處理,Activity 的七大生命週期幾乎都在這裡完成:
private void handleLaunchActivity(ActivityClientRecord r, Intent customIntent) {
unscheduleGcIdler();
mSomeActivitiesChanged = true;
handleConfigurationChanged(null, null);
Activity a = performLaunchActivity(r, customIntent);
if (a != null) {
r.createdConfig = new Configuration(mConfiguration);
handleResumeActivity(r.token, false, r.isForward,
!r.activity.mFinished && !r.startsNotResumed);
...
} else {
ActivityManagerNative.getDefault()
.finishActivity(r.token, Activity.RESULT_CANCELED, null, false);
}
}
performLaunchActivity 與 handleResumeActivity 分別負責 onCreate、onStart、onResume 三個環節(onResume 與 Window 的掛載在上一篇已說明)。這裡只聚焦 Activity 是如何被建立的。
performLaunchActivity 大致分成幾個步驟。第一步,從 ActivityRecord 取出啟動所需的元件資訊:
ActivityInfo aInfo = r.activityInfo;
if (r.packageInfo == null) {
r.packageInfo = getPackageInfo(aInfo.applicationInfo, r.compatInfo,
Context.CONTEXT_INCLUDE_CODE);
}
ComponentName component = r.intent.getComponent();
if (component == null) {
component = r.intent.resolveActivity(mInitialApplication.getPackageManager());
r.intent.setComponent(component);
}
第二步,透過 Instrumentation 的 newActivity,以類別載入器建立 Activity 實例:
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();
第三步,由 LoadedApk 的 makeApplication 嘗試建立 Application:
public Application makeApplication(boolean forceDefaultAppClass,
Instrumentation instrumentation) {
if (mApplication != null) {
return mApplication;
}
Application app = null;
String appClass = mApplicationInfo.className;
if (forceDefaultAppClass || (appClass == null)) {
appClass = "android.app.Application";
}
ContextImpl appContext = ContextImpl.createAppContext(mActivityThread, this);
app = mActivityThread.mInstrumentation.newApplication(
getClassLoader(), appClass, appContext);
appContext.setOuterContext(app);
mActivityThread.mAllApplications.add(app);
mApplication = app;
if (instrumentation != null) {
instrumentation.callApplicationOnCreate(app);
}
return app;
}
若已建立過則直接回傳原有物件,同樣依賴類別載入器;否則最終由 instrumentation.callApplicationOnCreate(app) 觸發建立。
第四步,建立 ContextImpl 並透過 attach 完成重要資料的初始化,例如 Window 的掛載:
Context appContext = createBaseContextForActivity(r, activity);
CharSequence title = r.activityInfo.loadLabel(appContext.getPackageManager());
Configuration config = new Configuration(mCompatConfiguration);
activity.attach(appContext, this, getInstrumentation(), r.token, r.ident,
app, r.intent, r.activityInfo, title, r.parent, r.embeddedID,
r.lastNonConfigurationInstances, config, r.voiceInteractor);
第五步,在 mInstrumentation.callActivityOnCreate 中呼叫 performCreate:
final void performCreate(Bundle icicle) {
onCreate(icicle);
mActivityTransitionState.readState(icicle);
performCreateCommon();
}
第六步,來到 onCreate,完成生命週期的第一步:
protected void onCreate(@Nullable Bundle savedInstanceState) {
if (mLastNonConfigurationInstances != null) {
mAllLoaderManagers = mLastNonConfigurationInstances.loaders;
}
if (mActivityInfo.parentActivityName != null) {
if (mActionBar == null) {
mEnableDefaultActionBarUp = true;
} else {
mActionBar.setDefaultDisplayHomeAsUpEnabled(true);
}
}
if (savedInstanceState != null) {
Parcelable p = savedInstanceState.getParcelable(FRAGMENTS_TAG);
mFragments.restoreAllState(p, mLastNonConfigurationInstances != null
? mLastNonConfigurationInstances.fragments : null);
}
mFragments.dispatchCreate();
getApplication().dispatchActivityCreated(this, savedInstanceState);
mCalled = true;
}
在這裡建立 ActionBar、讀取 configChanges 標誌位、還原先前存好的 savedInstanceState、綁定 Fragment,並觸發 Application 中 ActivityLifecycleCallbacks 的回呼。
至此,Activity 的整個啟動流程就走完了。
這篇文章的思路整理,受益於《Android 開發藝術探索》一書的啟發與觀念上的修正,特此致謝。最後也要提醒讀者:文中內容是個人學習過程中的理解與記錄,不保證百分之百正確,若有疏漏之處,歡迎指正。
安卓手機錄屏並轉成 GIF 的兩種實用方案
寫技術文的時候,一張好的動態演示往往比一堆靜態截圖更說得清楚。這段時間試了幾種給手機錄屏的方式,這裡挑兩個自己用得最順手的分享出來:(1)配好 adb 環境後,用 CMD
Android 入門:Gallery 控件的基礎用法實例
Gallery 是 Android 裡相當好用的看图控件,能大幅減少開發看图功能的工作量,而且效果本身就頗為美觀。本文的實例有一個重點:用反射機制動態讀取資源中的圖片,而
微信怎麼分享音樂?把喜歡的歌分享到朋友圈的圖文教學
逛朋友圈時常看到朋友分享歌曲,點下去就能直接播放,自己也想試試卻不知道從何下手。其實流程很短,只要音樂 App 本身支援分享就能完成。以下以 iPhone 上的網易雲音樂
Android 圖片異步加載實踐:用多線程打造不錯位、不閃動的列表
從最直白的做法開始 所謂異步,說到底就是多任務、多線程。而多線程向來伴隨各種坑,我們一步步踩過去。 先建一個類 ImageLoaderWithoutCaches——顧名思