Android : How To Stop Music Service Of My App, If Another App Plays Music.?
Solution 1:
This is how I solved the issue.
Implement OnAudioFocusChangeListener listener
Initialise AudioManager
like
privateAudioManagermAudioManager= (AudioManager) context.getSystemService(Context.AUDIO_SERVICE);
Request Audio focus
mAudioManager.requestAudioFocus(this, AudioManager.STREAM_MUSIC,
AudioManager.AUDIOFOCUS_GAIN);
@Overide the following method of OnAudioFocusChangeListener
publicvoidonAudioFocusChange(int focusChange){
switch (focusChange)
{
case AudioManager.AUDIOFOCUS_GAIN:
case AudioManager.AUDIOFOCUS_LOSS_TRANSIENT_CAN_DUCK:
resumePlayer(); // Resume your media player herebreak;
case AudioManager.AUDIOFOCUS_LOSS:
case AudioManager.AUDIOFOCUS_LOSS_TRANSIENT:
pausePlayer();// Pause your media player here break;
}
}
Solution 2:
This concept is called audio focus in Android.
In broad terms, it means that only one app can have audio focus at one point in time, and that you should relinquish if it asked to (for example if a phone call arrives, or another app wants to play music, &c).
To do this, you need to register an OnAudioFocusChangeListener
.
Basically, you must:
- Request audio focus before starting playback.
- Only start playback if you effectively obtain it.
- Abandon focus when you stop playback.
- Handle audio focus loss, either by lowering volume temporarily ("ducking") or stopping playback altogether.
Please check the Managing Audio Focus article in the Android documentation.
Solution 3:
privatebooleanreqAudioFocus() {
booleangotFocus=false;
intaudioFocus= am.requestAudioFocus(this, AudioManager.STREAM_MUSIC,
AudioManager.AUDIOFOCUS_GAIN);
if (audioFocus == AudioManager.AUDIOFOCUS_REQUEST_GRANTED) {
gotFocus = true;
} else {
gotFocus = false;
}
return gotFocus;
}
This will request for audio focus when you start your application and other music app is already running .So this will stop the already running app and start yours.
if (reqAudioFocus()) {
mPlayer.prepareAsync();
}
paste this where you want to prepare your mediaplayer.
For the other way round that is your app should stop when other app is played
use
publicvoidonAudioFocusChange(int focusChange){
if (focusChange == AudioManager.AUDIOFOCUS_LOSS) {
am.abandonAudioFocus(this);
mPlayer.stop();
}
}
where "am" is your AudioManager Instance.
Dont forget to implement AudioManager.OnAudioFocusChangeListener
Post a Comment for "Android : How To Stop Music Service Of My App, If Another App Plays Music.?"