面試—Activity生命周期

activity_lifecycle.png

onCreate()

系統(tǒng)第一次創(chuàng)建Activity時調(diào)用,處理Activity整個生命周期僅發(fā)生一次的應用初始化操作,例如綁定數(shù)據(jù)到List中,初始類成員。onCreate()方法接收一個Bundle參數(shù)savedInstanceState,保存了Activity之前的狀態(tài)。如果Activity之前沒有被創(chuàng)建過,Bundle是null。

TextView textView;

// some transient state for the activity instance
String gameState;

@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) {
        gameState = 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
    textView = (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) {
    textView.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, gameState);
    outState.putString(TEXT_VIEW_KEY, textView.getText());

    // call superclass to save any view hierarchy
    super.onSaveInstanceState(outState);
}

onStart()

onStart()讓Activity對用戶可見

onResume()

進入Resumed 狀態(tài)時,Activity進入前臺,用戶與Activity交互(interacts )。Activity一直保持在這個狀態(tài)直到失去焦點(比如接入電話、跳轉(zhuǎn)到另一個Activity、設(shè)備屏幕關(guān)閉)

當阻礙事件發(fā)生時,activity 進入 Paused state,系統(tǒng)觸發(fā)onPause()方法。

當Activity從Paused state 返回到Resumed state,系統(tǒng)會再次調(diào)用onResume()。因此在onResume()的初始化操作,在onPause()要釋放掉。

onPause()

當用戶離開Activity的時候調(diào)用(這并不意味著Activity被銷毀),這說明Activity不再處于前臺(盡管它仍然保持可見在multi-window mode)。一些讓Activity進入 paused state的例子:
1.一些事件打斷了App的運行,如在onResume()部分提到的例子。這是最常見的。
2.在 Android 7.0版本以上, 在multi-window 模式下運行多個App,因為只能由一個App獲得焦點,系統(tǒng)讓其他App處于paused狀態(tài)。
3.一個新的,半透明的Activity打開(如Dialog)。盡管Activity部分可見但沒有焦點,處于paused 狀態(tài)。

在onPause()里可停止任何非前臺狀態(tài)不需要的功能,如停止相機預覽。

在onPause()釋放系統(tǒng)資源,處理 sensors(像GPS),或者任何影響電池續(xù)航的。

onPause()執(zhí)行時間非常短,沒有提供足夠的時間去處理保存操作,因此,不要在這里保存應用或用戶數(shù)據(jù)、調(diào)用網(wǎng)絡(luò)、或執(zhí)行數(shù)據(jù)庫操作,類似的工作在onPause()方法結(jié)束前不能完成。這些可以在onStop()方法調(diào)用。

onStop()

當Acivity對用戶不再可見時,進入了Stopped state,系統(tǒng)回調(diào)onStop()。當一個新啟動的Activity覆蓋了整個屏幕,會觸發(fā)。 當Activity結(jié)束運行時也會觸發(fā)。

在onStop()可以釋放掉當Activity不可見時不需要的資源。例如停止動畫、將定位更新從fine-grained切換到coarse-grained。

@Override
protected void onStop() {
    // call the superclass method first
    super.onStop();

    // save the note's current draft, because the activity is stopping
    // and we want to be sure the current note progress isn't lost.
    ContentValues values = new ContentValues();
    values.put(NotePad.Notes.COLUMN_NAME_NOTE, getCurrentNoteText());
    values.put(NotePad.Notes.COLUMN_NAME_TITLE, getCurrentNoteTitle());

    // do this update in background on an AsyncQueryHandler or equivalent
    asyncQueryHandler.startUpdate (
            mToken,  // int token to correlate calls
            null,    // cookie, not used here
            uri,    // The URI for the note to update.
            values,  // The map of column names and new values to apply to them.
            null,    // No SELECT criteria are used.
            null     // No WHERE columns are used.
    );
}

當activity 進入 Stopped state , activity對象還保留在內(nèi)存中, 它保存所有狀態(tài)和成員信息,但是沒綁定到window manager。當Activity resume,activity恢復這些信息。系統(tǒng)同時追蹤每個View對象的狀態(tài),因此EditText輸入的文本依然會保存,你不需要再去保存和恢復。

Activity從stopped state返回與用戶交互,會調(diào)用onRestart()。如果結(jié)束Activity會調(diào)用onDestroy()。

onDestroy()

activity 被銷毀前調(diào)用onDestroy()。下面情況會觸發(fā):

1.Acitvity正在結(jié)束(用戶退出Activity,或者調(diào)用finish())

2.系統(tǒng)因為configuration 改變 (如設(shè)備旋轉(zhuǎn)或者multi-window mode)臨時銷毀Activity

在onDestroy()需要釋放在早期生命周期沒有釋放掉的資源。

當 Activity A 啟動 Activity B 時生命周期的變化

  1. Activity A 的 onPause()方法執(zhí)行。
    2.Activity B 的 onCreate()、onStart()、onResume()方法依次執(zhí)行(Activity B獲得焦點)
    3.Activity A 不再可見,它的onStop()方法執(zhí)行。
    (如果Activity B是一個半透明的Dialog,則Activity A只執(zhí)行onPause(),onStop()不會執(zhí)行)
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容