还有一篇关于相同异常的文章,但是该问题的答案是确保在致电Canvas
之前,我的this.holder.getSurface().unlockCanvasAndPost(this.canvas)
不为null。就我而言,即使canvas
不为null,SurfaceView
对象被锁定并创建了表面,我仍然会遇到此异常。以下是两种方法,我每秒从与我的主线程并发运行的Thread
调用60次:
public void start_draw_sequence() {
if (!surface_locked && this.holder.getSurface().isValid()) { // check if not locked already
if (android.os.Build.VERSION.SDK_INT >= 23) {
this.canvas = this.holder.getSurface().lockHardwareCanvas();
} else {
this.canvas = this.holder.getSurface().lockCanvas(null);
}
surface_locked = true;
}
if (this.canvas != null) {
this.canvas.clipRect(0, 0, this.canvas.getWidth(), this.canvas.getHeight());
}
}
public void end_draw_sequence() {
if (this.canvas != null && surface_locked && surface_created) {
this.holder.getSurface().unlockCanvasAndPost(this.canvas);
surface_locked = false;
}
}
我首先调用start_draw_sequence
,然后绘制一堆位图等,绘制完成后,我调用end_draw_sequence
。一切正常,直到调用Activity.onResume()
(将应用程序置于后台)。线程仍在onPause()
和onStop()
之后调用这些方法。
为什么我会引发此异常?
答案 0 :(得分:0)
如果绘图代码不在主线程(UI线程)中,请尝试将其移至主线程或使用Executors.newSingleThreadExecutor()
,以确保只有一个线程可以同时调用lockCanvas()
或{{1 }}-我以为是因为其他线程试图在另一个已经锁定画布的线程锁定画布的情况下发生问题,所以如果再次调用unlockCanvasAndPost()
而不解锁先前锁定的画布-返回null