我正在构建媒体播放器并以类似于文档的方式实施onAudioFocusChange()
:
OnAudioFocusChangeListener afChangeListener = new OnAudioFocusChangeListener() {
public void onAudioFocusChange(int focusChange) {
if (focusChange == AUDIOFOCUS_LOSS_TRANSIENT
// Pause playback
} else if (focusChange == AudioManager.AUDIOFOCUS_GAIN) {
// Resume playback
} else if (focusChange == AudioManager.AUDIOFOCUS_LOSS) {
am.unregisterMediaButtonEventReceiver(RemoteControlReceiver);
am.abandonAudioFocus(afChangeListener);
// Stop playback
}
}
};
唯一奇怪的问题:当我的手机在后台与应用程序坐在一起并且媒体播放器暂停时,该服务将随机开始播放。当我删除上面的代码时,它不会发生。因此,onAudioFocusChange()
被调用AUDIO_FOCUS_GAIN
作为参数似乎是随机的。还有其他人处理过这个问题吗?
答案 0 :(得分:3)
为了避免在你不想要的时候播放,你可以保留一个布尔值来表明你的应用应该播放:
boolean wantsMusic = true;
OnAudioFocusChangeListener afChangeListener = new OnAudioFocusChangeListener() {
public void onAudioFocusChange(int focusChange) {
if (focusChange == AUDIOFOCUS_LOSS_TRANSIENT
// Pause playback
} else if (focusChange == AudioManager.AUDIOFOCUS_GAIN && wantsMusic) {
// Resume playback
} else if (focusChange == AudioManager.AUDIOFOCUS_LOSS) {
am.unregisterMediaButtonEventReceiver(RemoteControlReceiver);
am.abandonAudioFocus(afChangeListener);
// Stop playback
}
}
};