unlockCanvasAndPost中的IllegalArgumentException(android动态壁纸)

Ant*_*kov 5 java multithreading android live-wallpaper

我创建了我的第一个动态壁纸,在一个单独的线程中实现绘图.所以现在我有了一个WallpaperService和我的WallpaperPainter来完成这项工作.问题是,我得到一个IllegalArgumentException在unlockCanvasAndPost某些设备上的方法(三星Note是一个).我已经阅读了所有可以找到的建议,但无法修复该错误.看起来像unlockCanvasAndPost表面被破坏时被调用,因此画布无效.以下是代码的基本部分:

在壁纸服务:

    @Override
    public void onSurfaceChanged(SurfaceHolder holder, int format, int width,
            int height) {
        super.onSurfaceChanged(holder, format, width, height);
        painting.setSurfaceSize(width, height);
    }

    @Override
    public void onSurfaceCreated(SurfaceHolder holder) {
        super.onSurfaceCreated(holder);
        painting.start();
    }

    @Override
    public void onSurfaceDestroyed(SurfaceHolder holder) {
        boolean retry = true;
        painting.stopPainting();
        while (retry) {
            try {
                painting.join();
                retry = false;
            } catch (InterruptedException e) { }
        }
        super.onSurfaceDestroyed(holder);
    }
Run Code Online (Sandbox Code Playgroud)

在绘画线程中:

public void stopPainting() {
    this.run = false;
    synchronized(this) {
        this.notify();
    }
}

public void run() {
    this.run = true;
    Canvas c = null;
    while (run) {
        try {
            synchronized (this) {
                Thread.sleep(50);
                c = this.surfaceHolder.lockCanvas();
                doDraw(c);
            }
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            if (c != null) {
                this.surfaceHolder.unlockCanvasAndPost(c); // << -- HERE IS THE PROBLEM
            }
        }
        // if pause...
        synchronized (this) {
            if (wait) {
                try {
                    wait();
                } catch (Exception e) { }
            }
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

谁能给我任何线索我做错了什么?我是Java和Android的新手.

Gra*_*ray 1

我没有看到明确的问题,但这里有一些想法。

  • 您有可能解锁尚未锁定的画布。c = null;我会在循环的顶部设置while,否则之前的值c将在下次循环时解锁。

    while (run) {
        Canvas c = null;
        ...
    
    Run Code Online (Sandbox Code Playgroud)
  • 您的run字段应标记为,volatile因为它由多个线程访问。

  • Thread.sleep(...)切勿在块内调用synchronized。这是一个非常糟糕的做法,因为它不必要地阻塞其他线程。

  • 确保至少记录异常情况。要极其小心catch (Exception e) {}。所做的一切只是掩盖你的问题。

  • join()做内部循环没有多大意义while。如果您的线程被中断,您应该中断绘画线程并退出。

  • 由于您既在睡觉又在等待,因此取消睡眠并执行以下操作会更有意义:

    try {
       synchronized (this) {
           if (wait) {
              wait();
           else {
              wait(50);
           }
       }
    } catch (Exception e) {
       e.printStackTrace();
    }
    
    Run Code Online (Sandbox Code Playgroud)