androidkotlinandroid-mediasession

Android MediaSessionCompat onMediaButtonEvent not working


I want to be able to detect when the pause button is pressed on my headseat (When no media is played)

I have tried all sorts of receivers and services, but nothing worked. Untill I tested this code I got after removing all the bloat from an very old example.

import android.content.ComponentName
import android.content.Intent
import android.os.Bundle
import android.support.v4.media.session.MediaSessionCompat
import androidx.appcompat.app.AppCompatActivity
import androidx.media.session.MediaButtonReceiver


class MainActivity : AppCompatActivity() {
    private lateinit var mMediaSessionCompat: MediaSessionCompat
    private val mMediaSessionCallback: MediaSessionCompat.Callback = object : MediaSessionCompat.Callback() {
        override fun onMediaButtonEvent(mediaButtonEvent: Intent): Boolean {
            println("WORKS!!!")
            return super.onMediaButtonEvent(mediaButtonEvent)
        }
    }

    private fun initMediaSession() {
        val mediaButtonReceiver = ComponentName(applicationContext, MediaButtonReceiver::class.java)
        mMediaSessionCompat = MediaSessionCompat(applicationContext, "Tag", mediaButtonReceiver, null)
        mMediaSessionCompat.setCallback(mMediaSessionCallback)
        mMediaSessionCompat.setFlags(MediaSessionCompat.FLAG_HANDLES_MEDIA_BUTTONS or MediaSessionCompat.FLAG_HANDLES_TRANSPORT_CONTROLS)
        mMediaSessionCompat.isActive = true
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        initMediaSession()
        setContentView(R.layout.activity_main)
    }

    override fun onDestroy() {
        super.onDestroy()
        mMediaSessionCompat.release()
    }
}

This code worked for some time, but did not work in other projects for some reason and after rebooting this code no longer works. I have no reason why it stopped working, but I have tried to get this working for serveral hours and I dont understand why it wont work. Can someone just give me a minimum reproducible example that works or point out what I am missing.


Solution

  • I solved this by simply playing a dummy sound

    private fun playDummySound() {
        val mMediaPlayer: MediaPlayer = MediaPlayer.create(this, R.raw.dummy_sound_500ms)
        mMediaPlayer.setOnCompletionListener { mMediaPlayer.release() }
        mMediaPlayer.start()
    }
    

    taken from https://github.com/anars/blank-audio

    Issue was solved by the solution in Android "O" (Oreo, 8) and higher media buttons issue