Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲
您现在的位置: Android教程網 >> Android系統教程 >  >> Android 技術 >> Android 開發 >> 進階開發

Android 系列教學:Activity 生命週期實戰演示

編輯:進階開發

Activity 的生命週期是 Android 開發的核心概念之一。本文透過一個可實際運行的範例,示範各生命週期方法的執行順序,幫助你真正理解 Activity 從建立到銷毀的完整歷程。

一、Activity 的生命週期方法

Android 提供了許多生命週期方法,最常用的是粗粒度的六個:onCreate()、onStart()、onResume()、onPause()、onStop()、onDestroy()。從命名即可大致推知它們的呼叫時機。若需要更細緻的控制,另有 onPostCreate()、onPostResume() 等細粒度方法可參考 API 文件。

二、透過範例觀察執行順序

我們建立一個含兩個 Activity 的專案,在各生命週期方法中印出日誌,藉此觀察呼叫順序。

主畫面 main.xml:

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

第二個 Activity:

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

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Log.v(TAG, "onCreate");
        setContentView(R.layout.second);
        Button btnExit = (Button) findViewById(R.id.exit);
        btnExit.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                finish(); // 關閉當前 Activity
            }
        });
    }

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

主 Activity:

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

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Log.v(TAG, "onCreate");
        setContentView(R.layout.main);
        Button btnSecond = (Button) findViewById(R.id.second);
        btnSecond.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                startActivity(new Intent(HelloWorld.this, SecondActivity.class));
                finish(); // 關閉當前 Activity
            }
        });
    }

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

三、執行結果分析

程式啟動時,日誌顯示的順序為 onCreate() → onStart() → onResume(),這就是打開一個 Activity 時週期方法的執行順序。

接著點擊「打開第二個 Activity」按鈕,日誌輸出如下:

可以觀察到:當 HelloWorld 啟動 SecondActivity 時,Android 會先執行 HelloWorld 的 onPause(),接著依序執行 SecondActivity 的 onCreate() → onStart() → onResume()。待 SecondActivity 顯示於螢幕後,才再次執行 HelloWorld 的 onStop() → onDestroy(),將它從 Activity 堆疊中移除並銷毀。

這裡特別值得一提的是 HelloWorld 中的 finish():正因為執行了它,HelloWorld 才會從堆疊中移除銷毀,因此當你按「返回」鍵時,就回不到 HelloWorld 畫面,而是直接回到 Android 的應用程式列表。

四、總結:生命週期方法的作用

由此可見,一個 Activity 啟動時依序執行 onCreate() → onStart() → onResume(),結束時則執行 onPause() → onStop() → onDestroy(),這便構成了一個完整的生命週期。各方法的責任如下:

  • onCreate():建立 Activity 時呼叫,用於初始化,並可透過 Bundle 參數存取先前儲存的狀態。
  • onStart():Activity 在螢幕上對使用者可見時呼叫。
  • onResume():Activity 開始與使用者互動時呼叫,此時它位於堆疊頂端。
  • onPause():Activity 被暫停時呼叫,適合在此做清理與持久狀態的儲存——這是最後的機會,因為 onPause 完成後,托管 Activity 的行程隨時可能被結束。
  • onStop():Activity 被停止或變為不可見時呼叫。
  • onDestroy():Activity 從記憶體中移除時呼叫,通常發生在執行 finish() 或系統回收記憶體時。

因此,我們應在 onCreate() 中準備好所需資源(初始化),在 onResume() 中對介面做調整,並在 onPause() 中完成清理與狀態保存工作。理解這套週期,是寫出穩定、資源管理得宜的 Android 應用的基礎。

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