- Parcelable接口
Interface for classes whose instances can be written to and restored from a Parcel。 Classes implementing the Parcelable interface must also have a static field called CREATOR, which is an object implementing the Parcelable.Creator interface。
2.實現Parcelable就是爲了進行序列化,那麼,爲什麼要序列化?
1)永久性保存對象,保存對象的字節序列到本地文件中;
2)通過序列化對象在網絡中傳遞對象;
3)通過序列化在進程間傳遞對象。
3.實現序列化的方法
Android中實現序列化有兩個選擇:一是實現Serializable接口(是JavaSE本身就支持的),一是實現Parcelable接口(是Android特有功能,效率比實現Serializable接口高效,可用於Intent數據傳遞,也可以用於進程間通信(IPC))。實現Serializable接口非常簡單,聲明一下就可以了,而實現Parcelable接口稍微複雜一些,但效率更高,推薦用這種方法提高性能。
注:Android中Intent傳遞對象有兩種方法:一是Bundle.putSerializable(Key,Object),另一種是Bundle.putParcelable(Key,Object)。當然這些Object是有一定的條件的,前者是實現了Serializable接口,而後者是實現了Parcelable接口。
4.選擇序列化方法的原則
1)在使用內存的時候,Parcelable比Serializable性能高,所以推薦使用Parcelable。
2)Serializable在序列化的時候會產生大量的臨時變量,從而引起頻繁的GC。
3)Parcelable不能使用在要將數據存儲在磁盤上的情況,因爲Parcelable不能很好的保證數據的持續性在外界有變化的情況下。儘管Serializable效率低點,但此時還是建議使用Serializable 。
5.應用場景
需要在多個部件(Activity或Service)之間通過Intent傳遞一些數據,簡單類型(如:數字、字符串)的可以直接放入Intent。複雜類型必須實現Parcelable接口。
6、Parcelable接口定義
public interface Parcelable
{
//內容描述接口,基本不用管
public int describeContents();
//寫入接口函數,打包
public void writeToParcel(Parcel dest, int flags);
//讀取接口,目的是要從Parcel中構造一個實現了Parcelable的類的實 例處理。因爲實現類在這裏還是不可知的,所以需要用到模板的方式,繼承類名通過模板參數傳入
//爲了能夠實現模板參數的傳入,這裏定義Creator嵌入接口,內含兩個接口函數分別返回單個和多個繼承類實例
public interface Creator<T>
{
public T createFromParcel(Parcel source);
public T[] newArray(int size);
}
}
7、實現Parcelable步驟
1)implements Parcelable
2)重寫writeToParcel方法,將你的對象序列化爲一個Parcel對象,即:將類的數據寫入外部提供的Parcel中,打包需要傳遞的數據到Parcel容器保存,以便從 Parcel容器獲取數據
3)重寫describeContents方法,內容接口描述,默認返回0就可以
4)實例化靜態內部對象CREATOR實現接口Parcelable.Creator
public static final Parcelable.Creator CREATOR
注:其中public static final一個都不能少,內部對象CREATOR的名稱也不能改變,必須全部大寫。需重寫本接口中的兩個方法:createFromParcel(Parcel in) 實現從Parcel容器中讀取傳遞數據值,封裝成Parcelable對象返回邏輯層,newArray(int size) 創建一個類型爲T,長度爲size的數組,僅一句話即可(return new T[size]),供外部類反序列化本類數組使用。
簡而言之:通過writeToParcel將你的對象映射成Parcel對象,再通過createFromParcel將Parcel對象映射成你的對象。也可以將Parcel看成是一個流,通過writeToParcel把對象寫到流裏面,在通過createFromParcel從流裏讀取對象,只不過這個過程需要你來實現,因此寫的順序和讀的順序必須一致。
代碼如下:
聲明:WorkBean類
/**
* 1、Parcelable比Serializable效率高,
*
*/
public class WorkBean implements Parcelable {
// 普通常量按Parcelable提供的方法直接操作即可
private int keyId;
private String address;
public HashMap<String, String> map = new HashMap<String, String>();
// 聲明boolean變量,在傳值時需要依據true,false來設置1,0轉換爲byte字節進行寫入和讀取時則相反
private boolean isOk;
// 聲明list對象集合
private ArrayList<AccountBean> listAccount = new ArrayList<AccountBean>();
// 繼承了Serializeable
private AccountBean myAccount;
// 繼承了Parcelable的對象
private Student stu;
private static String[] arrayStr;
public WorkBean() {
}
public WorkBean(int keyId, String address, HashMap<String, String> map,
boolean isOk, ArrayList<AccountBean> listAccount,
AccountBean myAccount, Student stu, String[] arrayStr) {
this.keyId = keyId;
this.address = address;
this.map = map;
this.isOk = isOk;
this.listAccount = listAccount;
this.myAccount = myAccount;
this.stu = stu;
this.arrayStr = arrayStr;
}
public HashMap<String, String> getMap() {
return map;
}
public void setMap(HashMap<String, String> map) {
this.map = map;
}
public ArrayList<AccountBean> getListAccount() {
return listAccount;
}
public void setListAccount(ArrayList<AccountBean> listAccount) {
this.listAccount = listAccount;
}
public AccountBean getMyAccount() {
return myAccount;
}
public void setMyAccount(AccountBean myAccount) {
this.myAccount = myAccount;
}
public Student getStu() {
return stu;
}
public void setStu(Student stu) {
this.stu = stu;
}
@Override
public int describeContents() {
return 0;
}
public int getKeyId() {
return keyId;
}
public void setKeyId(int keyId) {
this.keyId = keyId;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
@Override
public String toString() {
return "WorkBean [keyId=" + keyId + ", address=" + address
+ ", map.name=" + map.get("name") + ",map.age:"
+ map.get("age") + ", isOk=" + isOk + ", listAccount="
+ listAccount + ", myAccount=" + myAccount + ", stu=" + stu
+ ", arrayStr=" + Arrays.toString(arrayStr) + "]";
}
@Override
public void writeToParcel(Parcel dest, int flags) {
// 常規寫入
dest.writeInt(keyId);
dest.writeString(address);
if (arrayStr == null) {
dest.writeInt(0);
} else {
dest.writeInt(arrayStr.length);
}
if (arrayStr != null) {
dest.writeStringArray(arrayStr);
}
// 注意:寫入boolean
dest.writeByte((byte) (isOk ? 1 : 0));
dest.writeList(listAccount);
// 注意:寫入序列化的對象
dest.writeSerializable(myAccount);
dest.writeParcelable(stu, flags);
// 寫入HashMap<String,String>()對象
dest.writeMap(map);
}
// 必須聲明公開靜態的,名稱爲CREATOR的成員變量方法,否則會在獲取數據時報:android.os.BadParcelableException
public static final Parcelable.Creator<WorkBean> CREATOR = new Creator<WorkBean>() {
@Override
public WorkBean[] newArray(int size) {
return new WorkBean[size];
}
// 在讀取Parcel容器裏的數據時,必須按成員變量聲明的順序讀取數據
@Override
public WorkBean createFromParcel(Parcel source) {
WorkBean workBean = new WorkBean();
workBean.keyId = source.readInt();
workBean.address = source.readString();
int length = source.readInt();
String[] tempStr = null;
if (length > 0) {
tempStr = new String[length];
source.readStringArray(tempStr);
}
workBean.isOk = source.readByte() == 1 ? true : false;
workBean.listAccount = source.readArrayList(AccountBean.class
.getClassLoader());
workBean.myAccount = (AccountBean) source.readSerializable();
workBean.stu = source
.readParcelable(Student.class.getClassLoader());
workBean.map = source.readHashMap(HashMap.class.getClassLoader());
return workBean;
}
};
/**
* (1、)Caused By:android.os.BadParcelableException: ClassNotFoundException
* when unmarshalling,原因是ClassLoader設置不對,或者沒有傳入ClassLoader。
*
* (2、)java.lang.RuntimeException: Parcelable encountered IOException
* writing serializable
* object,原因是傳遞的Parcelable對象裏面的對象也要Parcelable或者Serializable。
*/
}
**聲明AccountBean 類:**
/**
* 一個對象序列化的接口,一個類只有實現了Serializable接口,它的對象纔是可序列化的。因此如果要序列化某些類的對象,
* 這些類就必須實現Serializable接口
* 。而實際上,Serializable是一個空接口,沒有什麼具體內容,它的目的只是簡單的標識一個類的對象可以被序列化。
*
*/
public class AccountBean implements Serializable {
// 1、如果在這個裏面也添加自定義的類也是要實現Serializable,否則會報NotSerializableException;
// 2、在Parcelable中可以使用Serializable,但在Serializable不可用Parcelable,否則會報:java.io.NotSerializableException異常
// 3、傳遞枚舉enum的話,把枚舉當做類來看就行了
private static final long serialVersionUID = -6738248150126276047L;
private String account;
private String password;
public AccountBean(String account, String password) {
this.account = account;
this.password = password;
}
public AccountBean() {
}
@Override
public String toString() {
return "AccountBean [account=" + account + ", password=" + password
+ "]";
}
public String getAccount() {
return account;
}
public void setAccount(String account) {
this.account = account;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
}
**聲明Student類:**
public class Student implements Parcelable {
private int classNum;
private String name;
private int age;
private boolean s;
public int getClassNum() {
return classNum;
}
public void setClassNum(int classNum) {
this.classNum = classNum;
}
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;
}
public boolean isS() {
return s;
}
public void setS(boolean s) {
this.s = s;
}
public Student() {
super();
}
@Override
public String toString() {
return "Student [classNum=" + classNum + ", name=" + name + ", age="
+ age + ", s=" + s + "]";
}
public Student(int classNum, String name, int age, boolean s) {
super();
this.classNum = classNum;
this.name = name;
this.age = age;
this.s = s;
}
@Override
public int describeContents() {
return 0;
}
@Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeInt(classNum);
dest.writeString(name);
dest.writeInt(age);
dest.writeByte((byte) (s ? 1 : 0));
}
// 生成靜態的方法
public static final Parcelable.Creator<Student> CREATOR = new Creator<Student>() {
@Override
public Student[] newArray(int size) {
return new Student[size];
}
@Override
public Student createFromParcel(Parcel source) {
Student student = new Student();
student.classNum = source.readInt();
student.name = source.readString();
student.age = source.readInt();
student.s = source.readByte() == 1 ? true : false;
return student;
}
};
}
8、Serializable實現與Parcelabel實現的區別
1)Serializable的實現,只需要implements Serializable 即可。這只是給對象打了一個標記,系統會自動將其序列化。
2)Parcelabel的實現,不僅需要implements Parcelabel,還需要在類中添加一個靜態成員變量CREATOR,這個變量需要實現 Parcelable.Creator 接口。
發送序列化後的對象:
AccountBean accountBean = new AccountBean("account", "123456");
ArrayList<AccountBean> listAccount = new ArrayList<AccountBean>();
listAccount.add(accountBean);
String[] tempStr = { "01", "02", "03" };
HashMap<String,String> map=new HashMap<String, String>();
map.put("name", "xiaohui");
map.put("age", "002");
// 初始化對象
WorkBean workbean = new WorkBean(002, "china shanghai",
map, false, listAccount, accountBean, new Student(02, "xiaohui", 25,
true), tempStr);
ArrayList<WorkBean> listwork = new ArrayList<WorkBean>();
listwork.add(workbean);
Intent mIntent = new Intent();
mIntent.setAction(Battery_level);
mIntent.putExtra("battery", mBatteryLevel);
mIntent.putExtra("workbean", listwork.get(0));
context.sendBroadcast(mIntent);
// 接受到序列化的對象
WorkBean parcelable = intent.getParcelableExtra("workbean");
Log.i(TAG, "parcelable:" + parcelable.toString());