Forked from kuccello/Example OnAudioFocusChangeListener
Last active
August 29, 2015 14:07
-
-
Save chiemy/f895e22a7b668f5e4b13 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; | |
} | |
} | |
}; |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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