的一種可能的解決方案,我在此發現使用AudioManager.requestAudioFocus(...)函數
AudioManager AM =(AudioManager)getSystemService(Context.AUDIO_SERVICE);
代碼示例:
int result = am.requestAudioFocus(focusChangeListener, //Request audio focus for playback
AudioManager.STREAM_MUSIC, //Use the music stream.
AudioManager.AUDIOFOCUS_GAIN); //Request permanent focus.
if (result == AudioManager.AUDIOFOCUS_REQUEST_GRANTED) {
// other app had stopped playing song now , so u can do u stuff now .
}
音頻焦點依次分配給請求它的每個應用程序。這意味着如果另一個應用程序請求音頻焦點,您的將失去它。 通過onAudioFocusChange事件偵聽器在AudioFocus發生變化時通知應用程序。此偵聽器是requestAudioFocus函數中的第一個參數。
此偵聽器應該是這個樣子:
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 (not sure what ducking means really)
break;
case (AudioManager.AUDIOFOCUS_LOSS_TRANSIENT) :
//TODO: pause audio
break;
case (AudioManager.AUDIOFOCUS_LOSS) :
//TODO: pause audio
break;
case (AudioManager.AUDIOFOCUS_GAIN):
//TODO: Return the volume to normal and resume if paused.
break;
default: break; //empty on default
}
}
};
我認爲這個問題可以幫助你:http://stackoverflow.com/questions/24716455/android-how-to-stop-music-service-of -My-APP-IF-另一-APP-播放音樂 – 0xDEADC0DE
見https://developer.android.com/training/managing-audio/audio-focus.html – F43nd1r