MEDIA BUTTON是干什么的? 在手机,有线耳机或无线蓝牙耳机上有Media playback button ,比如play, pause,stop, next等,Android 系统在收到这些按键后,会广播android.intent.action.MEDIA_BUTTON 这个Intent,里面就包含了各种键(play, pause,stop 等)。 还有一种情况是Screen lock上的远程播放控制界面(Music widget),在点击play, pause, next Button时,Android系统也会广播此Intent. 相应的App在收到此广播后,可以做出对应的反应。
如何对media button 作出反应?
- 注册
<receiver android:name=".RemoteControlReceiver"> <intent-filter> <action android:name="android.intent.action.MEDIA_BUTTON" /> </intent-filter> </receiver>
指南:Android里是多任务的环境,会有多个App要求去监听MEDIA_BUTTON intent,而且该注册是排他性的, 这意味着最后一个注册MEDIA_BUTTON intent receiver的app才会收到此广播。 App必须编程来控制什么时候开始需要接收此广播。 一般是开始播放Music后,需要注册监听,而在停止播放后取消监听。 最好的办法是在获取AudioFocus后注册此监听, 而在失去AudioFocus时取消此监听!!! 如果别的App还在播放Music,你的app又没有获得AudioFocus的情况下去注册此监听,这属于捣乱行为,Android framework (AudioService)并不会来阻止你这样做,但这会影响到用户体验。
代码注册以及取消监听方式: AudioManager am = mContext.getSystemService(Context.AUDIO_SERVICE); ...
// Start listening for button presses am.registerMediaButtonEventReceiver(RemoteControlReceiver); ...
// Stop listening for button presses am.unregisterMediaButtonEventReceiver(RemoteControlReceiver);
- 具体处理代码 public class RemoteControlReceiver extends BroadcastReceiver { @Override public void onReceive(Context context, Intent intent) { if (Intent.ACTION_MEDIA_BUTTON.equals(intent.getAction())) { KeyEvent event = (KeyEvent)intent.getParcelableExtra(Intent.EXTRA_KEY_EVENT); if (KeyEvent.KEYCODE_MEDIA_PLAY == event.getKeyCode()) { // Handle key press. //具体处理 } } } } 注意在收到ACTION_MEDIA_BUTTON这个Intent时,必须从EXTRA_KEY_EVENT解出key code检查到底是按了什么键,比如KEYCODE_MEDIA_PLAY_PAUSE, KEYCODE_MEDIA_NEXT等
参考自: http://developer.android.com/training/managing-audio/volume-playback.html