【问题标题】:VideoView memory leakVideoView 内存泄漏
【发布时间】:2017-04-07 14:18:18
【问题描述】:

你们中有人遇到过类似的内存泄漏吗? 这就是我目前处理 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.bind 返回 Unbinder 。保持会员身份,可以Unbinder.unbindonDetacheFromWindow检查你是否有同样的泄漏
  • 我既没有使用 Butterknife 也没有使用片段 - 另外,在 onCompletion(MediaPlayer mp) 回调中,有一个 mVideoView.stopPlayback()

标签: android memory-leaks android-videoview


【解决方案1】:

这为我在不使用 Butterknife 的 AppCompatActivity 中修复了它

第 1 步:创建实用程序类

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 中,使用此实用程序类

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

【讨论】:

【解决方案2】:

将 ButterKnife 与 Fragments 一起使用时,您需要使用 onDestroyView() 中的 Unbinder 来正确取消引用 Fragment 的 View——因为 Fragment 与活动具有不同的生命周期。

有一个相关问题here

【讨论】:

    【解决方案3】:

    onPause()onDestory() 中致电videoView.suspend()

    【讨论】:

    • 欢迎来到 Stack Overflow!感谢您提供此代码 sn-p,它可能会提供一些有限的即时帮助。 proper explanation would greatly improve its long-term value 通过展示为什么这是一个很好的解决问题的方法,并将使其对未来有其他类似问题的读者更有用。请edit您的回答添加一些解释,包括您所做的假设。
    【解决方案4】:

    如果您使用 Butterknife,请确保取消绑定,如果您不确定在 onDestroy 中调用 videoView.stopPlayback()

    【讨论】:

    • 调用stopPlayback() 似乎不够好。即使这样,我也会遇到同样的内存泄漏。
    猜你喜欢
    • 1970-01-01
    • 2017-10-24
    • 1970-01-01
    • 1970-01-01
    • 2011-10-08
    • 2013-01-20
    • 2011-10-31
    • 2019-08-10
    • 2013-06-24
    相关资源
    最近更新 更多