有这么一种场景:你打开qq音乐、优酷客户端、视频播放的时候。这个时候突然来电显示了,此时所有的MediaPlayer相关的服务或者响应都进入“休眠”状态。那么,这个功能是怎么实现的呢?看到这篇文章的时候,原理其实很简单。只修要复制下面的d代码就能完成这个功能。
1、首先要创建一个AudioManager
//创建audioMangerAudioManager audioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE);int result = audioManager.requestAudioFocus(this, AudioManager.STREAM_MUSIC, AudioManager.AUDIOFOCUS_GAIN);例如你在服务里面的onCreate方法里面完成的上面操作的。
2、让你的服务实现OnAudioFocusChangeListener接口:
例如:
public class AudioService extends Service implements OnAudioFocusChangeListener3、实现该接口回调的方法。
/**---------------音频焦点处理相关的方法---------------**/@Overridepublic void onAudioFocusChange(int focusChange) { switch (focusChange) { case AudioManager.AUDIOFOCUS_GAIN://你已经得到了音频焦点。 System.out.println("-------------AUDIOFOCUS_GAIN---------------"); // resume playback mPlayer.start(); mPlayer.setVolume(1.0f, 1.0f); break; case AudioManager.AUDIOFOCUS_LOSS://你已经失去了音频焦点很长时间了。你必须停止所有的音频播放 System.out.println("-------------AUDIOFOCUS_LOSS---------------"); // Lost focus for an unbounded amount of time: stop playback and release media player if (mPlayer.isPlaying()) mPlayer.stop(); mPlayer.release(); mPlayer = null; break; case AudioManager.AUDIOFOCUS_LOSS_TRANSIENT://你暂时失去了音频焦点 System.out.println("-------------AUDIOFOCUS_LOSS_TRANSIENT---------------"); // Lost focus for a short time, but we have to stop // playback. We don't release the media player because playback // is likely to resume if (mPlayer.isPlaying()) mPlayer.pause(); break; case AudioManager.AUDIOFOCUS_LOSS_TRANSIENT_CAN_DUCK://你暂时失去了音频焦点,但你可以小声地继续播放音频(低音量)而不是完全扼杀音频。 System.out.println("-------------AUDIOFOCUS_LOSS_TRANSIENT_CAN_DUCK---------------"); // Lost focus for a short time, but it's ok to keep playing // at an attenuated level if (mPlayer.isPlaying()) mPlayer.setVolume(0.1f, 0.1f); break; }}简单的三步,就完成了一个强大的功能。
喜欢可以关注本博客哦~不定义更新简单有趣的Android小文