Skip to content

Instantly share code, notes, and snippets.

@thedumbtechguy
Last active August 29, 2015 14:05
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save thedumbtechguy/23c9c88592723e8b2811 to your computer and use it in GitHub Desktop.
Save thedumbtechguy/23c9c88592723e8b2811 to your computer and use it in GitHub Desktop.
Handling focus in Android media player
@Override
public void onPrepared(MediaPlayer mediaPlayer) {
mIsPrepared = true;
isLoadingNew = false;
mLostFocus = false;
if (startFocus() == AudioManager.AUDIOFOCUS_REQUEST_GRANTED) {
initForeground();
mMediaPlayer.start();
mDuration = mMediaPlayer.getDuration();
checkProgress();
if(mLastSongUID != null) {
Bundle data = new Bundle();
data.putString(Constant.UID, mLastSongUID);
PlayerService.this.sendMessage(MSG_EVENT_MEDIA_PLAY_START, -1, -1, data);
}
}
else {
mLostFocus = true;
}
}
int startFocus() {
AudioManager audioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
return audioManager.requestAudioFocus(this, AudioManager.STREAM_MUSIC,
AudioManager.AUDIOFOCUS_GAIN);
}
void endFocus() {
AudioManager audioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
audioManager.abandonAudioFocus(this);
}
@Override
public void onAudioFocusChange(int focusChange) {
switch (focusChange) {
case AudioManager.AUDIOFOCUS_GAIN:
// resume playback
if (mMediaPlayer == null) initPlayer();
else if (mLostFocus) {
mLostFocus = mIsPaused = false;
mMediaPlayer.start();
checkProgress();
if(mLastSongUID != null) {
Bundle data = new Bundle();
data.putString(Constant.UID, mLastSongUID);
PlayerService.this.sendMessage(MSG_EVENT_MEDIA_PLAY_START, -1, -1, data);
}
}
mMediaPlayer.setVolume(1.0f, 1.0f);
break;
case AudioManager.AUDIOFOCUS_LOSS:
// Lost focus for an unbounded amount of time: stop playback and release media player
if (mMediaPlayer.isPlaying()) mMediaPlayer.stop();
mMediaPlayer.release();
mMediaPlayer = null;
endForeground();
break;
case AudioManager.AUDIOFOCUS_LOSS_TRANSIENT:
// Lost focus for a short time, but we have to stop
// playback. We don't release the media player because playback
// is likely to resume
if (mMediaPlayer.isPlaying()) {
mMediaPlayer.pause();
cancelCheckProgress();
if(!mMediaPlayer.isPlaying()) {
mLostFocus= mIsPaused = true;
PlayerService.this.sendMessage(MSG_EVENT_MEDIA_PLAY_PAUSE, -1, -1, null);
}
}
break;
case AudioManager.AUDIOFOCUS_LOSS_TRANSIENT_CAN_DUCK:
// Lost focus for a short time, but it's ok to keep playing
// at an attenuated level
if (mMediaPlayer.isPlaying()) mMediaPlayer.setVolume(0.1f, 0.1f);
break;
}
}
//set mLostFocus = false; whenever a command comes to the service e.g. play, pause, next, prev, seek etc
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment