Search code examples
androidkotlinandroid-intentbroadcastreceiverandroid-pendingintent

Arguments for a BroadcastReceiver used inside Intent.createChooser()


I have many share buttons on my App. When a share button is pressed, a chooser is showed to the user so he can select an app to share the content. I wanted to know what the user chose so I decided to use a BroadcastReceiver with the Intent.createChooser() method.

But I have multiple share buttons across the app, so I defined the following class:

class MyBroadcastReceiver(val listener: MyBroadcastReceiverListener) : BroadcastReceiver() {
    override fun onReceive(context: Context, intent: Intent) {
        listener.handleShare()
    }

    interface MyBroadcastReceiverListener {
        fun handleShare()
    }
}

I want to use this class from different places that implement MyBroadcastReceiverListener (Activity1, Activity2, Activity3, etc.) so I can perform the corresponding task on override fun handleShare() at each place. The problem I'm facing is that I have to do this before using the Intent.createChooser().

var receiver = Intent(this, MyBroadcastReceiver::class.java) // how can I pass args 🧐 ?
var pi = PendingIntent.getBroadcast(this, 0, receiver, PendingIntent.FLAG_UPDATE_CURRENT)
Intent.createChooser(..., ..., pi.getIntentSender());

Because I have to provide MyBroadcastReceiver in a static manner, I can't pass arguments (listener in this case) to MyBroadcastReceiver. Is there a way to address this problem? Thanks for your support! 😊


Solution

  • Story: To run a block of code after users choose an app from the app chooser dialog. You shouldn't pass your activity as a listener because this can leak the activity (the application might keep a reference to the activity even it got destroyed).

    Solution: Using EventBus to achieve your goal.

    Step 1: Add EventBus to your project via gradle

    implementation 'org.greenrobot:eventbus:3.2.0'
    

    Step 2: Defines events

    object OnShareEvent
    

    Step 3: Register/unregister listening event from your activity, such as Activity1.

    override fun onStart() {
        super.onStart()
        EventBus.getDefault().register(this)
    }
    
    override fun onStop() {
        super.onStop()
        EventBus.getDefault().unregister(this)
    }
    
    @Subscribe(threadMode = ThreadMode.MAIN)
    fun handleShare(event: OnShareEvent) {
        // TODO: Your code logic goes here
    }
    

    Step 4: Post events

    class MyBroadcastReceiver : BroadcastReceiver() {
    
        override fun onReceive(context: Context, intent: Intent) {
            EventBus.getDefault().post(OnShareEvent)
        }
    }