Android:媒体按键消息

具体的使用方法:

  •   用 AudioManager 对象注册一个 MediaoButtonRecevie,让它成为 MEDIA_BUTTON。
  audioManager = context.getSystemService(Context.AUDIO_SERVICE) as AudioManager
  audioManager!!.registerMediaButtonEventReceiver(ComponentName(context,MusicIntentReceiver::class.java!!))
  • 广播必须在 AndroidManifest.xml 文件中进行声明,否则就监听不到该 MEDIA_BUTTON 广播了。
       
            
                
            
        
  • 创建 MusicIntentReceiver 类

    class MusicIntentReceiver : BroadcastReceiver() {
        override fun onReceive(context: Context, intent: Intent) {
            LogManager.info("onReceive" + intent.action)
            if (intent.action == android.media.AudioManager.ACTION_AUDIO_BECOMING_NOISY) {
            } else if (intent.action == Intent.ACTION_MEDIA_BUTTON) {
                val keyEvent = intent.extras!!.get(Intent.EXTRA_KEY_EVENT) as KeyEvent
                LogManager.info("action:" + intent.action + "    keycode:" + keyEvent.keyCode)
                when (keyEvent.keyCode) {
                    KeyEvent.KEYCODE_MEDIA_PLAY_PAUSE -> {
                    
                    }
                    KeyEvent.KEYCODE_MEDIA_PLAY -> {

                    }
                    KeyEvent.KEYCODE_MEDIA_PAUSE -> {
                      
                    }

                    KeyEvent.KEYCODE_MEDIA_STOP -> {
                     
                    }
                    KeyEvent.KEYCODE_MEDIA_NEXT -> {
                  
                    }
                    KeyEvent.KEYCODE_MEDIA_PREVIOUS -> {
                 
                    }
                }
            }
    }

 

你可能感兴趣的:(Android)