Android Parcel

A parcel with respect to android development is a class that holds object references and data that can be sent through an IBinder.

Parcels act as containers for these:

  1. Data – Flattened data to be unflattened on the other side of IPC(Inter Process Communication). This flattened data can be flattened using various mechanisms for writing specific types or through a general Parcelable interface.
  2. Objects – Live IBinder references. These IBinder objects will then on the other side receive a proxy IBinder connected to the original IBinder in the Parcel.

Parcel was added into the Android Framework way back with API level 1 as a high-performance IPC transport mechanism.

Therefore they are not meant to be used as a general-purpose serialization technique.

Parcel class definition

Parcel is a final class so it’s not derivable.

public final class Parcel{}

It derives from the java.lang.Object class:

public final class Parcel extends Object{}

Parcel belongs to android.os package:

package android.os

Android Parcelable

Parcelable is an interface that allows its implementers to be writable to and restorable from a parcel.

A parcel is a class that acts as a holder for both data and IBinder objects that can be sent through an IBinder.

Parcelable has existed in the android framework all the way since API level 1.

 

Pareclable Interface Definition

Parcelable is an interface hence it’s implemented and not directly instantiated.

public interface Parcelable{}

Parcelable resides in the android.os package:

package android.os

Function

  1. Allows for the placement of arbitrary objects into a Parcel.

Usage

As an interfacce Parcelable has to be implemented by classes.

Those classes must have a non-null static field called CREATOR. This field is of data type that implements Parcelable.Creator.

Here’s an example:

 public class MyParcelable implements Parcelable {
     private int mData;

     public int describeContents() {
         return 0;
     }

     public void writeToParcel(Parcel out, int flags) {
         out.writeInt(mData);
     }

     public static final Parcelable.Creator<MyParcelable> CREATOR
             = new Parcelable.Creator<MyParcelable>() {
         public MyParcelable createFromParcel(Parcel in) {
             return new MyParcelable(in);
         }

         public MyParcelable[] newArray(int size) {
             return new MyParcelable[size];
         }
     };

     private MyParcelable(Parcel in) {
         mData = in.readInt();
     }
 }
Share



Share an Example

Share an Example

Browse
What is the capital of Egypt? ( Cairo )