Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

LiveWallpaper: java.lang.IllegalStateException: Surface has already been released

Tags:

android

I have created a Live Wallpaper.

It works fine, but if I want long press on the screen and I go to Live Wallpapers and open my Live Wallpaper in preview, after that the Wallpaper goes havoc.

I get the exception: java.lang.IllegalStateException: Surface has already been released.

like image 313
Lisa Anne Avatar asked Dec 18 '13 18:12

Lisa Anne


1 Answers

It's hard to tell without your code, but I was seeing this exception, but only when I navigated away from the preview before it was finished loading.

In my case, it was being caused because I started an AsyncTask off from the onSurfaceCreated method, but then by the time it got to the point where I called surfaceHolder.lockCanvas() the surface had already been destroyed.

To get round this I overrode the onSurfaceDestroyed method, and had a variable global to that class called drawOk, like this:

    @Override
    public void onSurfaceCreated(SurfaceHolder holder) {
        super.onSurfaceCreated(holder);
        handler.post(reload);
        drawOk = true;
    }

    @Override
    public void onSurfaceDestroyed(SurfaceHolder holder) {
        super.onSurfaceDestroyed(holder);
        handler.removeCallbacks(reload);
        drawOk = false;
    }

    @Override
    public void onVisibilityChanged(boolean visible) {
        super.onVisibilityChanged(visible);
        if(visible) {
            handler.post(reload);
            drawOk = true;
        } else {
            handler.removeCallbacks(reload);
            drawOk = false;
        }
    }

    private void draw() {

        SurfaceHolder surfaceHolder = getSurfaceHolder();
        Canvas canvas = null;

        if(drawOk) {
            canvas = surfaceHolder.lockCanvas();
            if(canvas != null) {
                                // ...
            }
        }
    }   

There is a surfaceHolder.isCreating(), but not a surfaceHolder.isCreated(). This might not be the right way to do it, but it is working for me.

like image 106
Katy Montgomerie Avatar answered Oct 25 '22 16:10

Katy Montgomerie