Skip to content Skip to sidebar Skip to footer

Canvas And Surfaceview Example Crash/freeze - Memory Leak?

http://www.helloandroid.com/tutorials/how-use-canvas-your-android-apps-part-1 At the end of this tutorial link for source code download is available. I downloaded the code and trie

Solution 1:

The onDraw looks like this:

@OverridepublicvoidonDraw(Canvas canvas) {

            Paintpaint=newPaint();


            Bitmapkangoo= 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:

publicclassPanelextendsSurfaceViewimplementsSurfaceHolder.Callback{
    // rest of class ignored for brevityprivate Paint paint;
    private Bitmap kangoo;

    publicPanel(Context context, AttributeSet attrs) {
    super(context, attrs); 
    getHolder().addCallback(this);
    canvasthread = newCanvasThread(getHolder(), this);
    setFocusable(true);
         paint = newPaint();


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

    @OverridepublicvoidonDraw(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.

Post a Comment for "Canvas And Surfaceview Example Crash/freeze - Memory Leak?"