Android Studio - 无法捕获异常锁定表面

时间:2015-03-02 03:29:23

标签: java android exception canvas android-studio

您好我在Android Studio中制作了游戏。偶尔当我在模拟器上关闭并重新启动应用程序时,我会将以下垃圾邮件发送到logcat:

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

我尝试使用try-catch块来包围canvas = this.surfaceHolder.lockCanvas();但是没有捕到异常。有没有办法在尝试锁定之前检查画布是否被锁定?

这是我在MainThread.java类中的代码

    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();}
            }
    }

1 个答案:

答案 0 :(得分:2)

您可以识别并使用布尔常量进行检查;

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


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

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

这可以防止异常。它已经锁定时不会锁定,反之亦然。