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

Android 對象傳遞兩法:Serializable 與 Parcelable 探索

編輯:關於 Android 程式設計

在 Android 開發中,Activity 之間傳遞數據是家常便飯,而要在 Intent 中傳遞對象也不可避免。目前我了解到的主要有兩種方式:

1. 利用 Bundle.putSerializable(Key, Object);
2. 利用 Bundle.putParcelable(Key, Object);

這兩種方法的前提都是將傳遞的對象序列化。那麼,什麼是序列化?如何序列化?又有什麼好處?下面逐一探討。

序列化的含義:序列化(Serialization)是把對象的狀態信息轉換為可存儲或傳輸形式的過程。序列化期間,對象會把當前狀態寫入臨時或持久性存儲區,之後可通過讀取或反序列化重新創建該對象。

序列化的目的:以某種存儲形式使自定義對象持久化;將對象從一個地方傳遞到另一個地方;讓程序更易於維護。

如何序列化

方式一:實現 Serializable 接口(Java SE 本身支持)

這種方式很簡單,只需實現一個 Serializable 接口即可:

public class Person implements Serializable {
    private int id;
    private String name;
    public int getId() { return id; }
    public void setId(int id) { this.id = id; }
    public String getName() { return name; }
    public void setName(String name) { this.name = name; }
}

方式二:實現 Parcelable 接口(Android 特有,效率比 Serializable 更高,可用於 Intent 數據傳遞與進程間通信 IPC)

步驟稍多:1. implements Parcelable;2. 重寫 writeToParcel(),把數據寫入 Parcel;3. 重寫 describeContents(),默認返回 0 即可;4. 實例化靜態內部對象 CREATOR 並實現 Parcelable.Creator 接口。

public class Man implements Parcelable {
    private int id;
    private String name;
    protected Man(Parcel in) {
        id = in.readInt();
        name = in.readString();
    }
    public Man() { }
    @Override
    public void writeToParcel(Parcel dest, int flags) {
        dest.writeInt(id);
        dest.writeString(name);
    }
    @Override
    public int describeContents() { return 0; }
    public static final Creator<Man> CREATOR = new Creator<Man>() {
        @Override
        public Man createFromParcel(Parcel in) { return new Man(in); }
        @Override
        public Man[] newArray(int size) { return new Man[size]; }
    };
    public int getId() { return id; }
    public void setId(int id) { this.id = id; }
    public String getName() { return name; }
    public void setName(String name) { this.name = name; }
}

如果使用 Android Studio 2.1 及以上版本,寫好類的屬性、添加 Parcelable 接口後,用 alt+回車即可讓編譯器自動生成這一系列代碼。

兩者的區別

Serializable 只需 implements Serializable;而 Parcelable 不僅要 implements Parcelable,還需在類中添加一個實現 Parcelable.Creator 接口的靜態成員變量 CREATOR。

選擇原則

在內存使用上,Parcelable 性能優於 Serializable,因此推薦使用 Parcelable。Serializable 序列化時會產生大量臨時變量,引起頻繁 GC。但 Parcelable 不能用於將數據存儲到磁盤的場景,因為它無法很好地保證數據在外界變化時的持續性,此時仍建議使用 Serializable。總之,在 Activity 或 Service 之間通過 Intent 傳遞簡單類型可直接放入 Intent,複雜類型則需實現 Parcelable 接口。

下面是對象傳遞與接收的實現。先在 MainActivity 中傳遞序列化好的對象:

//用 Serializable 方式傳遞
public void sendForSerializable(View view) {
    Person person = new Person();
    person.setId(100);
    person.setName("胡漢三");
    Intent intent = new Intent(this, NextAcitvity.class);
    Bundle bundle = new Bundle();
    bundle.putSerializable("Serializable", person);
    intent.putExtras(bundle);
    startActivity(intent);
}
//用 Parcelable 方式傳遞
public void sendForParcelable(View view) {
    Man man = new Man();
    man.setId(10010);
    man.setName("TestParcelable");
    Bundle bundle = new Bundle();
    bundle.putParcelable("Parcelable", man);
    Intent intent = new Intent(this, NextAcitvity.class);
    intent.putExtras(bundle);
    startActivity(intent);
}

再在 NextAcitvity 中獲取對象實例:

//獲取 Serializable 傳遞的對象
Person person = (Person) getIntent().getSerializableExtra("Serializable");
if (person != null) {
    editText1.setText("id =" + person.getId() + "****" + "名字是:" + person.getName());
}
//獲取 Parcelable 傳遞的對象
Man man = getIntent().getExtras().getParcelable("Parcelable");
if (man != null) {
    editText2.setText("id =" + man.getId() + "****" + "名字是:" + man.getName());
}

最後,別忘了在 AndroidManifest.xml 中聲明新增的 Activity,否則程序無法正常運行。

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