Parcelable is a serialization interface provided by Android. Compared with Serializable, it is more complex to use, but more efficient. It is often used for AIDL communication, etc.

Parcelable basic implementation

// Implement the Parcelable interface
public class Person implements android.os.Parcelable {
  private int age;
  private String name;
  
  @Override
  public int describeContents(a) {
    return 0;
  }

  @Override
  public void writeToParcel(Parcel dest, int flags) {
  	// Write in order
    dest.writeInt(this.age);
    dest.writeString(this.name);
  }

  public Person(a) {}protected Person(Parcel in) {
    // Fetch in the order you save it
    this.age = in.readInt();
    this.name = in.readString();
  }

  public static final Creator<Person> CREATOR = new Creator<Person>() {
    @Override
    public Person createFromParcel(Parcel source) {
      // Create a Person from Parcel
      return new Person(source);
    }

    @Override
    public Person[] newArray(int size) {
      return newPerson[size]; }}; }Copy the code

Here are two important methods:

writeToParcel()Write variables to Parcel for serialization

createFromParcel(): Creates serialized objects from Parcel

If you feel the operation is troublesome, there is a simple approach:

  1. Add in Android StudioAndroid Parcelable code generatorThis plugin.
  2. Open this class and useAlt+Insert“And then click Parcelbale.

Enum Implements the Parcelable interface

When you create an enumeration and want to use the above plug-in, you will find that the sequence number is not available. This is because Parcel. WriteXXX does not have methods to write enumerations, so Parcelable cannot be implemented directly.

At this point, we just need to define a conversion rule that converts the enumeration to a type that Parcel can write to, and supports finding the corresponding enumeration by retrieving variables from Parcel.

public enum Fruit implements Parcelable {
  /** * fruit */
  APPLE,
  BANANA,
  WATERMELON;

  @Override
  public int describeContents(a) {
    return 0;
  }

  @Override
  public void writeToParcel(Parcel dest, int flags) {
    // Store the ordinal number in the enumeration constant
    dest.writeInt(ordinal());
  }
  public static final Creator<Fruit> CREATOR = new Creator<Fruit>() {
    @Override
    public Fruit createFromParcel(Parcel in) {
      // Find the corresponding enumeration type by enumerating the ordinal of the constant
      return Fruit.values()[in.readInt()];
    }

    @Override
    public Fruit[] newArray(int size) {
      return newFruit[size]; }}; }Copy the code