packages/apps/Mms/src/com/android/mms/ui/ComposeMessageActivity.java
private void play() {
+ AudioManager am = (AudioManager)getSystemService(AUDIO_SERVICE);
+ am.requestAudioFocus(mAudioFocusChangeListener,AudioManager.STREAM_MUSIC, AudioManager.AUDIOFOCUS_GAIN);
mMediaPlayer.start();
mHandler.post(mUpdateThread);
mPlayPauseDrawable = getResources().getDrawable(R.drawable.audio_pause).mutate();
public void pause() {
+ AudioManager am = (AudioManager)getSystemService(AUDIO_SERVICE);
+ am.abandonAudioFocus(mAudioFocusChangeListener);
mMediaPlayer.pause();
mPlayPauseDrawable = getResources().getDrawable(R.drawable.audio_play).mutate();
mPlayPauseDrawable.setTint(mColor);
+ private AudioManager.OnAudioFocusChangeListener mAudioFocusChangeListener
+ = new AudioManager.OnAudioFocusChangeListener() {
+
+ @Override
+ public void onAudioFocusChange(int focusChange) {
+ if (AudioManager.AUDIOFOCUS_LOSS_TRANSIENT == focusChange) {
+ Log.d(TAG, "audio focus loss, stop player");
+ pause();
+ }
+ }
+ };
}
AudioManager.java
/**
* Used to indicate a gain of audio focus, or a request of audio focus, of unknown duration.
* @see OnAudioFocusChangeListener#onAudioFocusChange(int)
* @see #requestAudioFocus(OnAudioFocusChangeListener, int, int)
*/
public static final int AUDIOFOCUS_GAIN = 1;
/**
* Interface definition for a callback to be invoked when the audio focus of the system is
* updated.
*/
public interface OnAudioFocusChangeListener {
/**
* Called on the listener to notify it the audio focus for this listener has been changed.
* The focusChange value indicates whether the focus was gained,
* whether the focus was lost, and whether that loss is transient, or whether the new focus
* holder will hold it for an unknown amount of time.
* When losing focus, listeners can use the focus change information to decide what
* behavior to adopt when losing focus. A music player could for instance elect to lower
* the volume of its music stream (duck) for transient focus losses, and pause otherwise.
* @param focusChange the type of focus change, one of {@link AudioManager#AUDIOFOCUS_GAIN},
* {@link AudioManager#AUDIOFOCUS_LOSS}, {@link AudioManager#AUDIOFOCUS_LOSS_TRANSIENT}
* and {@link AudioManager#AUDIOFOCUS_LOSS_TRANSIENT_CAN_DUCK}.
*/
public void onAudioFocusChange(int focusChange);
}
//通话判断:
int state = TelephonyManager.getDefault().getCallState();
if (state != TelephonyManager.CALL_STATE_IDLE) {}