• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

How do I save and restore a game's state when using SurfaceView and threads in Android Studio?

 
Eric Sweeten
Greenhorn
Posts: 21
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I have the GameActivity class, which sets the content view to a GamePanel. The GamePanel extends SurfaceHolder. When I click on an ad and it leaves the game and comes back, the screen is black. What am I supposed to put in the onDestroy() and onResume() methods? If I reinstantiate the GamePanel and put it in the content view again, it reloads the game just fine, but I want it to continue where it left off.
 
Ankit Garg
Sheriff
Posts: 9580
33
Android Google Web Toolkit Hibernate IntelliJ IDE Java Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
How are you displaying/opening the ad from the application? Your activity might be getting killed I guess, add a few loggers to the different lifecycle methods to see what's happening to your application when it goes to the background. You can use the onPause callback (preferably onSaveInstanceState callback) to save your game's state and load that state in the onCreate/onRestoreInstanceState methods.

Check the lifecycle documentation for more info...
 
Eric Sweeten
Greenhorn
Posts: 21
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I found a workaround that works flawlessly. I found out that when the phone leaves the app, it kills all the instance variables. However, it saves the static variables. I don't know why. Do you know why? I noticed this as I started creating what I wanted saved as static variables. I then decided a very good way of doing it would be to make the entire Game instance a static instance. When I do this, the exact state of the game is saved. I can be shooting at an enemy, while another enemy is in the middle of exploding, and when I close the app and reopen, it continues exactly at that state.

Weird, but whatever, it works. Why is it the instance objects are deleted but everything static remains? What I do now is reinstantiate the GamePanel and MainThread, and I think the SurfaceHolder too, and I have a static Game object and static boolean that keeps track of whether or not the Game object has already been instantiated. If not (as in first load), it instantiates it.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic