Android offers a new type: Parcel. This class is used as a container for encapsulating data, and the encapsulated data can be passed through intent or IPC. Except for the base type, only classes that implement the Parcelable interface can be placed in parcel. The Android platform contracts data definitions that can be passed through the process communication (IPC) mechanism, which must implement the Parcelable interface and must contain a public static member of type Parcelable.creator and named Creator. Only classes that implement the Parcelable interface can be passed with intent extended data.
The Createfromparcel method that implements the creator member of the Parcelable interface is used to tell the platform how to create instances of the class from the package, while the Writetoparcel method is used to tell the platform how to store instances of that class in the package. Through the engagement of interface team members, the Android platform learns the interface of data reading and writing of data classes, thus instantiating and persisting objects, such as:
The sample code is as follows:
public
class
Person
implements
Parcelable{
private
String name;
private
String phone;
//必须包含一个类型为Parcelable.Creator且名为CREATOR的公共静态成员
private
static
final
Parcelable.Creator<Person> CREATOR =
new Parcelable.Creator<Person>() {
@Override
public
Person createFromParcel(Parcel source) {
//该方法用于告诉平台如何从包裹里创建数据类实例
return
new
Person(source);
}
@Override
public
Person[] newArray(
int
size) {
return
new
Person[size];
}
};
public
Person(String name,String phone){
this
.name = name;
this
.phone = phone;
}
public
Person(Parcel in){
this
.name = in.readString();
this
.phone = in.readString();
}
@Override
public
int describeContents() {
return
0
;
}
/**
* 告诉平台如何将数据实例写入Parcel里
*/
@Override
public
void
writeToParcel(Parcel dest,
int
flags) {
dest.writeString(
this
.getName());
dest.writeString(
this
.getPhone());
}
/**
* 属性的set和get方法
* @return
*/
public
String getName() {
return
name;
}
public
void
setName(String name) {
this
.name = name;
}
public
String getPhone() {
return
phone;
}
public
void
setPhone(String phone) {
this
.phone = phone;
}
}
|
The role of the Android---parcelable wrapper class