Skip to content

Instantly share code, notes, and snippets.

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 chiemy/f895e22a7b668f5e4b13 to your computer and use it in GitHub Desktop.
Save chiemy/f895e22a7b668f5e4b13 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
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment