如何序列化一个包? [英] How to serialize a Bundle?

查看:181
本文介绍了如何序列化一个包?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想序列化一个Bundle对象,但似乎无法找到这样做的一个简单的方法。使用包裹似乎是一个选项不,因为我想存储序列化的数据保存到文件。

I'd like to serialize a Bundle object, but can't seem to find a simple way of doing it. Using Parcel doesn't seem like an option, since I want to store the serialized data to file.

就如何做到这一点任何想法?

Any ideas on ways to do this?

我想这样做的原因是为了保存和恢复我的活动状态,还当它杀死用户。我已创建我想要保存的onSaveInstanceState状态的包。而Android只有保持这种捆绑活动时被系统杀死。当用户杀死了活动,我需要存储它自己。因此,我想序列化并将其存储到文件。当然,如果你有完成同样的事情任何其他方式,我很感激这一点。

The reason I want this is to save and restore the state of my activity, also when it's killed by the user. I already create a Bundle with the state I want to save in onSaveInstanceState. But android only keeps this Bundle when the activity is killed by the SYSTEM. When the user kills the activity, I need to store it myself. Hence i'd like to serialize and store it to file. Of course, if you have any other way of accomplishing the same thing, i'd be thankful for that too.

编辑: 我决定EN code我的状态为的JSONObject 中的,而不是束。 JSON对象可以被放在一个包作为一个序列化或存储到文件。也许不是最有效的方式,但它的简单,它似乎工作正常。

I decided to encode my state as a JSONObject instead of a Bundle. The JSON object can then be put in a Bundle as a Serializable, or stored to file. Probably not the most efficient way, but it's simple, and it seems to work ok.

推荐答案

存储任何Parcelable到一个文件是很容易的:

storing any Parcelable to a file is very easy:

FileOutputStream fos = context.openFileOutput(localFilename, Context.MODE_PRIVATE);
Parcel p = Parcel.obtain(); // i make an empty one here, but you can use yours
fos.write(p.marshall());
fos.flush();
fos.close();

享受!

这篇关于如何序列化一个包?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆