http://blog.csdn.net/caowenbin/article/details/6532217
http://blog.csdn.net/caowenbin/article/details/6532238
1、新的序列化方式:
android提供了一种新的类型:Parcel。本类被用作封装数据的容器,封装后的数据可以通过Intent或IPC传递。
除了基本类型以外,只有实现了Parcelable接口的类才能被放入Parcel中。
Parcelable实现要点:需要实现三个东西
1)writeToParcel 方法。该方法将类的数据写入外部提供的Parcel中.声明如下:
writeToParcel (Parcel dest, int flags) 具体参数含义见javadoc
2)describeContents方法。没搞懂有什么用,反正直接返回0也可以
3)静态的Parcelable.Creator接口,本接口有两个方法:
createFromParcel(Parcel in) 实现从in中创建出类的实例的功能
newArray(int size) 创建一个类型为T,长度为size的数组,仅一句话(return new T[size])即可。估计本方法是供外部类反序列化本类数组使用
这个代码是在电话本源码里面copy的
public class ContactsRequest implements Parcelable {public static Parcelable.Creator<ContactsRequest> CREATOR = new Creator<ContactsRequest>() {
public ContactsRequest[] newArray(int size) {
return new ContactsRequest[size];
}
public ContactsRequest createFromParcel(Parcel source) {
ClassLoader classLoader = this.getClass().getClassLoader();
ContactsRequest request = new ContactsRequest();
request.mValid = source.readInt() != 0;
request.mActionCode = source.readInt();
request.mRedirectIntent = source.readParcelable(classLoader);
request.mTitle = source.readCharSequence();
request.mSearchMode = source.readInt() != 0;
request.mQueryString = source.readString();
request.mIncludeProfile = source.readInt() != 0;
request.mLegacyCompatibilityMode = source.readInt() != 0;
request.mDirectorySearchEnabled = source.readInt() != 0;
request.mContactUri = source.readParcelable(classLoader);
request.mCascadingData=new ArrayList<String>();
source.readStringList(request.mCascadingData);
return request;
}
};
public void writeToParcel(Parcel dest, int flags) {
dest.writeInt(mValid ? 1 : 0);
dest.writeInt(mActionCode);
dest.writeParcelable(mRedirectIntent, 0);
dest.writeCharSequence(mTitle);
dest.writeInt(mSearchMode ? 1 : 0);
dest.writeString(mQueryString);
dest.writeInt(mIncludeProfile ? 1 : 0);
dest.writeInt(mLegacyCompatibilityMode ? 1 : 0);
dest.writeInt(mDirectorySearchEnabled ? 1 : 0);
dest.writeParcelable(mContactUri, 0);
dest.writeStringList(mCascadingData);
}
public int describeContents() {
return 0;
}
}
一个进程中创建对象,当要传输这个对象到另外一个进程的时候,就会自动通过这些序列化函数在另外一个进程中CLONE出一个一模一样的对象出来
本文介绍了Android中的Parcel机制,详细阐述了如何通过实现Parcelable接口来完成对象的序列化过程,以便于通过Intent或IPC进行传递。

被折叠的 条评论
为什么被折叠?



