2

I had a separate class extends BroadcastReceiver and was able to define it in the manifest. However, I wanted to use some functions in my MPFragment class, so I put the broadcast receiver class into the Fragment class as an inner class, so that I can access the functions inside the Fragment. But now I am not sure how to define it in the manifest.xml. I tried some ways from Is it possible to define a broadcast receiver as an inner class in manifest file?, However, I will get the message from logcat: 'Couldn't find a unique registered media button receiver in the given context.' What should I do to fix this?

//manifest.xml
<receiver android:name=".MPFragment$MyReceiver"/>
class MPFragment : Fragment() {

//...other functions ...

    var broadcastReceiver = MyReceiver()
    class MyReceiver: BroadcastReceiver() {
        override fun onReceive(context: Context?, intent: Intent?) {
            context?.sendBroadcast(Intent("TRACKS_TRACKS")
                .putExtra("actionName", intent?.getAction()))

            var action = intent?.getExtras()?.getString("actionName")
            Log.i(MYLOG, "actionstr " + action + ", " + intent?.action)

            when (action) {

                CreateNotification.ACTION_PREVIOUS -> {
                    Log.i(MYLOG, "action previous clicked")
                }

                CreateNotification.ACTION_NEXT -> {
                    Log.i(MYLOG, "action next clicked")
//                    nextSong()
                }

                CreateNotification.ACTION_PLAY -> {
                    Log.i(MYLOG, "action play clicked")
                }
            }
        }

    }
}
hy c
  • 115
  • 1
  • 9

2 Answers2

0

why not define the class as a normal class not inner class, send a message (such as the action )to activity (use the rxbus,livebus,eventbus)? it's my solution

Silence
  • 126
  • 4
0

I forgot to change the Intent argument to 'MPFragment.MyReceiver::class.java' after I add the inner class. Below the code is working

manifest.xml

<receiver android:name=".MPFragment$MyReceiver"/>

CreateNotification Class

var pendingIntentPrevious: PendingIntent?
var intentPrevious = Intent(context, MPFragment.MyReceiver::class.java)
                    .setAction(ACTION_PREVIOUS)
                    .putExtra("actionName", ACTION_PREVIOUS)

...
   var notification = NotificationCompat.Builder(context, CHANNEL_ID)
                    .setSmallIcon(R.drawable.music)
                    .setContentTitle(title)    
                    .addAction(actionPrevious, "Previous", pendingIntentPrevious)
...


hy c
  • 115
  • 1
  • 9