Put objects into bundle

限于喜欢 提交于 2019-12-02 04:38:44

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.

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.

Serialization:

@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());
        }
    }
} 

Deserialization:

@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) {}
    }
}

Basically you have 2 options

1 - Implement Serializable, really simple to implement, but has a bad drawback which is performance.

2 - Implement Parcelable, very fast, but you need to implement the parser method (writeToParcel()), which basically you have to serialize manually, but afterwards bundle will call it automatically for you and will produce a much more performatic serialization.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!