Ehsan Nokandi
Ehsan Nokandi

Reputation: 1973

Error: Unable to instantiate receiver... has no zero argument constructor

I have a problem with my BroadcastReceiver class that it is inside my MainActivity as a inner class. Every time that I click on a button in my app's notification, I get this error:

java.lang.RuntimeException: Unable to instantiate receiver com.oniktech.testmediaservice.MainActivity$MediaReceiver: java.lang.InstantiationException: java.lang.Class<com.oniktech.testmediaservice.MainActivity$MediaReceiver> has no zero argument constructor

here is my code:

val playPauseAction = NotificationCompat.Action(
            icon, play_pause,
            MediaButtonReceiver.buildMediaButtonPendingIntent(
                this,
                PlaybackStateCompat.ACTION_PLAY_PAUSE
            )
        )

    builder.setContentTitle("my test")
                .addAction(playPauseAction)
                .setStyle(
                    androidx.media.app.NotificationCompat.MediaStyle()
                        .setMediaSession(mediaSession.getSessionToken())
                        .setShowActionsInCompactView(0)
                )

            notificatioManager = getSystemService(NOTIFICATION_SERVICE) as NotificationManager
            notificatioManager.notify(0, builder.build())

and here is my inner class:

inner class MediaReceiver : BroadcastReceiver() {
        override fun onReceive(context: Context, intent: Intent) {
            MediaButtonReceiver.handleIntent(mediaSession, intent)
        }
    }

I know that I should not use inner class in this case. But I have to use my 'mediaSession' object in it. What should I do? thanks for your help.

Upvotes: 0

Views: 3447

Answers (1)

Md. Asaduzzaman
Md. Asaduzzaman

Reputation: 15423

Problem - 1: Your MediaReceiver should be Nested only not inner. In Kotlin Nested class is static by default. So remove inner keyword.

class MediaReceiver : BroadcastReceiver() {
}

Problem - 2: You want to access outer class property from BroadcastReceiver which is not good practice. You should avoid it. But if you still want to do so you should make that property static and use it inside Receiver. Check my below sample implementation.

class MainActivity {
    companion object {
        var mediaSession: MediaSessionCompat? = null
    }

    class MediaReceiver : BroadcastReceiver() {
        override fun onReceive(context: Context, intent: Intent) {
            MediaButtonReceiver.handleIntent(mediaSession, intent)
        }
    }
}

Upvotes: 2

Related Questions