Handling media buttons


#1

Hi!

I am starting to develop for android with Kotlin and I am trying to intercept the volume up / down button presses on my app, but so far I had no success.

I have tried to follow this documentation page:
https://developer.android.com/guide/topics/media-apps/mediabuttons#mediabuttons-and-active-mediasessions

I created the MediaSession, set the callback object but the OnMediaButtonEvent() is never called.

This is basically what I did:

private lateinit var mediaSession: MediaSession
private val msCallBack = object: MediaSession.Callback() {
    override fun onMediaButtonEvent(intent: Intent) : Boolean {
        Log.d("ChessApp", "Media button event")
        var keyEvent : KeyEvent = intent.getParcelableExtra(Intent.EXTRA_KEY_EVENT)
        if (keyEvent.getKeyCode() == KeyEvent.KEYCODE_VOLUME_UP) {
            Log.d("ChessApp", "Volume Up Pressed!")
            return true
        } else if (keyEvent.getKeyCode() == KeyEvent.KEYCODE_VOLUME_UP) {
            Log.d("ChessApp", "Volume Down Pressed!")
            return true
        }
        return super.onMediaButtonEvent(intent)
    }
}

Then on my onViewCreated() function I added this:

    mediaSession = MediaSession(this.context, "ChessApp")
    mediaSession.setCallback( msCallBack )
    mediaSession.isActive = true

From what the documentation suggests, this is all I should need to get it to work. What am I missing?


#2

Answering my own question, I was of course going the wrong way about it… All I needed to do is have a onKeyDown event handler on my activity. This worked for me:

override fun onKeyDown(keyCode: Int, event: KeyEvent): Boolean {
    when (keyCode) {
        KeyEvent.KEYCODE_VOLUME_UP -> {
            Log.d("ChessApp", "Key Pressed: Volume Up!!!")
            return true
        }
        KeyEvent.KEYCODE_VOLUME_DOWN -> {
            Log.d("ChessApp", "Key Pressed: Volume Down!!!")
            return true
        }
    }
    return super.onKeyDown(keyCode, event)
}