Skip to content

Instantly share code, notes, and snippets.

@kuccello
Created August 5, 2013 16:27
Show Gist options
  • Save kuccello/6157301 to your computer and use it in GitHub Desktop.
Save kuccello/6157301 to your computer and use it in GitHub Desktop.
private AudioManager.OnAudioFocusChangeListener mOnAudioFocusChangeListener;
//…
mOnAudioFocusChangeListener = new AudioManager.OnAudioFocusChangeListener() {
@Override
public void onAudioFocusChange(int focusChange) {
switch (focusChange) {
case AudioManager.AUDIOFOCUS_GAIN:
Log.i(TAG, "AUDIOFOCUS_GAIN");
// Set volume level to desired levels
play();
break;
case AudioManager.AUDIOFOCUS_GAIN_TRANSIENT:
Log.i(TAG, "AUDIOFOCUS_GAIN_TRANSIENT");
// You have audio focus for a short time
play();
break;
case AudioManager.AUDIOFOCUS_GAIN_TRANSIENT_MAY_DUCK:
Log.i(TAG, "AUDIOFOCUS_GAIN_TRANSIENT_MAY_DUCK");
// Play over existing audio
play();
break;
case AudioManager.AUDIOFOCUS_LOSS:
Log.e(TAG, "AUDIOFOCUS_LOSS");
stop();
break;
case AudioManager.AUDIOFOCUS_LOSS_TRANSIENT:
Log.e(TAG, "AUDIOFOCUS_LOSS_TRANSIENT");
// Temporary loss of audio focus - expect to get it back - you can keep your resources around
pause();
break;
case AudioManager.AUDIOFOCUS_LOSS_TRANSIENT_CAN_DUCK:
Log.e(TAG, "AUDIOFOCUS_LOSS_TRANSIENT_CAN_DUCK");
// Lower the volume
break;
}
}
};
AudioManager am = (AudioManager) mContext
.getSystemService(Context.AUDIO_SERVICE);
// Request audio focus for play back
int result = am.requestAudioFocus(mOnAudioFocusChangeListener,
// Use the music stream.
AudioManager.STREAM_MUSIC,
// Request permanent focus.
AudioManager.AUDIOFOCUS_GAIN);
if (result == AudioManager.AUDIOFOCUS_REQUEST_GRANTED) {
mAudioFocusGranted = true;
} else if (result == AudioManager.AUDIOFOCUS_REQUEST_FAILED) {
// take appropriate action
}
@randauto
Copy link

randauto commented Feb 2, 2015

Thank you very much, but I have a question hope you can help me.
How do I control headphone button for play, pause or next, prev music?

@davidburgos
Copy link

I know that it's too late, but somebody else could need the hint, you should use MediaSessionCompat in order to control your player from headphone buttons, Google Assistant etc...

@mohammadBabul
Copy link

thanks a lot
You r saving my times

@Arsonist-Cook
Copy link

Arsonist-Cook commented Mar 4, 2021

Thank you more than very much!
This code snipet saved my day on studying how to manipulate audio focus! 'Cause there were tons os codes where I couldn't ser how to conect my listener in...
I really appreciated!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment