视图变为不可见时暂停MediaPlayer

时间:2016-10-19 20:19:39

标签: android android-mediaplayer visibility android-custom-view

我在一些基于TextureView和MediaPlayer的Android自定义视图上工作。我想在TextureView不可见时暂停MediaPlayer。我试着在下一个方面做到这一点:

在我的自定义视图的根布局中覆盖onVisibilityChanged()onDetachedFromWindow()。它工作正常,除了2个案例:

  • 启动隐藏我的TextureView的新活动,它可以工作但延迟几秒钟,直到新的Activity完全加载
  • 通过电源按钮锁定设备

在这2个案例中,MediaPlayer继续在后台工作。 如何在视图不可见的情况下暂停MediaPlayer而不会覆盖Acitivity onResume()onPause()方法?

UPD - 代码示例

public class MyCustomView extends FrameLayout {

    private VisibilityListener visibilityListener;

    public interface VisibilityListener {
        void onVisibilityChanged(int visibility);
    }

    protected void onVisibilityChanged(View changedView, int visibility) {
        super.onVisibilityChanged(changedView, visibility);
        if (visibilityListener != null) {
            visibilityListener.onVisibilityChanged(visibility);
        }
    }

    public void setVisibilityListener(VisibilityListener visibilityListener) {
        if (visibilityListener != null) {
            this.visibilityListener = visibilityListener;
        }
    }

    protected void onDetachedFromWindow() {
        super.onDetachedFromWindow();
        if (visibilityListener != null) {
            visibilityListener.onVisibilityChanged(INVISIBLE);
        }
    }

}

以及我如何使用它:

        public void onVisibilityChanged(int visibility) {
            if (mediaPlayer == null) {
                return;
            }
            try {
                if (visibility == View.VISIBLE) {
                    mediaPlayer.start();
                } else {
                    mediaPlayer.pause();
                }
            } catch (Exception e) {
                Log.e(TAG, "mediaPlayer issue", e);
            }
        }

0 个答案:

没有答案