I have a Pong game that I wrote in Java and I'm trying to port it to Android. (It's my first Android game ;).
In Java I used a Timer
object which basically updated the Game values (ball/paddles position) and then redrew the screen.
I'm trying to implement the same functionality in Android but I'm getting a number of errors.
My program consists of a PongView
class which is the visual part of the game, and a PongDriverActivity
class which uses PongView
for its view. If I have a looping thread invalidating PongView
I get an error because the thread can't touch a view spawned on another thread.
I assume I need to do some sort of AsyncTask
, but I'm not sure how to loop that.
Any suggestions on what would be the best way to implement this?
There's many ways to do this. Android does support normal Java
Thread
objects, and you can use those. You can search (SO) forandroid game loop
and probably find lots of examples. But, if you'd like to tryAsyncTask
, here's a sample implementation:Then, your Activity:
And, then (maybe inside PongDriverActivity.java, an inner class):
The task's
doInBackground()
method will be run on a background thread, so you must not directly modify the UI from there. But, all the otherAsyncTask
methods I override above are called on the UI thread, so it's safe to perform UI work in any of them.This code assumes the paddle is controlled by a seek bar, which you'd make your
Activity
a change listener for. Lots of other ways to do it, too.I just implemented a crude game stop mechanism, which you could hook up to a button. If you want to allow the user to pause and resume, you can search for implementations to pause/resume threads, which should be applicable here, too. For example:
How to Pause and Resume a Thread in Java from another Thread
More Reading ...
See this writeup for some discussion of game loop speeds ...
and maybe take a look at this discussion, too