Snippets

Victor Apoyan HowTo: Pass Interface in Parceable

Created by Victor Apoyan
class Item implements Parcelable {

    public interface IAction {
        void execute();
    }

    private int id;
    private IAction action;
    private IBinder binder = new Binder() {
        @Override
        protected boolean onTransact(int code, Parcel data, Parcel reply, int flags) throws RemoteException {
            action.execute();
            return true;
        }
    };

    protected Item(Parcel in) {
        id = in.readInt();
        binder = in.readStrongBinder();
    }

    public Item(int id, IAction action) {
        this.id = id;
        this.action = action;
    }

    public static final Creator<Item> CREATOR = new Creator<Item>() {
        @Override
        public Item createFromParcel(Parcel in) {
            return new Item(in);
        }

        @Override
        public Item[] newArray(int size) {
            return new Item[size];
        }
    };

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

    @Override
    public void writeToParcel(Parcel dest, int flags) {
        dest.writeInt(id);
        dest.writeStrongBinder(binder);
    }

    public void execute() {
        try {
            Parcel data = Parcel.obtain();
            binder.transact(0, data, null, 0);
        } catch (RemoteException e) {
            e.printStackTrace();
        }
    }
}

Comments (0)

HTTPS SSH

You can clone a snippet to your computer for local editing. Learn more.