I’m attempting to learn the ropes of Game Development and Android and it’s been a great learning experience so far, but the Android Activity Lifecycle stuff has me a little stuck.
Let’s say I have three Activities –
- Game Menu
- Level Select
- The Actual Game (2d Game using the
SurfaceView).
I would think I need to load all Bitmaps and Sounds outside the Actual Game Activity to prevent from having to unload and reload them everytime onDestroy and onCreate is called, for example, like when the phone goes to sleep, or everytime a new level is chose from the level select screen.
This led me to the Singleton approach which makes sense and seems to be what I’m after, but I don’t fully understand where I would need to unload the Singleton to make sure it gets GC’d, for example, could I release it in the Game Menu onDestroy, if so, how do I know if the Game Menu Activity will hang around indefinately. I’ve also seen mention of Android being able to kill the singleton on its own. I have also read some about using the Application Context that would give me lifecycle.
What would be the best way to approach this? Do I really want to unload and reload all the resources in the Game Activity? Am I going in the right direction with the Singleton or Application idea?
Always assume your activity will be destroyed. Assuming otherwise will always give you headaches.
Personally I’ve taken the approach of having my Loading and Main Game activity one in the same in the sense that while the surfaceview is being created I can overlay a loading graphic/screen on top of the surfaceview and preload all the bitmaps/sounds in onCreate.
The level select and other activities are then spawned from the main activity, typically through a startActivityForResult. This allows you to 1) Create a loading screen while preloading/instantiation takes place 2) Present a main screen with Start Game etc… 3) Have the surfaceView already created but being hidden or behind the main game activity.
Obviously you shouldn’t be starting threads or anything until they start the game but the surfaceview itself can be ready to go. In that way Start Game is seamless and quick. You just hide all the other Views and bring your SurfaceView to the top.
But again, always assume your activity will be destroyed. Meaning saving game state etc…
With regards to the Main Game you should split your game into 2 threads – one for game logic and one for the actual drawing on the canvas. In your Game Activity you should override:
Always profile your app using the tools available. Have your application update threads and track it using the resource tracker to make sure you aren’t using temporary objects. Always create such objects in your main activity/class and reference them. My app never runs GC unless I tell it to and it runs smoothly using the aforementioned design.
Hope this helps. I’ve written some posts with regards to Android Game development at methodin.tumblr.com.