從技術上講,如果我沒有記錯的話,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