如何在Parcel的帮助下将一个Parcelable编组和解组为字节数组?

我想编组和解编实现Parcelable到/从字节数组的类。我很好地意识到以下事实:Parcelable表示形式不稳定,因此并不意味着可以长期存储实例。但是我有一个用例,我需要序列化一个对象,并且如果由于内部Android更改而导致解组失败,则这不是最重要的事情。而且该类已经在实现Parcelable接口。

给定一个类MyClass implements Parcelable,我如何(ab)使用该Parcelable接口进行编组/解组?


慕妹3242003
浏览 888回答 3
3回答

森林海

public static byte[] pack(Parcelable parcelable) {&nbsp; &nbsp; Parcel parcel = Parcel.obtain();&nbsp; &nbsp; parcelable.writeToParcel(parcel, 0);&nbsp; &nbsp; byte[] bytes = parcel.marshall();&nbsp; &nbsp; parcel.recycle();&nbsp; &nbsp; return bytes;}public static <T> T unpack(byte[] bytes, Parcelable.Creator<T> creator) {&nbsp; &nbsp; Parcel parcel = Parcel.obtain();&nbsp; &nbsp; parcel.unmarshall(bytes, 0, bytes.length);&nbsp; &nbsp; parcel.setDataPosition(0);&nbsp; &nbsp; return creator.createFromParcel(parcel);}MyObject myObject = unpack(new byte[]{/* bytes */}, MyObject.CREATOR);
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Android