如何修复SurfaceView中的内存泄漏

时间:2013-08-22 01:27:21

标签: android memory-leaks surfaceview

我在surfaceview中遇到了内存泄漏问题。

我定义了一个从surfaceview扩展的自定义视图MyView。

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

和onCreate()中的setContentView; 完成活动后。 我得到下面的日志; 它显示Surface视图中存在内存泄漏。

我希望有人可以帮我解决这个问题。谢谢!

使用Android 4.2。

记录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)

记录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 个答案:

答案 0 :(得分:3)

我找到了解决此问题的方法。 你应该简单地打电话:

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

来自活动onDestroy()

的控件

这样的事情:

class MyView {

    ...

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

    ...
}

class MyActivity extends Activity {

    ...

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

    ...

}