zkello
zkello

Reputation: 239

Sleeping a Thread in Canvas

In my game I want to draw the screen black after losing or winning a level and then draw a message in white on to the screen. After a few seconds delay I then want the screen to disappear when touched. Below is part of my draw() method. The problem is that screen freezes (or the thread sleeps) before the screen is drawn black and the text is drawn, even though the sleep command is after the text and canvas is drawn. Any ideas why this is happening?

if (state == WIN || state == LOSE){
        canvas.drawColor(Color.BLACK);
        message = "Touch Screen To Start";                                                
        canvas.drawText(message + "", mCanvasWidth / 2, mCanvasHeight / 2, white);
        try {
        GameThread.sleep(500);
        } catch (InterruptedException e) {
        e.printStackTrace();
        }
    }       

Upvotes: 0

Views: 1214

Answers (3)

MJD
MJD

Reputation: 1193

I have a feeling that the canvas function doesn't actually display anything until it returns. Especially if you are running on Android >3.0 with hardware acceleration, or any configuration with double buffering, it won't actually update the screen until it finishes.

Instead when you draw the black screen, store the current time. Something like:

mStartTime = System.currentTimeMillis();

Then in the function watching for presses, check how many seconds have passed and see if enough time is happening, something like:

if( (System.currentTimeMillis() - mStartTime)/1000 > 5){
    //Put code here to run after 5 seconds
}

This should draw your text and avoid blocking the Ui thread (a big no no in every respect).

Upvotes: 2

Code Droid
Code Droid

Reputation: 10472

Use CountDownTimer

 http://developer.android.com/reference/android/os/CountDownTimer.html


 new CountDownTimer(30000, 1000) {

 public void onTick(long millisUntilFinished) {
     mTextField.setText("seconds remaining: " + millisUntilFinished / 1000);
     // Here you do check every second = every 1000 milliseconds
 }

 public void onFinish() {
    // Here you can restart game after 30 seconds which is 30K milliseconds.
     mTextField.setText("done!");
 }
}.start();

Upvotes: 0

Matt N
Matt N

Reputation: 146

It could be that the call to drawText is taking a few fractions of a second longer than you realize, and since you immediately call sleep, you are actually sleeping the thread before you draw.

Try putting a small loop, for( i < 10000 ) or something before the call to sleep and see if that helps.

Upvotes: 1

Related Questions