我有一个带有音频播放器和视频播放器的应用程序。我希望当音频播放器在后台播放并开始播放视频时,音频播放器自行停止。
我可以通过在打开视频时发送一个意图通过广播接收器轻松实现这一点,并在音频播放器中监听该意图并在 onReceive() 中停止它。
但是,我想将此功能不仅扩展到我的音频播放器,而且扩展到所有音频播放器。所以我想在视频播放器打开时是否有标准的发送意图?
我有一个带有音频播放器和视频播放器的应用程序。我希望当音频播放器在后台播放并开始播放视频时,音频播放器自行停止。
我可以通过在打开视频时发送一个意图通过广播接收器轻松实现这一点,并在音频播放器中监听该意图并在 onReceive() 中停止它。
但是,我想将此功能不仅扩展到我的音频播放器,而且扩展到所有音频播放器。所以我想在视频播放器打开时是否有标准的发送意图?
您应该为此使用音频焦点。Cf RandomMusicPlayer 示例 android 项目:
public class AudioFocusHelper {
AudioManager mAM;
MusicFocusable mFocusable;
private final AudioManager.OnAudioFocusChangeListener listener = new AudioManager.OnAudioFocusChangeListener() {
@Override
/**
* Called by AudioManager on audio focus changes. We implement this by calling our
* MusicFocusable appropriately to relay the message.
*/
public void onAudioFocusChange(int focusChange) {
if (mFocusable == null) return;
switch (focusChange) {
case AudioManager.AUDIOFOCUS_GAIN:
mFocusable.onGainedAudioFocus();
break;
case AudioManager.AUDIOFOCUS_LOSS:
case AudioManager.AUDIOFOCUS_LOSS_TRANSIENT:
mFocusable.onLostAudioFocus(false);
break;
case AudioManager.AUDIOFOCUS_LOSS_TRANSIENT_CAN_DUCK:
mFocusable.onLostAudioFocus(true);
break;
default:
}
}
};;
public AudioFocusHelper(Context ctx, MusicFocusable focusable) {
mAM = (AudioManager) ctx.getSystemService(Context.AUDIO_SERVICE);
mFocusable = focusable;
}
/** Requests audio focus. Returns whether request was successful or not. */
public boolean requestFocus() {
return AudioManager.AUDIOFOCUS_REQUEST_GRANTED ==
mAM.requestAudioFocus(listener, AudioManager.STREAM_MUSIC, AudioManager.AUDIOFOCUS_GAIN);
}
/** Abandons audio focus. Returns whether request was successful or not. */
public boolean abandonFocus() {
return AudioManager.AUDIOFOCUS_REQUEST_GRANTED == mAM.abandonAudioFocus(listener);
}
}