TRX
TRX

Reputation: 747

How to send Intent.ACTION_SEND inside BroadcastReceiver's onReceive?

I want to add an action to my notification, when the user clicks the button, it shares the text of the notification with other apps, here is my code:

class NotificationReceiver : BroadcastReceiver() {
    override fun onReceive(context: Context?, intent: Intent?) {
        val message = intent?.getStringExtra("sharedMessage")
        val shareIntent: Intent = Intent(Intent.ACTION_SEND).apply {
            putExtra(Intent.EXTRA_TEXT, message)
            type = "text/plain"
        }
        shareIntent.flags = Intent.FLAG_ACTIVITY_NEW_TASK
        if (context != null) {
            if (shareIntent.resolveActivity(context.packageManager) != null) {
                context.startActivity(shareIntent)
            }
        }
    }
}

The onReceive function can receive the click action, but it does not start my shareIntent which should prompt the user to choose an app for sharing. What is the issue?

Upvotes: 0

Views: 220

Answers (1)

David Wasser
David Wasser

Reputation: 95578

There are restrictions on background processes (Service and BroadcastReceiver) launching activities. See https://developer.android.com/guide/components/activities/background-starts

This is probably why you aren't seeing the Activity launch.

However, why are you doing this in such a roundabout way? If you want an Activity launched when the user clicks on the notification, just do that directly instead of having the notification click start a BroadcastReceiver.

Upvotes: 1

Related Questions