RatherBeSailing
RatherBeSailing

Reputation: 311

Android API 31 media button detection using MediaSession .setCallback .setMediaButtonBroadcastReceiver and BroadcastReceiver

Android API 31 supports at least three different methods claiming to handle media buttons. Despite multiple attempts I have not managed to get any of them to detect a button press on a connected audio headset

Can anyone suggest how to receive button presses on a connected audio headset in Android API 31+?

The API 31+ restriction arises because I am using mediaRecorder to record the audio stream from the headset

The latest three methods I have attempted to use are described below

MediaSession.setCallback is described as "Set the callback to receive updates for the MediaSession. This includes media button events and transport controls."

mediaSession = MediaSession(this, packageName)
mediaSession.setCallback(object : MediaSession.Callback() {
    override fun onMediaButtonEvent(mediaButtonIntent: Intent): Boolean {
        Log.d(TAG, "mediaSession.callback ${mediaButtonIntent.action}")
        return super.onMediaButtonEvent(mediaButtonIntent)
    }
})

MediaSession.setMediaButtonBroadcastReceiver is described as "Set the component name of the manifest-declared android.content.BroadcastReceiver class that should receive media buttons"

val componentName = ComponentName(this, "HeadsetMediaButtonReceiver()")
mediaSession.setMediaButtonBroadcastReceiver(componentName)

With the associated MediaButtonReceiver:

class HeadsetMediaButtonReceiver : MediaButtonReceiver() {
    override fun onReceive(context: Context?, intent: Intent?) {
        Log.d(TAG, "HeadsetMediaButtonReceiver() - ${intent?.action}")
    }
}

and the receiver field in the Manifest

<receiver android:name=".MainActivity$HeadsetMediaButtonReceiver" android:exported="false">
    <intent-filter>
        <action android:name="android.intent.action.MEDIA_BUTTON" />
    </intent-filter>
</receiver>

The generic BroadcastReceiver

registerReceiver(HeadsetMediaButtonBroadcastReceiver(), IntentFilter(Intent.ACTION_MEDIA_BUTTON))

To test the above three methods I connect to a Bluetooth headset and use mediaRecorder to record the audio. During the recording I press the headset call button but nothing is logged

The generic BroadcastReceiver is fired using sendBroadcast(), but the two MediaSession button handlers do nothing (even if I only enable one)

findViewById(R.id.send_event_button).setOnClickListener {
    sendBroadcast(Intent("android.intent.action.MEDIA_BUTTON")) 
}

Upvotes: 1

Views: 626

Answers (0)

Related Questions