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

Android 系列教程:Activity 生命週期完全解析

編輯:關於 Android 開發

Activity 的生命週期

上一節我們搞清楚了 Activity 是什麼,但還有兩個問題沒回答:為什麼我們創建 Activity 時總要覆寫 onCreate()?為什麼有些資料要在 onPause() 裡保存?答案都藏在生命週期裡——也就是一個 Activity 從誕生到消亡,究竟會經過哪些狀態。下面用一個實例把它跑一遍。

一、生命週期方法有哪些

Android 提供了大量生命週期方法,常用的有 onCreate、onStart、onResume、onPause、onStop、onDestroy,這些屬於粗粒度的方法,從命名就能看出它們在什麼時候被呼叫。

此外還有 onPostCreate、onPostResume 之類的細粒度方法,需要更精細控制時可以查 API 文檔選用。

二、實測執行順序

新建一個 HelloWorld 專案,把上述方法全部覆寫並打點日誌,順序自然一目了然。

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>

2. 第二個頁面布局 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>

3. SecondActivity——別忘了在 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) {
                // 關閉當前 Activity
                finish();
            }
        });
    }

    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. HelloWorld

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
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) {
                // 跳轉到 SecondActivity
                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");
    }
}

5. 跑起來看日誌

程式啟動時,日誌依次輸出 onCreate → onStart → onResume。可見打開一個 Activity 的順序就是這三步。

接著點擊「打開第二個 Activity」,日誌變化很有意思:Android 會先執行 HelloWorld 的 onPause(),然後才依次執行 SecondActivity 的 onCreate → onStart → onResume。等 SecondActivity 完全呈現在螢幕上,才轮到 HelloWorld 的 onStop → onDestroy,把它從 Activity 棧中移除銷毀。

這裡要特別留意 finish():正因為呼叫了它,HelloWorld 才會被棧移除。所以當你按返回鍵時,回不到 HelloWorld,而是直接回到應用列表。如果把 finish() 拿掉,返回鍵就會把你送回上一頁——這正是 Activity 棧在起作用。

三、各方法職責總結

根據上面的實驗,一個 Activity 啟動時走 onCreate → onStart → onResume,離開時走 onPause → onStop → onDestroy,這就是它完整的一生。各方法的定位如下:

  • onCreate():創建時呼叫,用於初始化。帶一個 Bundle 參數,可以讀取以前保存的狀態。
  • onStart():Activity 對用戶可見時呼叫。
  • onResume():Activity 開始與用戶交互時呼叫,此時它位於棧頂。
  • onPause():Activity 被暫停時呼叫,是保存持久狀態的最後機會——因為 onPause 執行完之前,Android 不會結束託管該 Activity 的進程,而之後進程隨時可能被回收。
  • onStop():Activity 被停止或變得不可見時呼叫。
  • onDestroy():Activity 從內存中移除時呼叫,通常發生在執行 finish() 或系統回收內存時。

把這六個方法的職責記牢,你在寫任何 Android 應用時都不會再為「該在哪裡初始化、該在哪裡存資料」糾結。onCreate 準備、onResume 調整、onPause 收尾保存——這三句口訣基本涵蓋了九成的日常場景。

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