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:
publicclassPerson implementsParcelable{ privateString name; privateString phone; //必须包含一个类型为Parcelable.Creator且名为CREATOR的公共静态成员 privatestaticfinalParcelable.Creator<Person> CREATOR = new Parcelable.Creator<Person>() { @Override publicPerson createFromParcel(Parcel source) {//该方法用于告诉平台如何从包裹里创建数据类实例 returnnewPerson(source); } @Override publicPerson[] newArray(intsize) { returnnewPerson[size]; } }; publicPerson(String name,String phone){ this.name = name; this.phone = phone; } publicPerson(Parcel in){ this.name = in.readString(); this.phone = in.readString(); } @Override publicint describeContents() { return0; } /** * 告诉平台如何将数据实例写入Parcel里 */ @Override publicvoidwriteToParcel(Parcel dest, intflags) { dest.writeString(this.getName()); dest.writeString(this.getPhone()); } /** * 属性的set和get方法 * @return */ publicString getName() { returnname; } publicvoidsetName(String name) { this.name = name; } publicString getPhone() { returnphone; } publicvoidsetPhone(String phone) { this.phone = phone; } } |
The role of the Android---parcelable wrapper class