Java – Android Studio – Unable to catch exception lock surface

Android Studio – Unable to catch exception lock surface… here is a solution to the problem.

Android Studio – Unable to catch exception lock surface

Hello, I made a game in Android Studio. Sometimes when I close and restart the app on the emulator, I get the following spam in logcat:

Exception locking surface
java.lang.IllegalStateException: Surface was already locked

I tried surrounding canvas with try-catch block = this.surfaceHolder.lockCanvas(); But no exception is caught. Is there a way to check if a Canvas is locked before attempting to lock it?

This is my code in the MainThread.java class

    while (running) {
        startTime = System.nanoTime();
        canvas = null;

try {
     canvas = this.surfaceHolder.lockCanvas();
            synchronized (surfaceHolder) {
                 update game state
                this.gamePanel.update();
                 draws the canvas on the panel
                this.gamePanel.draw(canvas);
            }

} catch(Exception e){e.printStackTrace(); }finally {
             in case of an exception the surface is not left in
             an inconsistent state
            if (canvas != null) {
                try {

surfaceHolder.unlockCanvasAndPost(canvas);

}
                catch(Exception e){e.printStackTrace(); }
            }
    }

Solution

You can identify and check with the boolean constant;

    //create the boolean;
private boolean cLocked = false;

Locking
 if (!cLocked){
    canvas = this.surfaceHolder.lockCanvas();
    cLocked = true;
}

Unlocking
if (cLocked) {
    surfaceHolder.unlockCanvasAndPost(canvas);
    cLocked = false;
}

This will prevent exceptions. It does not lock when it is already locked, and vice versa.

Related Problems and Solutions