Canvas and surfaceView example crash/freeze - Memory Leak?

馋奶兔 提交于 2019-11-29 18:12:37

The onDraw looks like this:

    @Override
    public void onDraw(Canvas canvas) {

            Paint paint = new Paint();


            Bitmap kangoo = BitmapFactory.decodeResource(getResources(),
                            R.drawable.kangoo);
            canvas.drawColor(Color.BLACK);
            canvas.drawBitmap(kangoo, 10, 10, null);
    }

So each time it runs, it's creating a new paint and possibly (I've not used the BitmapFactory), creating a new bitmap. This seems like overkill (particularly, since the paint isn't used, although it does seem to be in part 2). I'd consider moving these bits to the constructor for the panel to see if it makes a difference, something like:

public class Panel extends SurfaceView implements SurfaceHolder.Callback{
    // rest of class ignored for brevity

    private Paint paint;
    private Bitmap kangoo;

    public Panel(Context context, AttributeSet attrs) {
    super(context, attrs); 
    getHolder().addCallback(this);
    canvasthread = new CanvasThread(getHolder(), this);
    setFocusable(true);
         paint = new Paint();


         kangoo = BitmapFactory.decodeResource(getResources(),
                            R.drawable.kangoo);
}

    @Override
    public void onDraw(Canvas canvas) {                
            canvas.drawColor(Color.BLACK);
            canvas.drawBitmap(kangoo, 10, 10, null);
    }
}

It may also be worth running it in the emulator to see if you get the same problem, or if it is device specific.

EDIT: It's also worth noting that the run() method in the CanvasThread class doesn't have any sleeps in it, so it's running as fast as it can, redrawing the screen. This is probably ok for a tutorial, but in a real app I would expect some kind of target frame rate with an appropriate sleep in the run method, otherwise it seems like you would be using an awful lot of cpu cycles (and presumably battery) that the user probably isn't going to notice.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!