VideoView内存泄漏

VideoView memory leak

你们有遇到过类似的内存泄漏吗? 这就是我目前处理 VideoView

的方式
@Override
protected void onFinishInflate() {
    super.onFinishInflate();
    ButterKnife.bind(this);

    Uri videoUri = Uri.parse(String.format("android.resource://%s/%s", getContext().getPackageName(), videoRes));
    videoView.setVideoURI(videoUri);
    videoView.setOnPreparedListener(mp -> {
        mp.setLooping(true);
        videoView.start();
    });
}

这是我在 LeakCanary 上得到的

感谢任何帮助!

将 ButterKnife 与 Fragment 一起使用时,您需要使用 onDestroyView() 中的 Unbinder 来正确取消引用 Fragment 的视图——因为 Fragment 的生命周期与 Activity 不同。

有一个相关问题 here

如果您使用的是 Butterknife,请确保解除绑定,如果您不使用,请确保在您的 onDestroy

中调用 videoView.stopPlayback()

这在不使用 Butterknife

AppCompatActivity 中为我修复了它

第 1 步:创建实用程序 class

public class AudioServiceContext extends ContextWrapper {

    public AudioServiceContext(Context base) {
        super(base);
    }

    public static ContextWrapper getContext(Context base) {
        return new AudioServiceContext(base);
    }

    @Override
    public Object getSystemService(String name) {
        if (Context.AUDIO_SERVICE.equals(name)) {
            return getApplicationContext().getSystemService(name);
        }
        return super.getSystemService(name);
    }
}

第 2 步:在您的 Activity 中,使用此实用程序 class

public class YourVideoActivity extends AppCompatActivity {

    private VideoView videoView;

    @Override
    protected void attachBaseContext(Context newBase) {
        super.attachBaseContext(AudioServiceContext.getContext(newBase));
    }

    //etc...
}

来源:https://medium.com/@chauyan/confirmed-videoview-leak-on-android-ac502856a6cf

onPause()onDestory()中调用videoView.suspend()