我的應用程序有一個包含一些ImageButtons的佈局。另外,我的應用程序呈現一些位圖供以後使用。位圖通過創建帶有位圖參數的畫布,然後繪製到畫布來呈現。該位圖渲染任務發生在非UI線程中,因此gui在位圖渲染時可以保持響應。Android:在非UI線程中繪製到畫布引起的同步問題?
正在發生ANR。造成的原因似乎是ImageButton.draw()方法沒有完成。此外,看起來該方法無法完成,因爲Bitmap渲染任務在ImageButton繪製時開始渲染。
下面是一些代碼片段,日誌輸出和ANR中的traces.txt文件。
我的結論是否可能/在非UI線程中畫Canvas可能會導致ImageButton.draw()掛起?如果是這樣,任何建議來解決這個問題?
private class BitmapRenderTask implements Runnable
{
...
public void run()
{
Log.e("start render task", rect.toString());
...
Canvas canvas = new Canvas(bitmap);
Log.e("created canvas", "created canvas");
//do stuff to draw into canvas
Log.e("drew to canvas", "drew to canvas");
...
Log.e("done, exit", rect.toString());
public class MyImageButton extends ImageButton
{
public void draw(Canvas canvas)
{
Log.e("start drawing", this.toString());
super.draw(canvas);
Log.e("end drawing", this.toString());
}
}
My log:
04-24 14:10:12.115: E/start render task(9446): 1 Rect(512, 0 - 800, 512)
04-24 14:10:12.230: E/start drawing(9446): MyButton1
04-24 14:10:12.230: E/end drawing(9446): MyButton1
04-24 14:10:12.230: E/start drawing(9446): MyButton2
04-24 14:10:12.230: E/end drawing(9446): MyButton2
04-24 14:10:12.230: E/start drawing(9446): MyButton3
04-24 14:10:12.230: E/end drawing(9446): MyButton3
04-24 14:10:12.230: E/start drawing(9446): MyButton4
04-24 14:10:12.235: E/end drawing(9446): MyButton4
04-24 14:10:12.235: E/start drawing(9446): MyButton5
04-24 14:10:12.235: E/end drawing(9446): MyButton5
04-24 14:10:12.235: E/start drawing(9446): MyButton6
04-24 14:10:12.390: E/drew to canvas(9446): drew to canvas
04-24 14:10:12.395: E/done, exit(9446): Rect(512, 0 - 800, 512)
04-24 14:10:12.395: E/start render task(9446): Rect(0, 1024 - 512, 1084)
04-24 14:10:12.410: E/drew to canvas(9446): drew to canvas
04-24 14:10:12.395: E/done, exit(9446): Rect(0, 1024 - 512, 1084)
traces.txt: