简体   繁体   English

Android位图/字节数组内存泄漏

[英]Android bitmap/ byte array memory leak

I am having problems with a memory leak in my android app. 我的android应用存在内存泄漏问题。 Based on my hprof analysis it appears to be caused by a byte array that comes from a Bitmap in a SurfaceView class. 根据我的hprof分析,它似乎是由SurfaceView类中的Bitmap产生的byte数组引起的。

Here is the MAT analysis of one of several arrays: 这是几个数组之一的MAT分析:

MAT分析

and the code of the offending class: 以及令人反感的类的代码:

public class AndroidFastRenderView extends SurfaceView implements Runnable {

    AndroidGame game;
    Bitmap framebuffer;
    Thread renderThread = null;
    SurfaceHolder holder;
    volatile boolean running = false;

    public AndroidFastRenderView(AndroidGame game, Bitmap framebuffer) {
        super(game);
        this.game = game;
        this.framebuffer = framebuffer;
        this.holder = getHolder();
        this.holder.setFormat(PixelFormat.RGBA_8888);
        setSystemUiVisibility(
                SYSTEM_UI_FLAG_IMMERSIVE_STICKY | SYSTEM_UI_FLAG_FULLSCREEN | SYSTEM_UI_FLAG_HIDE_NAVIGATION);

    }

    public void resume() {
        setSystemUiVisibility(
                SYSTEM_UI_FLAG_IMMERSIVE_STICKY | SYSTEM_UI_FLAG_FULLSCREEN | SYSTEM_UI_FLAG_HIDE_NAVIGATION);
        running = true;
        renderThread = new Thread(this);
        renderThread.start();

    }

    public void run() {
        Rect dstRect = new Rect();
        long startTime = System.nanoTime();
        while (running) {
            if (!holder.getSurface().isValid())
                continue;
            float deltaTime = (System.nanoTime() - startTime) / 10000000.000f;
            startTime = System.nanoTime();
            game.getCurrentScreen().update(deltaTime);
            game.getCurrentScreen().paint(deltaTime);
            Canvas canvas = holder.lockCanvas();
            canvas.getClipBounds(dstRect);
            canvas.drawBitmap(framebuffer, null, dstRect, null);
            holder.unlockCanvasAndPost(canvas);

        }
    }

    public void pause() {
        running = false;
        while (true) {
            try {
                renderThread.join();
                break;
            } catch (InterruptedException e) {
            }
        }
    }

    public void release() {
        getHolder().getSurface().release();
        framebuffer.recycle();
    }
}

release() is called in my Activity's onDestroy() . release()在我的Activity的onDestroy()调用。

frameBuffer is created with the line: 使用以下行创建frameBuffer

Bitmap frameBuffer = Bitmap.createBitmap(frameBufferWidth, frameBufferHeight, ARGB_8888);

in my Activity. 在我的活动中。

Make sure your Thread "renderThread" is stopped. 确保您的线程“ renderThread”已停止。 If it is still active, it holds a reference to the "AndroidFastRenderView" object so it can't free the memory... 如果它仍然处于活动状态,它将保存对“ AndroidFastRenderView”对象的引用,因此无法释放内存...

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM