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

Bundle 到底是什麼?從源碼看它與 Intent 的關係

編輯:關於 Android 程式設計

不時回頭看看自己的 Android 學習與實踐路,總會發現一些以前不明白的、現在清楚緣由了;也會發現一些當初沒怎麼留意的東西,現在看到了就很想深入了解。

比如 Bundle。

每個 Activity 生命週期裡,第一個被呼叫的是 onCreate:

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

這個 savedInstanceState 參數是 IDE 自動補上的,多數時候我們連看都不看它一眼。今天就把 Bundle 的作用,以及它和 Intent 的關係一次講清楚。

一、Bundle 是什麼

官方定義是「A mapping from String values to various Parcelable types」——一句話,鍵值對的集合。

繼承關係很單純:java.lang.Object → android.os.Bundle,而 Bundle 是一個 final 類別:

public final class Bundle extends Object implements Parcelable, Cloneable

它實作了 Parcelable,這正是它能被跨進程傳遞的原因。最常見的用途就是作為兩個 Activity 之間的溝通管道。

用法一:裝載資料

Bundle mBundle = new Bundle();
mBundle.putString("DataTag", "要傳過去的數據");

Intent intent = new Intent();
intent.setClass(MainActivity.this, Destion.class);
intent.putExtras(mBundle);

用法二:目標 Activity 解析

Bundle bundle = getIntent().getExtras();   // 取得傳過來的 bundle
String data = bundle.getString("DataTag"); // 讀出資料

二、Intent 與 Bundle 的關係

Intent 的含義這裡就跳過,直接看兩者的比較。

在兩個 Activity 之間傳遞資料,附加方式有兩種:一種是 intent.putExtra(),另一種是先 bundle.putXxx(),再呼叫 intent.putExtras(bundle)。本質上兩者完全一樣。

先看 Intent 的 putExtra:

public Intent putExtra(String name, boolean value) {
    if (mExtras == null) {
        mExtras = new Bundle();
    }
    mExtras.putBoolean(name, value);
    return this;
}

其中 mExtras 是 Intent 內部定義的一個 private Bundle 變數。也就是說,Intent 其實是呼叫了 Bundle 對應的 put 方法——Intent 內部本來就是用 Bundle 實作資料傳遞的,只是多包了一層。

再看 putExtras:

public Intent putExtras(Bundle extras) {
    if (mExtras == null) {
        mExtras = new Bundle();
    }
    mExtras.putAll(extras);
    return this;
}

它做的事是把傳進來那個 bundle 的內容,批次併入 Intent 內部的 bundle。原理和直接 putExtra 並無二致。

三、那該用哪一個

Intent 的目標是資料傳遞,Bundle 的目標是資料存取。Intent 雖然也提供了一部分存取能力,但比起 Bundle 就顯得不夠專業、也不夠靈活。

實務上的判斷很簡單:只帶一兩個參數,直接 putExtra 最省事;參數多、需要結構化整理,或想把同一組資料重複帶到多個地方,就先用 Bundle 收攏再 putExtras。至於 savedInstanceState 那個 Bundle,用途又不同——它是系統在 Activity 被銷毀前暫存、重建後還給你的狀態包,常用來保存滾動位置、表單草稿這類「不想讓使用者重做一遍」的中間狀態,通常搭配 onSaveInstanceState() 一起使用。

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