一、Parcelable類(Android獨有的)
簡介:Parcelable是一個接口。
作用:是Android提供的序列化接口,實現序列化和反序列化的操作。
二、跨進程使用
步驟一:創建Book類繼承Parcelable接口
public class Book implements Parcelable {
private String mBookName;
private int mBookId;
/**
*準備:創建Book類,并繼承Parcelable接口
*/
public Book(int bookId, String bookName) {
mBookId = bookId;
mBookName = bookName;
}
@Override
public String toString() {
return mBookId+""+mBookName;
}
}
步驟二:會提示必須重寫接口的方法
describeContents():返回當前對象的描素內容,如果含有文件描述符(什么叫文件描述符)則返回1,否則返回0,一般都返回0(所以不用考慮咯)。
writeToParcel(Parcel out,int flags):將對象寫入序列化
Parcel out :系統提供的輸出流,將成員變量存儲到內存中。
int flags:0或1,1表示當前對象需要作為返回值保存(不明白),基本上所有情況都為0,(所以說可以不用考慮咯)
//接上面的代碼
@Override
public int describeContents() {
return 0;
}//描述文件,現在只要返回0就行
@Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeInt(mBookId);
dest.writeString(mBookName);
}//將當前對象寫入序列化結構
步驟三:創建反序列化對象 Parcelable.Creator<T>接口:專門用于反序列化
重寫該接口的方法:
createFromParcel(Parcel in):系統提供的輸入流,從序列化的對象獲取數據。
newArray(int size):創建該對象的數組 (暫時感覺沒用)
注:反序列化的時候,要按照序列化放入數據的順序獲取數據,否則會收不著值。
//一定需要按照這種格式書寫 public static final Parcelable.Creator<Book> CREATOR
public static final Parcelable.Creator<Book> CREATOR = new Parcelable.Creator<Book>(){
@Override
public Book createFromParcel(Parcel source) {
return new Book(source);
}//獲取輸入流,反序列化對象
@Override
public Book[] newArray(int size) {
return new Book[0];
}
};
//創建構造方法,實例化對象
private Book (Parcel in){
mBookId = in.readInt();
mBookName = in.readString();
}
3.原理
Parcelable利用Parcel out 將數據存儲到內存中,然后通過Parcel in 從內存中獲取數據。
三、Intent之間傳遞Parcelable類(就是各個Activity傳遞對象的方法)
根據上面創建Parcelable的方式,創建該類,然后應用Intent傳輸就可以了。