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

Activity 詳解(二):Activity 之間的數據傳遞

編輯:關於 Android 開發

頁面跳轉時如何把數據帶過去,是 Activity 開發中的基礎問題。本文梳理 Bundle、Intent 以及 Parcelable / Serializable 對象傳遞的具體做法。

先看效果圖:

一、Bundle 類的作用

Bundle 用作數據載體,使用方式類似 Map,用於存放 key-value 形式的值。相比 Map,它針對常用類型提供了成套的 putXxx() / getXxx() 方法,例如 putString() / getString()、putInt() / getInt()。其內部實際上是用 HashMap<String, Object> 來存儲數據。

簡單說,Bundle 就是一個專門用於配合 Intent 傳值的「打包容器」。

二、為 Intent 附加數據的兩種寫法

寫法一:批量添加。先把數據裝進 Bundle,再一次性掛到 Intent 上:

Intent intent = new Intent();

Bundle bundle = new Bundle();       // 該類用作攜帶數據
bundle.putString("name", "Alice");
bundle.putInt("age", 20);

// 為意圖追加額外數據。意圖原有的數據不會丟失,
// 但 key 同名的數據會被替換
intent.putExtras(bundle);

寫法二:逐個添加。直接調用 Intent 的 putExtra():

Intent intent = new Intent();
intent.putExtra("name", "XXX");

兩者有區別嗎?完全沒有。當你調用 putExtras() 時,傳入的 Bundle 會被轉換為 Intent 的鍵值數據(Intent 本身也是以鍵值模式承載數據的)。寫法二在只需傳少量數據時更簡潔,寫法一則在數據較多、需要復用 Bundle 時更清晰。

三、取出數據

接收方直接使用 getIntent() 拿到傳入的 Intent,再調用 getExtras() 取出 Bundle,然後按需 get 即可:

Bundle bundle = getIntent().getExtras();

String str = bundle.getString("USERNAME");   // 取鍵為 USERNAME 的字符串
int num = bundle.getInt("Number");           // 取鍵為 Number 的整型

四、傳遞自定義對象

Android 組件間傳遞對象時,推薦實現 Parcelable 接口;也可以使用 Java 原生的 Serializable 接口。前者是 Android 專門設計的序列化方案,內存與性能表現明顯優於後者,數據量越大差距越明顯。

1. 讓實體類實現 Parcelable:

public class ParcelableData implements Parcelable {

    private String name;
    private int age;

    public ParcelableData() {
        name = "guest";
        age = 20;
    }

    // 從 Parcel 中讀取,順序必須與 writeToParcel 的寫入順序完全一致
    protected ParcelableData(Parcel in) {
        name = in.readString();
        age = in.readInt();
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    @Override
    public int describeContents() {
        return 0;
    }

    @Override
    public void writeToParcel(Parcel dest, int flags) {
        dest.writeString(name);
        dest.writeInt(age);
    }

    public static final Parcelable.Creator<ParcelableData> CREATOR =
            new Parcelable.Creator<ParcelableData>() {
        public ParcelableData createFromParcel(Parcel in) {
            return new ParcelableData(in);
        }

        public ParcelableData[] newArray(int size) {
            return new ParcelableData[size];
        }
    };
}

這裡最容易犯的低級錯誤是讀寫順序不一致——writeToParcel() 中先寫 name 後寫 age,那麼構造函數中就必須先讀 name 後讀 age,否則數據會錯位。

2. 發送對象:Bundle 本身也實現了 Parcelable 接口,實戰中通常通過 Bundle 封裝數據再傳送。

Intent intent = new Intent();
intent.setClass(this, SubActivity.class);

// 方式一:直接附加 Parcelable 對象
// intent.putExtra("MyData", new ParcelableData());

// 方式二:通過 Bundle 封裝(推薦,可同時攜帶多個值)
Bundle bundle = new Bundle();
bundle.putString("MyString", "test bundle");
bundle.putParcelable("MyData", new ParcelableData());

intent.putExtras(bundle);
startActivity(intent);

3. 接收對象:

// 方式一:直接從 Intent 中取
// ParcelableData data = getIntent().getParcelableExtra("MyData");

// 方式二:先取 Bundle,再從中解析
Bundle bundle = getIntent().getExtras();
ParcelableData parcelableData = bundle.getParcelable("MyData");
String testBundleString = bundle.getString("MyString");

Log.v("string=", testBundleString);
Log.v("name=", parcelableData.getName());
Log.v("age=", String.valueOf(parcelableData.getAge()));

五、Demo 代碼

public class TestBundleActivity extends AppCompatActivity {

    EditText editText1;
    EditText editText2;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_test_bundle);
        editText1 = (EditText) findViewById(R.id.editText1);
        editText2 = (EditText) findViewById(R.id.editText2);
    }

    /** 提交選擇的地區,把字符串傳給 TestBundleActivity3 */
    public void submitRegion(View view) {
        EditText editTextRegion = (EditText) findViewById(R.id.editTextRegion);
        Intent intent = new Intent(this, TestBundleActivity3.class);
        String region = editTextRegion.getText().toString();
        if (!TextUtils.isEmpty(region)) {
            intent.putExtra("region", region);
            startActivity(intent);
        } else {
            Toast.makeText(this, "地區不能是空值", Toast.LENGTH_SHORT).show();
        }
    }

    /** 兩個 Integer 相加,傳入 TestBundleActivity1 計算 */
    public void calculte(View view) {
        Intent intent = new Intent(this, TestBundleActivity1.class);
        Bundle bundle = new Bundle();
        String first = editText1.getText().toString();
        String second = editText2.getText().toString();
        if (!TextUtils.isEmpty(first) && !TextUtils.isEmpty(second)) {
            bundle.putInt("first", Integer.parseInt(first));
            bundle.putInt("second", Integer.parseInt(second));
            intent.putExtras(bundle);
            startActivity(intent);
        } else {
            Toast.makeText(this, "數值不能是空", Toast.LENGTH_SHORT).show();
        }
    }

    /** 傳遞 Serializable 對象到 TestBundleActivity2 */
    public void login(View view) {
        EditText editTextName = (EditText) findViewById(R.id.editTextName);
        EditText editTextCode = (EditText) findViewById(R.id.editTextCode);
        Intent intent = new Intent(this, TestBundleActivity2.class);
        Bundle bundle = new Bundle();
        String name = editTextName.getText().toString();
        String code = editTextCode.getText().toString();
        if (!TextUtils.isEmpty(name) && !TextUtils.isEmpty(code)) {
            Person person = new Person();
            person.setName(name);
            person.setCode(code);
            bundle.putSerializable("person", person);
            intent.putExtras(bundle);
            startActivity(intent);
        } else {
            Toast.makeText(this, "姓名編號不能是空", Toast.LENGTH_SHORT).show();
        }
    }
}

補充:傳遞大數據要注意什么

Intent 攜帶的數據會經歷序列化與跨進程拷貝,系統對 Bundle 大小存在實際限制(歷史上大致在 1MB 量級,具體與 Binder 緩衝區相關)。因此:

  • 不要試圖通過 Intent 傳遞大圖的 Bitmap 或大列表;
  • 大數據應先在本地持久化,只傳遞標識符(如文件路徑、數據庫主鍵、URI);
  • 接收方拿到標識符後自行按需加載,這樣既不撐爆 Binder,也避免臨時對象無法回收。

示例整理自「安卓無憂」學習項目,可在應用寶或豌豆莢下載完整源碼對照參考。

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