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

Android 開發:用 Parcelable 序列化自訂類別並透過 Intent 傳遞

編輯:關於 Android 程式設計

當自訂的資料型別需要透過 Intent 或 IPC 傳遞時,就必須先把它序列化。Android 對此提供了 Parcelable 介面,它比 Java 原生的 Serializable 更適合行動裝置——因為它不把整個物件圖寫進記憶體,而是讓你自己決定要往 Parcel 裡放哪些欄位,開銷小得多。

Parcelable 的基本結構

官方文件中的範例:

public class MyParcelable implements Parcelable {
    private int mData;

    public int describeContents() {
        return 0;
    }

    public void writeToParcel(Parcel out, int flags) {
        out.writeInt(mData);
    }

    public static final Parcelable.Creator<MyParcelable> CREATOR =
            new Parcelable.Creator<MyParcelable>() {
        public MyParcelable createFromParcel(Parcel in) {
            return new MyParcelable(in);
        }
        public MyParcelable[] newArray(int size) {
            return new MyParcelable[size];
        }
    };

    private MyParcelable(Parcel in) {
        mData = in.readInt();
    }
}

從這個範例可以看出實作 Parcelable 的四個要點:

  1. 實作 Parcelable 介面。
  2. 覆寫 writeToParcel(),決定資料怎麼寫進 Parcel。寫入與讀取的順序必須完全一致,這是最容易出錯的地方。
  3. 提供一個名為 CREATOR 的 public static final 欄位,型別為 Parcelable.Creator,負責從 Parcel 還原物件。
  4. 通常再搭配一個接收 Parcel 的私有建構子來完成還原。

完成之後,這個自訂型別就能像基本資料型別一樣用 Intent 傳遞了。

用 Intent 傳遞 MyParcelable

專案結構如下:

MainActivity.java(發送端)

package com.example.parcelabledemo;

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

public class MainActivity extends Activity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Button btn = (Button) findViewById(R.id.btn);
        btn.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(MainActivity.this, HandleActivity.class);
                MyParcelable myParcelable = new MyParcelable(10);
                Bundle bundle = new Bundle();
                bundle.putParcelable("value", myParcelable);
                intent.putExtras(bundle);
                startActivity(intent);
            }
        });
    }
}

HandleActivity.java(接收端)

package com.example.parcelabledemo;

import android.app.Activity;
import android.os.Bundle;
import android.widget.Toast;

public class HandleActivity extends Activity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.handle);

        Bundle bundle = getIntent().getExtras();
        MyParcelable myParcelable = bundle.getParcelable("value");
        Toast.makeText(this, "value = " + myParcelable.get_data(),
                Toast.LENGTH_LONG).show();
    }
}

這樣一個自訂類別的序列化與跨元件傳遞就完成了。

幾個實務提醒

  • 欄位順序一定要對齊。writeToParcel 的順序若與讀取端不一致,拿到的就是錯亂的資料,而且不一定會報錯,是很難查的問題。
  • Parcel 不是通用的序列化機制。它主要用於記憶體中的 IPC,不適合拿來寫檔長期保存。
  • 記得處理 null。若物件中可能含 null 欄位,寫入時用 writeString() 等方法是安全的(它們能處理 null),但自訂物件欄位要留意。
  • Android Studio 有外掛可以自動產生。像 Parcelable Generator 這類外掛能依欄位自動產生 boilerplate,大幅減少手寫出錯的機會。
  • 大量資料改用 Bundle 分批傳。Intent 有大小限制(實務上約 1MB,與 Binder 緩衝區有關),傳大物件會直接失敗。
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved