我在一些基于TextureView和MediaPlayer的Android自定义视图上工作。我想在TextureView不可见时暂停MediaPlayer。我试着在下一个方面做到这一点:
在我的自定义视图的根布局中覆盖onVisibilityChanged()
和onDetachedFromWindow()
。它工作正常,除了2个案例:
在这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);
}
}