Reputation: 3761
I am creating a music player app.
I want:
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
Upvotes: 1
Views: 720
Reputation: 4203
The first argument to requestAudioFocus
is an OnAudioFocusChangeListener
instance. You're passing null
at the moment. Assuming you've implemented reqAudioFocus
and onAudioFocusChanged
on the same class, passing this
instead of null
should be enough.
Upvotes: 1