如果在后台默认音乐播放器正在运行,如果我使用我的应用播放音乐,则两者同时运行。
有没有办法阻止背景音乐播放器。
答案 0 :(得分:0)
您必须实施Mediaplayer的AudioFocus
。为此,您需要获取AudioManager
的实例。获得实例后,您可以使用requestAudioFocus
。
AudioManager am = (AudioManager)getSystemService(Context.AUDIO_SERVICE);
// Request audio focus for playback
int result = am.requestAudioFocus(focusChangeListener,
// Use the music stream.
AudioManager.STREAM_MUSIC,
// Request permanent focus.
AudioManager.AUDIOFOCUS_GAIN);
if (result == AudioManager.AUDIOFOCUS_REQUEST_GRANTED) {
Log.d("AudioFocus", "Audio focus received");
return true;
} else {
Log.d("AudioFocus", "Audio focus NOT received");
return false;
}
}
AudioFocus
被分配给请求它的每个应用程序。当您的应用获得焦点时,它可以传递AudioManager.OnAudioFocusChangeListener
,这会在焦点发生变化时提供回调。
如果应用获得音频焦点,而另一个应用请求音频焦点,则焦点将提供给其他应用。 Android会通过OnAudioFocusChangeListener
通知您的应用,以便您的应用可以响应更改。要接收焦点事件,您需要像这样传递AudioManager.OnAudioFocusChangeListener
的实例。
private OnAudioFocusChangeListener focusChangeListener =
new OnAudioFocusChangeListener() {
public void onAudioFocusChange(int focusChange) {
AudioManager am =(AudioManager)getSystemService(Context.AUDIO_SERVICE);
switch (focusChange) {
case (AudioManager.AUDIOFOCUS_LOSS_TRANSIENT_CAN_DUCK) :
// Lower the volume while ducking.
mediaPlayer.setVolume(0.2f, 0.2f);
break;
case (AudioManager.AUDIOFOCUS_LOSS_TRANSIENT) :
pause();
break;
case (AudioManager.AUDIOFOCUS_LOSS) :
stop();
ComponentName component =new ComponentName(AudioPlayerActivity.this,MediaControlReceiver.class);
am.unregisterMediaButtonEventReceiver(component);
break;
case (AudioManager.AUDIOFOCUS_GAIN) :
// Return the volume to normal and resume if paused.
mediaPlayer.setVolume(1f, 1f);
mediaPlayer.start();
break;
default: break;
}
}
};
参考文档:https://developer.android.com/guide/topics/media-apps/volume-and-earphones.html