I am creating a music player app.
I want:
- When the user plays a song using my app, then the default music player should get stopped(is playing)
- And if some other application starts playing when my app is already playing then mine should get stopped.
I am able to work out with the 1st point using Audio Focus.
But for the 2nd point, i.e. Handling AUDIOFOCUS_LOSS
, i'm facing some issues.
Problem: I've followed the documentation but how should I register my music player service to detect that AudioFocus has been lost.
For 1st Point, here is the code:
if (reqAudioFocus()) {
mPlayer.start();
}
private boolean reqAudioFocus() {
boolean gotFocus = false;
int audioFocus = am.requestAudioFocus(null, AudioManager.STREAM_MUSIC,
AudioManager.AUDIOFOCUS_GAIN);
if (audioFocus == AudioManager.AUDIOFOCUS_REQUEST_GRANTED) {
gotFocus = true;
} else {
gotFocus = false;
}
return gotFocus;
}
For 2nd point my code so far:
//Class implements OnAudioFocusChangeListener
@Override
public void onAudioFocusChange(int focusChange) {
/*
* TODO : Call stopService/onDestroy() method. Pause the track; Change
* the Play/Pause icon; save the track postion for seekTo() method.
*/
if (focusChange == AudioManager.AUDIOFOCUS_LOSS_TRANSIENT) {
// TODO: Pause playback
if (mPlayer.isPlaying()) {
mPlayer.pause();
}
} else if (focusChange == AudioManager.AUDIOFOCUS_GAIN) {
// TODO: Resume Playback
if (!mPlayer.isPlaying()) {
mPlayer.start();
}
} else if (focusChange == AudioManager.AUDIOFOCUS_LOSS) {
// TODO: stop playback.
// am.unregisterMediaButtonEventReceiver(RemoteControlReceiver);
am.abandonAudioFocus(afChangeListener);
}
}
Now how to make my application call onAudioFocusChange()
when app loses audio focus.
Thanks