Search code examples
javathread-sleepunhandled-exception

thread.sleep(long millis) doesn't work in Android


I want to do a simple animation in Android. I followed this tutorial series to setup the basic java code:

https://www.youtube.com/watch?v=UH2OWnq7NQ4

In order to be able to control the frame rate, I added the line thread.sleep(500);. However, this line gets underlined in red and if I hover above it, it says:

Unhandled exception: java.lang.interruptedException 

What am I doing wrong? Thank you!

public class AnimationActivity extends SurfaceView implements Runnable {

    Thread thread = null;
    boolean canDraw = false;

    Bitmap backgroundBlack;
    Canvas canvas;
    SurfaceHolder surfaceHolder;

    public AnimationActivity(Context context) {
        super(context);
        surfaceHolder = getHolder();
        backgroundBlack = BitmapFactory.decodeResource(getResources(), R.drawable.background_black);

    }

    @Override
    public void run() {
        while (canDraw) {
            if (!surfaceHolder.getSurface().isValid()) {
                continue;
            }

            canvas = surfaceHolder.lockCanvas();
            canvas.drawBitmap(backgroundBlack,0,0, null);

            //drawing stuff here

            surfaceHolder.unlockCanvasAndPost(canvas);

            thread.sleep(500)
        }
    }

    public void pause() {
        canDraw = false;

        while (true) {
            try {
                thread.join();
                break;
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }

        thread = null;
    }

    public void resume() {
        canDraw = true;
        thread = new Thread(this);
        thread.start();
    }
}

Solution

  • It is not "not working" - but it might throw an InterruptedException that you either have to declare to throw too (throws InterruptedException in the method signature), or you should catch it:

    try {
        Thread.sleep(500);
    } catch (InterruptedException e) {
        e.printStackTrace();
    }
    

    PS: sleep is a static method and should be called in a static way: Thread.sleep instead of thread.sleep