I'm creating a music player app.
In that I am checking if my application loses AudioFocus then the playback will stop.
But this is raising one issue that when I play a track - then stop it and - then play a track again, switch case AudioManager.AUDIOFOCUS_LOSS
is getting called in which I've stopped the player as it is losing focus.
So my own app is losing focus to itself. Obviously, these were not my intentions. I wanted it to get called when some other music player requested focus.
private OnAudioFocusChangeListener focusChangeListener = new OnAudioFocusChangeListener() {
@Override
public void onAudioFocusChange(int focusChange) {
switch (focusChange) {
case AudioManager.AUDIOFOCUS_LOSS:
if (mPlayer.isPlaying()) {
stopPlayback();
}
break;
case AudioManager.AUDIOFOCUS_LOSS_TRANSIENT:
if (mPlayer.isPlaying()) {
mPlayer.pause();
}
break;
case AudioManager.AUDIOFOCUS_GAIN:
if (!mPlayer.isPlaying()) {
initiatePlayback();
}
break;
}
}
};
There is one more problem, Exception that I was getting is IllegalStateException
.
This means when the code reaches inside case AudioManager.AUDIOFOCUS_LOSS
, my musicplayer is in some erroneous state.
So to check that, I registered an OnErrorListener
using:
//Inside Service - onCreate() Method
mPlayer.setOnErrorListener(mErrorListener);
But this listener is never gets called. I'll appreteate any help.