Reputation: 11
I have a simple android brick breaker game which is currently running on a single thread. I have been tasked to design the game to incorporated multi-threading, but am having issues finding a simple enough tutorial to guide me through it. I've got the game running smoothly at the moment, it has MainActivity, GameView, GameLogic and SpriteObject classes, doing as you would pretty much expect they would do from their names. How and where would I implement another thread that for the moment simply incremented a external variable say 'timer' every so often?
Please bare in mind I've been struggling to get my head around threads so you might have to be quite patronizing for me to get it.
Thanks
Upvotes: 1
Views: 446
Reputation: 1252
Android have a class called AsyncTask that is pretty nifty :)
Just create a class that extends it like this:
public class myTask extends AsyncTask<Object, Object, Object> {
@Override
protected Object doInBackground(Object... arg0) {
//Increase timer and wait here in a loop
return null;
}
protected void onPostExecute(Object result) {
//Something you want to do when done?
};
}
To start it simply call
new myTask().execute(INPUT or null);
The part are the class type of your Parameters to execute, class type of an object that can be used for updating visual progress and the value that doInBackground returns and onPostExecute gets, respectively.
For a guide, go here: http://android-developers.blogspot.com/2009/05/painless-threading.html
And documentation: http://developer.android.com/reference/android/os/AsyncTask.html
Upvotes: 1
Reputation: 743
so if its just doing something periodically just use scheduler/Timer no need to create a new thread
import java.util.concurrent.ScheduledFuture;
private void startUpdateTimer(){
final Runnable updater = new Runnable() {
@Override
public void run() {
try {
updateTheActualVariable();
} catch (Exception ex) {
Log.e("error in getting updates", ex.getMessage());
}
}
};
final ScheduledFuture updaterHandle = sheduler.scheduleAtFixedRate(updater, 0, Constants.GET_UPDATES_PERIOD, TimeUnit.SECONDS);
}
Read more here http://developer.android.com/reference/java/util/concurrent/ScheduledExecutorService.html
You can also you good old java timer http://developer.android.com/reference/java/util/Timer.html
Upvotes: 1