只要實現(xiàn)了 Parcelable 接口,一個類的對象就可以實現(xiàn)序列化并可以通過 Intent 和 Binder 傳遞薪韩。
使用示例
import android.os.Parcel;import android.os.Parcelable;
public class User implements Parcelable {
private int userId;
protected User(Parcel in) {
userId = in.readInt();
}
public static final Creator<User> CREATOR = new Creator<User>() {
@Override
public User createFromParcel(Parcel in) {
return new User(in);
}
@Override
public User[] newArray(int size) {
return new User[size];
}
};
@Override
public int describeContents() {
return 0;
}
@Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeInt(userId);
}
public int getUserId() {
return userId;
}
}
方法說明
Parcel 內(nèi)部包裝了可序列化的數(shù)據(jù)宙帝,可以在 Binder 中自由傳輸丧凤。序列化功能由 writeToParcel 方法完成,最終是通過 Parcel 中的一系列 write 方法完成步脓。反序列化功能由 CREATOR 來完成愿待,通過 Parcel 的一系列 read 方法來完成反序列化過程。
方法名
createFromParcel(Parcel in)
功能:從序列化后的對象中創(chuàng)建原始對象
方法名
newArray(int size)
功能:創(chuàng)建指定長度的原始對象數(shù)組
方法名
User(Parcel in)
功能:從序列化后的對象中創(chuàng)建原始對象
方法名
writeToParcel(Parcel dest, int flags)
功能:將當(dāng)前對象寫入序列化結(jié)構(gòu)中靴患,其中 flags 標識有兩種值:0 或者 1仍侥;為 1 時標識當(dāng)前對象需要作為返回值返回,不能立即釋放資源鸳君,幾乎所有情況都為 0
方法名
describeContents
功能:返回當(dāng)前對象的內(nèi)容描述农渊。如果含有文件描述符,返回 1或颊,否則返回 0砸紊,幾乎所有情況都返回 0
Parcelable 與 Serializable 對比
- Serializable 使用 I/O 讀寫存儲在硬盤上,而 Parcelable 是直接在內(nèi)存中讀寫
- Serializable 會使用反射囱挑,序列化和反序列化過程需要大量 I/O 操作批糟, Parcelable 自已實現(xiàn)封送和解封(marshalled &unmarshalled)操作不需要用反射,數(shù)據(jù)也存放在 Native 內(nèi)存中看铆,效率要快很多