Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲

Android 系列教程之 Activity 的生命週期

編輯:關於 Android 程式設計

在〈Android 系列教程之 Android 專案的目錄結構〉中我們談過什麼是 Activity。但有一個問題一直沒解釋清楚:為什麼我們每次建立 Activity 時,都要覆寫 onCreate()?為什麼會建議在 onPause() 中保存資料?

要弄懂這些,就必須先理解 Activity 的生命週期——一個 Activity 從誕生到死亡,究竟會經過哪些狀態。下面用一個實作來觀察。

一、粗粒度的生命週期方法

Android 提供了大量生命週期回呼,除了常用的 onCreate、onPause、onResume 之外,還有 onPostCreate、onPostResume 等更細緻的方法(可查 API 文件)。本文聚焦在幾個「粗粒度」的關鍵方法,因為它們決定了 Activity 的主要狀態轉換:

  • onCreate()
  • onStart()
  • onResume()
  • onPause()
  • onStop()
  • onDestroy()

光看名字大致能猜到時機,但要真正記住順序,還是得親眼觀察一次。

二、動手驗證執行順序

1. 建立專案與兩個版面

第一個版面 activity_main.xml,放一段文字與一個跳轉按鈕:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" >

    <TextView
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="第一個Activity" />

    <Button
        android:id="@+id/second"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="打開第二個Activity" />

</LinearLayout>

第二個版面 second.xml,放文字與一個退出按鈕:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" >

    <TextView
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="第二個Activity" />

    <Button
        android:id="@+id/exit"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="退出" />

</LinearLayout>

2. 新增 SecondActivity 並記得註冊

新建 Activity 之後,務必在 AndroidManifest.xml 中宣告,否則執行時會直接崩潰。

import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;

public class SecondActivity extends Activity {
    private final static String TAG = "SecondActivity";

    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.second);

        Button btnExit = (Button) findViewById(R.id.exit);
        btnExit.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View arg0) {
                finish(); // 關閉當前 Activity
            }
        });
    }

    protected void onStart() {
        super.onStart();
        Log.v(TAG, "onStart");
    }

    protected void onResume() {
        super.onResume();
        Log.v(TAG, "onResume");
    }

    protected void onPause() {
        super.onPause();
        Log.v(TAG, "onPause");
    }

    protected void onStop() {
        super.onStop();
        Log.v(TAG, "onStop");
    }

    protected void onDestroy() {
        super.onDestroy();
        Log.v(TAG, "onDestroy");
    }
}

3. 在第一個 Activity 中同樣埋入日誌

import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;

public class HelloWorld extends Activity {
    private final static String TAG = "HelloWorld";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        Button btnSecond = (Button) findViewById(R.id.second);
        btnSecond.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View arg0) {
                startActivity(new Intent(HelloWorld.this, SecondActivity.class));
                finish(); // 關閉當前 Activity
            }
        });
    }

    protected void onStart()   { super.onStart();   Log.v(TAG, "onStart"); }
    protected void onResume()  { super.onResume();  Log.v(TAG, "onResume"); }
    protected void onPause()   { super.onPause();   Log.v(TAG, "onPause"); }
    protected void onStop()    { super.onStop();    Log.v(TAG, "onStop"); }
    protected void onDestroy() { super.onDestroy(); Log.v(TAG, "onDestroy"); }
}

4. 執行並觀察日誌

App 啟動時,日誌依序輸出:

onCreate → onStart → onResume

由此可見,打開一個 Activity 時,生命週期方法的執行順序是 onCreate() → onStart() → onResume()。

點擊「打開第二個 Activity」按鈕後,日誌變成:

HelloWorld: onPause
SecondActivity: onCreate → onStart → onResume
HelloWorld: onStop → onDestroy

這個順序很有含意:Android 會先呼叫原本 Activity 的 onPause(),然後才建立並啟動新 Activity,等 SecondActivity 真正顯示到螢幕上,最後才把 HelloWorld 走到 onStop() 與 onDestroy()。

值得特別注意的是程式碼裡那個 finish():正因為呼叫了它,HelloWorld 才會從 Activity 堆疊中移除並銷毀。如果沒有呼叫 finish(),按返回鍵時你會回到 HelloWorld 的畫面;而因為呼叫了,按返回鍵就直接回到系統的應用程式列表。

三、結論:完整生命週期

綜合上述觀察,一個 Activity 的生命週期是:

  • 啟動:onCreate() → onStart() → onResume()
  • 離開/結束:onPause() → onStop() → onDestroy()

四、每個方法該做什麼

理解了順序,就能理解為什麼官方對每個方法有那樣的建議:

  • onCreate():Activity 建立時呼叫,用於初始化——設定版面、初始化資料、讀取之前保存的狀態。參數中的 Bundle 可以取回先前儲存的狀態值(首次啟動時為 null)。
  • onStart():Activity 對使用者變得可見時呼叫,但此時還在後方,無法互動。
  • onResume():Activity 開始與使用者互動時呼叫,這時它位於 Activity 堆疊的頂端。要在這裡做「每次回到前景都要重新整理」的工作,例如重新整理列表、恢復動畫。
  • onPause():Activity 被暫停時呼叫,也就是「即將離開使用者視線」的時刻。這裡要進行清理與保存持久狀態,因為這是你在可靠時機中的最後機會——onPause() 執行完之前,系統保證不會結束你的進程;而一旦它完成,進程隨時可能被回收。
  • onStop():Activity 完全被停止、對使用者不可見時呼叫。較重的資源釋放可以放在這裡。
  • onDestroy():Activity 從記憶體中移除時呼叫,通常發生在執行 finish() 或系統回收資源時。

五、實務上的兩個提醒

第一,不要在 onPause() 裡做耗時工作。它是在 Activity 切換的關鍵路徑上被呼叫的,若你在這裡寫檔、做網路請求或大量運算,會直接影響畫面切換的流暢度,甚至引發 ANR。耗時任務應該交給 onStop() 或背景執行緒。

第二,別假設 onDestroy() 一定會被呼叫。系統在記憶體吃緊時可能直接回收進程而不走完整的銷毀流程。因此真正必須保存的資料,不能只依賴 onDestroy();正確做法是搭配 onSaveInstanceState() 保存 UI 狀態,並把持久性資料即時寫入資料庫或偏好設定。

把這幾個方法的職責記清楚,你在寫 Activity 時就不會再出現「旋轉螢幕後輸入的內容消失」、「回到頁面時資料重複載入」這類看似莫名的問題——它們幾乎都是生命週期理解不足造成的。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved