将对象放入包 [英] Put objects into bundle
问题描述
问候,
我有一个游戏,我要保存在移动画布捆绑的对象(creatues),这样,当有人暂停/离开应用程序,对象可以留他们在那里。
I have a game, and i want to save the objects ( creatues ) that move on canvas to a bundle so that when someone pauses/leaves the app, the objects can stay where they were.
我已经看过了LunarLanding游戏,他们节省了航天飞机的坐标成束,并从中读出我想要做相同的(如果没有更好的办法),但我有一个自定义类型的对象,我不知道如何保存它们,并从包中读取。
I have looked at the LunarLanding game where they save the coordinates of the space shuttle into bundles and read from them and i want to do same ( if there is no better way ) but i have objects of a custom type and i am not sure how to save them and read from the bundle.
我可以做保存单独的对象的所有部件,并把他们重新走到一起,但我有很多的对象,而且也只是丑陋的code做了这一切。
I could do the save of all the parts of the object individually and put them back together, but i have a lot of objects and that would just be ugly code to do all that.
这将是好了,如果我能一个对象保存到一个包,但到目前为止,我没有运气上搜索如何这样做互联网。
It would be just great if i could save an object to a bundle, but so far i had no luck searching the internet on how to do so.
我也想实施 Parcelable
来我的对象,但我想知道是否有任何其他方式。
I was also thinking about implementing Parcelable
to my object, but i want to know if there is any other way.
有什么建议?
谢谢!
Any suggestions?
Thanks!
推荐答案
从技术上来说,的onSaveInstanceState()方法被调用大多只在方向变化,如果我没记错的话。如果你想持久性数据,你应该使用的onPause()或的onStop()回调,和序列化的游戏状态。
Technically, the onSaveInstanceState() method is called mostly only on orientation change if I remember correctly. If you want to make persistent data, you should use the onPause() or onStop() callback, and serialize the game state.
你能做到这一点的方式要么是通过存储状态SQLite数据库(似乎矫枉过正),或者让这个你可以序列化,通过实施序列化跟踪的实体对象接口
,和对象保存到文件中。
The ways you can do that is either by storing the state in a SQLite database (seems overkill), or make it so that you can serialize the object that keeps track of the entities via implementing the Serializable interface
, and save the object to a file.
连载:
@Override
public void onPause()
{
super.onPause();
FileOutputStream out = null;
try
{
out = openFileOutput("GameModelBackup",Context.MODE_PRIVATE);
try
{
ObjectOutputStream oos = new ObjectOutputStream(out);
oos.writeObject(gm);
}
catch(IOException e)
{
Log.d(this.getClass().toString(), e.getMessage());
}
}
catch(FileNotFoundException e)
{
Log.d(this.getClass().toString(), e.getMessage());
}
finally
{
try
{
if(out != null) out.close();
}
catch(IOException e)
{
Log.d(this.getClass().toString(), e.getMessage());
}
}
}
反序列化:
@Override
public void onResume()
{
super.onResume();
FileInputStream in = null;
try
{
in = openFileInput("GameModelBackup");
ObjectInputStream oos = new ObjectInputStream(in);
try
{
gm = (GameModel)oos.readObject();
}
catch(ClassNotFoundException e)
{
gm = null;
}
}
catch(IOException e)
{
Log.d(this.getClass().toString(), e.getMessage());
}
finally
{
try
{
if(in != null) in.close();
}
catch(IOException e) {}
}
}
这篇关于将对象放入包的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!