How to fix memory leak in SurfaceView

2019-04-15 12:58发布

I met a memory leak issue in surfaceview.

I define a custom view MyView which extends from surfaceview.

int Layout file 
<com.andoird.example.MyView
....
....
/>

and setContentView in onCreate(); after finish the Activity. I get the log below; It show the there are memory leak in Surface view.

I hope someone can help me to resolve this. Thank you!

use Android 4.2.

Log 1:

08-16 16:29:23.751 E/StrictMode(23220): A resource was acquired at attached stack trace but never released. See java.io.Closeable for information on avoiding resource leaks.
08-16 16:29:23.751 E/StrictMode(23220): java.lang.Throwable: Explicit termination method 'release' not called
08-16 16:29:23.751 E/StrictMode(23220):     at dalvik.system.CloseGuard.open(CloseGuard.java:184)
08-16 16:29:23.751 E/StrictMode(23220):     at android.view.Surface.<init>(Surface.java:293)
08-16 16:29:23.751 E/StrictMode(23220):     at android.view.SurfaceView.<init>(SurfaceView.java:101)

Log 2

08-16 16:29:23.751 E/StrictMode(23220): A resource was acquired at attached stack trace but never released. See java.io.Closeable for information on avoiding resource leaks.
08-16 16:29:23.751 E/StrictMode(23220): java.lang.Throwable: Explicit termination method 'release' not called
08-16 16:29:23.751 E/StrictMode(23220):     at dalvik.system.CloseGuard.open(CloseGuard.java:184)
08-16 16:29:23.751 E/StrictMode(23220):     at android.view.Surface.<init>(Surface.java:293)
08-16 16:29:23.751 E/StrictMode(23220):     at android.view.SurfaceView.<init>(SurfaceView.java:102)

1条回答
成全新的幸福
2楼-- · 2019-04-15 13:21

I found the workaround for this issue. You should simple call:

getHolder().getSurface().release();

in your control from Activity's onDestroy()

Something like this:

class MyView {

    ...

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

    ...
}

class MyActivity extends Activity {

    ...

    @Override
    public void onDestroy() {
         super.onDestroy();
         mMyView.release();
    }

    ...

}
查看更多
登录 后发表回答