Jak z Pomocą Parcela utworzyć Parcelable do tablicy bajtów?

Chcę marshall i unmarshall klasy, która implementuje Parcelable do / z tablicy bajtów. zdaję sobie sprawę z faktu, że reprezentacja Parcelowalna nie jest stabilna i dlatego nie jest przeznaczona do długotrwałego przechowywania instancji. ale mam przypadek użycia, w którym muszę serializować obiekt i nie jest to showstopper, jeśli unmarshalling nie powiedzie się z powodu wewnętrznej zmiany Androida. Również Klasa już implementuje interfejs Parcelable.

Biorąc pod uwagę klasę MyClass implements Parcelable, Jak mogę (ab)użyć interfejsu Parcelable do marshalling/unmarshalling?

Author: Flow, 2013-08-01

2 answers

Najpierw Utwórz klasę pomocniczą ParcelableUtil.java :

public class ParcelableUtil {    
    public static byte[] marshall(Parcelable parceable) {
        Parcel parcel = Parcel.obtain();
        parceable.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;
    }
}

Z pomocą powyższej klasy util możesz wyróżnić / wyróżnić instancje swojej klasy MyClass implements Parcelable w następujący sposób:

Unmarshalling (z CREATOR)

byte[] bytes = …
MyClass myclass = ParcelableUtil.unmarshall(bytes, MyClass.CREATOR);

Unmarshalling (Bez CREATOR)

byte[] bytes = …
Parcel parcel = ParcelableUtil.unmarshall(bytes);
MyClass myclass = new MyClass(parcel); // Or MyClass.CREATOR.createFromParcel(parcel).

Rozrząd

MyClass myclass = …
byte[] bytes = ParcelableUtil.marshall(myclass);
 109
Author: Flow,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-08-11 09:07:52
public static byte[] pack(Parcelable parcelable) {
    Parcel parcel = Parcel.obtain();
    parcelable.writeToParcel(parcel, 0);
    byte[] bytes = parcel.marshall();
    parcel.recycle();
    return bytes;
}

public static <T> T unpack(byte[] bytes, Parcelable.Creator<T> creator) {
    Parcel parcel = Parcel.obtain();
    parcel.unmarshall(bytes, 0, bytes.length);
    parcel.setDataPosition(0);
    return creator.createFromParcel(parcel);
}

MyObject myObject = unpack(new byte[]{/* bytes */}, MyObject.CREATOR);
 -3
Author: Yefimchuk Roman,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2014-03-16 23:20:36