系統(tǒng)提供了 6 個(gè)回調(diào)方法來(lái)處理 Activity 生命周期中不同的狀態(tài):
onCreate(), onStart(), onResume(), onPause(), onStop(), and onDestroy()
系統(tǒng)殺死一個(gè) APP 進(jìn)程時(shí)携取,有可能進(jìn)程依然存在于內(nèi)存中版保,這取決于當(dāng)時(shí) Activity 的狀態(tài)。
onCreate(Bundle savedInstanceState)
這個(gè)方法只在 Acitvity 啟動(dòng)時(shí)調(diào)用一次先煎,通常用來(lái)設(shè)置布局視圖setContentView()
,和初始化變量楞慈。
savedInstanceState 參數(shù)記錄了上次 Activity 的狀態(tài)(onSaveInstanceState(Bundle outState)
方法里保存的狀態(tài))
恢復(fù)狀態(tài)可以在 onCreate 和 onRestoreInstanceState 里完成旺嬉。
TextView mTextView;
// some transient state for the activity instance
String mGameState;
@Override
public void onCreate(Bundle savedInstanceState) {
// call the super class onCreate to complete the creation of activity like
// the view hierarchy
super.onCreate(savedInstanceState);
// recovering the instance state
if (savedInstanceState != null) {
mGameState = savedInstanceState.getString(GAME_STATE_KEY);
}
// set the user interface layout for this activity
// the layout file is defined in the project res/layout/main_activity.xml file
setContentView(R.layout.main_activity);
// initialize member TextView so we can manipulate it later
mTextView = (TextView) findViewById(R.id.text_view);
}
// This callback is called only when there is a saved instance that is previously saved by using
// onSaveInstanceState(). We restore some state in onCreate(), while we can optionally restore
// other state here, possibly usable after onStart() has completed.
// The savedInstanceState Bundle is same as the one used in onCreate().
@Override
public void onRestoreInstanceState(Bundle savedInstanceState) {
mTextView.setText(savedInstanceState.getString(TEXT_VIEW_KEY));
}
// invoked when the activity may be temporarily destroyed, save the instance state here
@Override
public void onSaveInstanceState(Bundle outState) {
outState.putString(GAME_STATE_KEY, mGameState);
outState.putString(TEXT_VIEW_KEY, mTextView.getText());
// call superclass to save any view hierarchy
super.onSaveInstanceState(outState);
}
onStart
這個(gè)方法代表 Acitivity 已經(jīng)準(zhǔn)備好進(jìn)入前臺(tái)了败潦,可以和用戶交互了。通常這里可以放置初始化用戶 UI 的代碼准脂。
onResume
這個(gè)狀態(tài)下 APP 處于與用戶的交互中劫扒,并一直保持到失去焦點(diǎn),例如來(lái)電狸膏、息屏沟饥、用戶轉(zhuǎn)到另一個(gè) APP 等。APP 可能會(huì)在 Resume 和 Pause 狀態(tài)之間來(lái)回跳轉(zhuǎn)湾戳。
onPause
Activity 失去焦點(diǎn)后進(jìn)入暫停狀態(tài)贤旷,恢復(fù)后從新進(jìn)入 resume 狀態(tài)。這個(gè)方法執(zhí)行時(shí)間應(yīng)該很短砾脑,不應(yīng)該在這里執(zhí)行一些耗時(shí)的工作幼驶,例如保存用戶數(shù)據(jù)、執(zhí)行網(wǎng)絡(luò)操作韧衣、處理數(shù)據(jù)庫(kù)事務(wù)等盅藻,這些工作可以在 onStop
里完成。該方法完成后畅铭,它有可能調(diào)用 onResume
或onStop
氏淑,取決于 Activity 是被重新恢復(fù)或者變得完全不可見。
onStop
這個(gè)方法在 Activity 變得不可見硕噩,或者 APP 即將終止時(shí)調(diào)用假残。在這里可以釋放一些 APP 不再需要的資源、保存數(shù)據(jù)等操作炉擅。在這個(gè)狀態(tài)辉懒, Acitvity 任然在內(nèi)存里,因此不需要做數(shù)據(jù)保存和恢復(fù)坑资。系統(tǒng)可能因?yàn)樾枰獌?nèi)存而隨時(shí)銷毀 Activity耗帕。這個(gè)方法結(jié)束后有兩個(gè)選擇:onRestart()
或 onDestroy()
onDestroy
onDestroy 的調(diào)用分兩種情況:
由于用戶完全關(guān)閉 Activity,或者 onFinish 被調(diào)用袱贮。
由于設(shè)備配置改變(如旋轉(zhuǎn)方向)臨時(shí)銷毀 Acitvity仿便,然后重建。
通過(guò) isFinishing
方法可以區(qū)分這兩種情況攒巍。第一種情況 onCleared()
會(huì)被調(diào)用嗽仪。第二種情況onCreate()
被調(diào)用。
Activity 狀態(tài)與內(nèi)存釋放的關(guān)系
Likelihood of being killed | Process state | Activity state |
---|---|---|
Least | Foreground (having or about to get focus) | Created, Started,Resumed |
More | Background (lost focus) | Paused |
Most | Background (not visible) | Stopped, Empty, Destroyed |
系統(tǒng)不會(huì)單獨(dú)釋放 Acitvity柒莉,而是釋放整個(gè) 進(jìn)程闻坚。
保護(hù)和恢復(fù) UI 狀態(tài)
ViewModel, onSaveInstanceState()
當(dāng)系統(tǒng)因內(nèi)存壓力或配置改變而關(guān)閉 Acitivity 時(shí)會(huì)自動(dòng)保存狀態(tài),恢復(fù)時(shí)自動(dòng)重建兢孝。狀態(tài)保存在 Bundle 對(duì)象里窿凤,但它只能保存簡(jiǎn)單的數(shù)據(jù)仅偎,會(huì)占用系統(tǒng)內(nèi)存,如果要保存大量數(shù)據(jù)雳殊,需要用onSaveInstanceState(), ViewModel class
將數(shù)據(jù)保存到本地存儲(chǔ)橘沥。
恢復(fù)對(duì)象可以在onCreate() 和 onRestoreInstanceState()
里,前置需要判斷 Bundle 是否為空夯秃,后者不需要座咆,只有系統(tǒng)有 state 要恢復(fù)時(shí)它才在onStart
之后調(diào)用。
從一個(gè) Acitivity 啟動(dòng)另一個(gè) Activity
通過(guò)傳遞一個(gè) Intent 對(duì)象給startActivity() 或 startActivityForResult()
創(chuàng)建仓洼。
使用startActivityForResult()
創(chuàng)建帶返回值的 Acitvity介陶,用 onActivityResult(int, int, Intent)
方法接收結(jié)果紊遵,在子 Acitvity 中用 setResult(int)
設(shè)置返回結(jié)果非洲。
public class MyActivity extends Activity {
// ...
static final int PICK_CONTACT_REQUEST = 0;
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_DPAD_CENTER) {
// When the user center presses, let them pick a contact.
startActivityForResult(
new Intent(Intent.ACTION_PICK,
new Uri("content://contacts")),
PICK_CONTACT_REQUEST);
return true;
}
return false;
}
protected void onActivityResult(int requestCode, int resultCode,
Intent data) {
if (requestCode == PICK_CONTACT_REQUEST) {
if (resultCode == RESULT_OK) {
// A contact was picked. Here we will just display it
// to the user.
startActivity(new Intent(Intent.ACTION_VIEW, data));
}
}
}
}
一個(gè) Acitvity 打開另一個(gè) Activity 時(shí)回調(diào)方法執(zhí)行順序
- Activity A's onPause() method executes.
- Activity B's onCreate(), onStart(), and onResume() methods execute in sequence. (Activity B now has user focus.)
- Then, if Activity A is no longer visible on screen, its onStop() method executes.