Created
August 5, 2013 16:27
-
-
Save kuccello/6157301 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 | |
} |
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...
thanks a lot
You r saving my times
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
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?