Android Lunar Lander thread handling alternatives

回眸只為那壹抹淺笑 提交于 2020-01-24 10:59:07

问题


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() return, 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.


回答1:


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.



来源:https://stackoverflow.com/questions/5431590/android-lunar-lander-thread-handling-alternatives

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