1. AudioManager am = (AudioManager) mContext.getSystemService(Context.AUDIO_SERVICE); 2. 3. int result = am.requestAudioFocus(mOnAudioFocusChangeListener, 4. // Hint: the music stream. 5. AudioManager.STREAM_MUSIC, 6. // Request permanent focus. 7. AudioManager.AUDIOFOCUS_GAIN); 8. if (result == AudioManager.AUDIOFOCUS_REQUEST_GRANTED) { 9. mState.audioFocusGranted = true; 10. } else if (result == AudioManager.AUDIOFOCUS_REQUEST_FAILED) { 11. mState.audioFocusGranted = false; 12. }
1. mOnAudioFocusChangeListener = new AudioManager.OnAudioFocusChangeListener() { 2. 3. @Override 4. public void onAudioFocusChange(int focusChange) { 5. switch (focusChange) { 6. case AudioManager.AUDIOFOCUS_GAIN: 7. mState.audioFocusGranted = true; 8. 9. if(mState.released) { 10. initializeMediaPlayer(); 11. } 12. 13. switch(mState.lastKnownAudioFocusState) { 14. case UNKNOWN: 15. if(mState.state == PlayState.PLAY && !mPlayer.isPlaying()) { 16. mPlayer.start(); 17. } 18. break; 19. case AudioManager.AUDIOFOCUS_LOSS_TRANSIENT: 20. if(mState.wasPlayingWhenTransientLoss) { 21. mPlayer.start(); 22. } 23. break; 24. case AudioManager.AUDIOFOCUS_LOSS_TRANSIENT_CAN_DUCK: 25. restoreVolume(); 26. break; 27. } 28. 29. break; 30. case AudioManager.AUDIOFOCUS_LOSS: 31. mState.userInitiatedState = false; 32. mState.audioFocusGranted = false; 33. teardown(); 34. break; 35. case AudioManager.AUDIOFOCUS_LOSS_TRANSIENT: 36. mState.userInitiatedState = false; 37. mState.audioFocusGranted = false; 38. mState.wasPlayingWhenTransientLoss = mPlayer.isPlaying(); 39. mPlayer.pause(); 40. break; 41. case AudioManager.AUDIOFOCUS_LOSS_TRANSIENT_CAN_DUCK: 42. mState.userInitiatedState = false; 43. mState.audioFocusGranted = false; 44. lowerVolume(); 45. break; 46. } 47. mState.lastKnownAudioFocusState = focusChange; 48. } 49.};
AUDIOFOCUS_GAIN
AUDIOFOCUS_LOSS
AUDIOFOCUS_GAIN_TRANSIENT
AUDIOFOCUS_LOSS_TRANSIENT
AUDIOFOCUS_GAIN_TRANSIENT_MAY_DUCK
AUDIOFOCUS_LOSS_TRANSIENT_CAN_DUCK
STREAM_ALARM
STREAM_DTMF
STREAM_MUSIC
STREAM_NOTIFICATION