![](/img/trans.png)
[英]Canvas object must be the same instance that was previously returned by lockCanvas
[英]java.lang.IllegalArgumentException: Canvas object must be the same instance that was previously returned by lockCanvas
還有一篇關於相同異常的文章,但是對該問題的答案是確保在調用this.holder.getSurface().unlockCanvasAndPost(this.canvas)
之前,我的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()
之后調用這些方法。
為什么會引發此異常?
如果繪制代碼不在主線程(UI線程)中,請嘗試將其移至主線程或使用Executors.newSingleThreadExecutor()
,以確保只有一個線程可以同時調用lockCanvas()
或unlockCanvasAndPost()
-我認為是這個問題發生這種情況是因為某個其他線程試圖在另一個已鎖定畫布的線程期間鎖定畫布,所以如果再次調用lockCanvas()
而不解鎖先前鎖定的畫布-則返回null
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.