1

我有一个Bundle并将它作为字节数组存储到磁盘中。现在,当我检索它时,我会使用字节数组。我怎样才能再次将其转换为Bundle

byte fileContent[] =  new byte[(int)file.length()];
int numerOfReturnedbytes = 0;

try {
    //read the stream and set it into the byte array readFileByteArray
    //and returns the numerOfReturnedbytes. If returns -1 means that
    //that the end of the stream has been reached.
    numerOfReturnedbytes = fis.read(fileContent);
    fis.close();
} catch (IOException e) {
    e.printStackTrace();
}

if (numerOfReturnedbytes == -1) {
    return;
} else {
    //creating empty parcel object
    Parcel parcel = Parcel.obtain();
    //un-marshalling the data contained into the byte array  to the parcel
    parcel.unmarshall(fileContent, 0, numerOfReturnedbytes);
}

fileContent字节数组。关于如何解决我的问题的任何想法?

4

3 回答 3

0

不要那样做。来自 Android 文档:

Parcel 不是通用的序列化机制。此类(以及用于将任意对象放入 Parcel 的相应 Parcelable API)被设计为高性能 IPC 传输。因此,将任何 Parcel 数据放入持久存储是不合适的:Parcel 中任何数据的底层实现的更改都可能导致旧数据不可读。

这意味着,在操作系统升级后,您的应用程序写入的数据可能变得不可读。

于 2013-01-11T15:33:01.650 回答
0

将 Bundle 转换为 ByteArray

    public byte[] bundleToBytes(@NonNull Bundle bundle) {
        Parcel parcel = Parcel.obtain();
        parcel.writeBundle(bundle);
        byte[] bytes = parcel.marshall();
        parcel.recycle();
        return bytes;
    }

将 ByteArray 转换为 Bundle

    @NonNull
    public Bundle bytesToBundle(byte[] bytes) {
        Parcel parcel = Parcel.obtain();
        parcel.unmarshall(bytes, 0, bytes.length);
        parcel.setDataPosition(0);
        Bundle bundle = parcel.readBundle(ClassWithinProject.class.getClassLoader());
        parcel.recycle();
        return bundle;
    }
于 2020-01-10T10:40:22.760 回答
-1

会不会是这样的:

Bundle bundle = Bundle.CREATOR.createFromParcel(parcel);

一旦你有包裹?

编辑

或者是

Bundle bundle = parcel.readParcelable(null);

? 我不记得了。我已经阅读了文档,但你知道...

(实际上,我真的不知道什么是最好的,它们似乎做的事情几乎相同)

编辑 2

还有

Bundle bundle = parcel.readBundle();

令人惊讶的是文档中的信息量。我应该经常去那里。

于 2013-01-11T15:33:07.823 回答