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

Android 進程通信前的基本功:Serializable 與 Parcelable 兩種序列化方式對比

編輯:關於 Android 程式設計

聊天提到 Messenger 之前,得先把 Android 的序列化機制說清楚——畢竟跨進程傳資料,靠的就是它。

兩種序列化方式

Android 裡有兩套:Serializable 是 Java 原生提供的,Parcelable 是 Android 獨有的。

Parcelable 效率更高,但寫起來麻煩,主要用於記憶體內的序列化。
Serializable 使用簡單,但伴隨大量 I/O 操作、開銷較大,適合儲存裝置或網路傳輸。

Serializable 怎麼用

簡單到只要實作一個空介面:

public class Goods implements Serializable {
    private int mId;

    public Goods(int id) {
        mId = id;
    }

    public int getmId() {
        return mId;
    }
}

搭配 ObjectOutputStream 與 ObjectInputStream 就能完成序列化與反序列化:

Goods goods = new Goods(3);

// 序列化
try {
    ObjectOutputStream oos = new ObjectOutputStream(
            new FileOutputStream("/sdcard/test.txt"));
    oos.writeObject(goods);
    oos.close();
} catch (IOException e) {
    e.printStackTrace();
}

// 反序列化
try {
    ObjectInputStream ois = new ObjectInputStream(
            new FileInputStream("/sdcard/test.txt"));
    Goods goodsIn = (Goods) ois.readObject();
    ois.close();
    Log.e("wing", goodsIn.getmId() + "");
} catch (IOException e) {
    e.printStackTrace();
} catch (ClassNotFoundException e) {
    e.printStackTrace();
}

執行後控制台會印出 id 為 3。

這裡有個容易被忽略的細節:為了保證序列化的正確性,建議為類別加上 serialVersionUID。它主要承擔版本檢驗的角色——反序列化時若這個值不一致,就會直接失敗。

private static final long serialVersionUID = 615555755L;

Parcelable 怎麼用

Parcelable 稍複雜一些,好在 Android Studio 能幫你生成大部分程式碼。以 Goods 為例,這次多一個 name 屬性:

public class Goods implements Parcelable {
    private int mId;
    private String mName;

    public Goods(int id, String name) {
        mId = id;
        mName = name;
    }

    protected Goods(Parcel in) {
        mId = in.readInt();
        mName = in.readString();
    }

    public static final Creator<Goods> CREATOR = new Creator<Goods>() {
        @Override
        public Goods createFromParcel(Parcel in) {
            return new Goods(in);
        }

        @Override
        public Goods[] newArray(int size) {
            return new Goods[size];
        }
    };

    public int getmId() {
        return mId;
    }

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

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

三個關鍵部分:

  • Parcel 構造器:屬性用 in.readXxx() 依序讀回。型別必須與寫入順序嚴格對應,例如 id 是 int 就寫 mId = in.readInt()。
  • writeToParcel:與上面完全對稱,把屬性依序 write 出去。
  • CREATOR:Parcelable 的必要成員,負責從 Parcel 重建物件。

用 Intent 傳遞資料時,可以直接放實作物件,也可以放 List、Map,前提是內部元素同樣可序列化。但要留意 Intent 有大小限制,這點在實務上很致命——大量資料應該走檔案或 Provider,而不是硬塞進 Intent。

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