I am trying to capture KEYCODE_MEDIA_PLAY_PAUSE key events from Bluetooth headphones. I tried to override onKeyDown in the MainActivity to get the keyCode, but I only got events from the phone, never from the Bluetooth headphones. I found some similar questions, but couldn't find any solution. Thanks!
override fun onKeyDown(keyCode: Int, event: KeyEvent): Boolean {
Timber.d("$keyCode")
when (keyCode) {
KeyEvent.KEYCODE_MEDIA_PLAY_PAUSE -> {
Timber.d("Received")
return true
}
}
return super.onKeyDown(keyCode, event)
}
If anyone is facing the same issue, this is what worked for me now:
fun configureMediaSession(){
s_mediaSession = MediaSession(this, "MyMediaSession")
s_mediaSession.setCallback(object : MediaSession.Callback() {
override fun onMediaButtonEvent(mediaButtonIntent: Intent): Boolean {
val ke: KeyEvent? = mediaButtonIntent.getParcelableExtra(Intent.EXTRA_KEY_EVENT)
if (ke != null && ke.action == KeyEvent.ACTION_DOWN) {
// Calling my method
return true
}
return super.onMediaButtonEvent(mediaButtonIntent)
}
})
}
It would be great if anyone can share a better solution.