停止来自其他应用程序的音乐

Stop music of from Other APP

如果在后台默认音乐播放器是 运行 并且如果我使用我的应用程序播放音乐,两者会同时运行。

有没有办法停止背景音乐播放器。

您将必须实施 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