Create ParcelableUtil class.

This commit is contained in:
Phillip Hsu 2017-02-28 14:31:54 -08:00
parent 7bed415932
commit e68ac72629

View File

@ -0,0 +1,31 @@
package com.philliphsu.clock2.util;
import android.os.Parcel;
import android.os.Parcelable;
/**
* Utilities to marshall and unmarshall a {@code Parcelable} to and from a byte array.
*/
public final class ParcelableUtil {
public static byte[] marshall(Parcelable parcelable) {
Parcel parcel = Parcel.obtain();
parcelable.writeToParcel(parcel, 0);
byte[] bytes = parcel.marshall();
parcel.recycle();
return bytes;
}
public static Parcel unmarshall(byte[] bytes) {
Parcel parcel = Parcel.obtain();
parcel.unmarshall(bytes, 0, bytes.length);
parcel.setDataPosition(0); // This is extremely important!
return parcel;
}
public static <T> T unmarshall(byte[] bytes, Parcelable.Creator<T> creator) {
Parcel parcel = unmarshall(bytes);
T result = creator.createFromParcel(parcel);
parcel.recycle();
return result;
}
}