Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to fix 'media button receiver could not be found' exception

I'm building media player, and want to handle action from notification like "play", "pause". In my activity I registerd MediaButtonReceiver

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

and created media notification with

val builder: NotificationCompat.Builder = MediaStyleHelper.from(this, mediaSession!!)
builder.addAction(
                NotificationCompat.Action(
                        android.R.drawable.ic_media_previous,
                        "Previous",
                        MediaButtonReceiver.buildMediaButtonPendingIntent(this, PlaybackStateCompat.ACTION_SKIP_TO_PREVIOUS)
                )
        )

but when I press action buttons on my media notification, nothing happens. And when I add these actions, executing

MediaButtonReceiver.buildMediaButtonPendingIntent(this, PlaybackStateCompat.ACTION_SKIP_TO_PREVIOUS)

prints to console a warning

"W/MediaButtonReceiver: A unique media button receiver could not be found in the given context, so couldn't build a pending intent."

But why is it not registered if I have registered it programmatically?

like image 221
Simon Avatar asked Dec 08 '22 13:12

Simon


1 Answers

Before you can use MediaButtonReceiver functions, you need to add it to the manifest as described in the docs:

<receiver android:name="androidx.media.session.MediaButtonReceiver" >
  <intent-filter>
    <action android:name="android.intent.action.MEDIA_BUTTON" />
  </intent-filter>
</receiver>

If you aren't using the AndroidX libraries yet, you need to use the old class name: android.support.v4.media.session.MediaButtonReceiver

like image 181
TheTurboTurnip Avatar answered Dec 11 '22 11:12

TheTurboTurnip