从技术上讲,如果我没有记错的话,onSaveInstanceState()方法主要只在方向改变时被调用。如果你想持久化数据,你应该使用onPause()或onStop()回调函数,并且序列化游戏状态。
你可以通过将状态存储在SQLite数据库中(看起来是多余的)来做到这一点,或者让它可以通过实现Serializable interface
来序列化跟踪实体的对象,并保存对象到一个文件。
连载:
@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) {}
}
}
你这是什么意思捆绑? SharedPreference? –
不,像一个包来存储当前数据[link](http://developer.android.com/reference/android/os/Bundle.html) – Pavle37
他意味着通过保存实例状态包发送数据状态包 – EpicPandaForce