I have a card game in which play passes automatically from player to play. There are 3 non-user players and play flows from one to the next without user intervention every number of seconds (as specified by the user).
I have 2 methods that control the flow:
- awaitTurn which is used to wait for the start of the turn
- doTurn when the actual turn starts
They are both within the same class.
Each player has their own instance of the class.
After the player has finished its turn it then invokes the “awaitTurn()” of the next player and so on.
After the 3 automated player makes its turn then control is sent to the “awaitTurn()” of the user which effectively does nothing and allows the user to make his/her turn.
In order to pause I wrote the following code:
public void awaitTurn()
{
GameActivity.thisActivity.displayHideCont(View.VISIBLE);
if (GameActivity.settings.getPauseTimeBetweenTurns() > 0){
startNextPlayerTurn = new Runnable() {public void run() {doTurn();}};
if (handler == null)
handler = new Handler();
else
handler.removeCallbacks(startNextPlayerTurn);
int extraDelay = GameActivity.settings.getCardAnimationTime();
handler.postDelayed(startNextPlayerTurn,
(GameActivity.settings.getPauseTimeBetweenTurns())*1000 + extraDelay);
}
return;
}
In doTurn I have:
public void doTurn() {
if (startNextPlayerTurn!=null) // just in case we are still pausing
handler.removeCallbacks(startNextPlayerTurn);
...
}
So, the big question is, whether I am building here an infinite depth of threads one from within the other or not.
You do not create threads in your application. You run all functions in your main UI thread (assuming handler is created in UI thread).
Here is what happens:
handler.postDelayed(runnableX, delayX)putsrunnableXinto UI queue and will be processed afterdelayX.runnableXand runs it.If you call
handler.removeCallbacks(runnableX), then all pending messages withrunnableXare removed from queue (and will not run).If you do multiple calls to
handler.postDelayes(runnableX, delayX), then yourrunnableXwill be called multiple times. But each time it will be run on UI thread.Unfortunately there is no way to check whether your
runnableXis already posted to queue.