开发者

Saving the state of a SurfaceView when the Activity is stopped and resumed

I have an Activity with a SurfaceView that is managed by a game engine (thread). I'm overriding the onCreate and the onSaveInstanceState for managing the save/restore stat开发者_开发百科e of the thread.

When the preferences screen is accessed from the menu of that Activity, that Activity goes through its lifecycle to onStop; when the preferences screen is closed, the Activity starts again at onResume, so onCreate does not happen. The thread however is in a state of TERMINATED and therefore cannot be resumed.

Yes, I can just create a new instance of the thread--but how can I restore the state? I tried overriding onRestoreInstanceState as well, but after a quick test and reading a little more thoroughly I realized that it's not called in this situation because it's called between onStart and onResume.

What's the best way to handle this?


I think you do need to target the onSaveInstanceState and either onRestoreInstanceState or use the onCreate functionality to do it (onRestoreInstanceState is called after onStart, whereas onCreate is called before onStart - so you'll need to use the onCreate way of doing things, although I'll list both below)

Save your state in the onSaveInstanceState of your activity - you may need to write getter methods in to your surfaceView class:

protected void onSaveInstanceState(Bundle outState) {
  outState.putInt(YourSurfaceViewClass.SOME_ID, surfaceViewClass.getVar());
  super.onSaveInstanceState(saveBundle);
}

And restore the values in onCreate:

public void onCreate(Bundle savedInstanceState) {
  if (savedInstanceState != null){
    value = savedInstanceState.getInt(YourSurfaceViewClass.SOME_ID);
  }
}

or restoreInstanceState:

@Override
protected void onRestoreInstanceState(Bundle savedInstanceState) {
    value = savedInstanceState.getInt(YourSurfaceViewClass.SOME_ID);
}

These methods will be called when you access the preferences screen and then use onCreate to restore your thread's state.


The problem seems to be with the dirty design of my app. Since the game engine itself is extending the Thread class and automatically being set to TERMINATED, my only option with the current design is to add logic to the surfaceCreated method. In there, I can check the state of the thread:

If it's TERMINATED, I can create a Bundle and pass it to my engine's saveState method. Once I have the state, I make the thread a new game engine thread and pass in the recently saved Bundle. I think continue as normal (start the thread).

This works, but the best way would be to move the actual Thread logic to a separate class. Since the game engine isn't actually being cleared, I would just be creating a new Thread instance instead of recreating the entire game engine, so this is what I'll do.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜