Like many of the novices of android programming, I used Lunar Lander as a guide for implementing the SurfaceView. I'm practicing by creating a version of PONG. The basic structure of the code is the same as LunarLander. Obviously, I soon discovered the bug that was in Lunar Lander. The immediate way I got around this is by instantiating a new Thread object in SurfaceCreated() and starting it, when the original thread can't be started (which incidentally, is the same method that a lot of people suggested):
My main question is whether this is actually good practice? Instantiating a new thread object would mean instantiating everything the game requires, thereby leaving all previously instantiated data hanging. If you look at LunarLander itself, almost every core component of the game is in the thread. I've read a few threads where people ran
System.gc();
to do a garbage collect, but that was generally thought to be bad advice.
I'm trying another workaround where instead of joining the thread in SurfaceDestroyed(), I simply interrupt it. Furthermore, when the activity loses focus, I don't let run() retur开发者_高级运维n, but cause it to do absolutely nothing in the background while everything else is paused. I let onDestroy() in the activity life cycle destroy everything. The hope is so that all the data don't need to be re-instantiated, while the old data left hanging. Can this be a suitable alternative?
Thanks in advance.
Keeping the thread object while focus is lost is certainly possible provided the necessary synchronization is done correctly when you regain focus.
However, for simplicity's sake and to release resources when not in focus, you could extract the game state into a class not owned by the game thread and instead pass it to the thread when starting, allowing you to stop the thread in surfaceDestroyed() as done in the original code.
Obviously a thread object will be garbage for each time you loose focus, but the collection of these meager bytes shouldn't be a problem.
精彩评论