adek111
adek111

Reputation: 1458

Android notifications: open Activity and run BroadcastReceiver when tapping a button using multiple PendingIntents

What I want to achieve: my notification has a button. When user taps it, I want to move the app to the foreground and do some background work simultaneously.

To achieve the first one, I would use PendingIntent like this:

val mySingleActivityAppPendingIntent = PendingIntent.getActivity(
    context,
    Random.nextInt(),
    Intent(context, MainActivity::class.java),
    PendingIntent.FLAG_IMMUTABLE
)

For the second one, I declared a broadcast receiver that in its onReceive do some background logic. And the PendingIntent looks like this:

val myBroadcastReceiverPendingIntent = PendingIntent.getBroadcast(
    context,
    Random.nextInt(),
    Intent(context, MyBroadcastReceiver::class.java),
    PendingIntent.FLAG_IMMUTABLE
)

Then normally I would create a NotificationCompat.Action using Builder, example:

val notificationButtonAction = NotificationCompat.Action.Builder(
    0,
    "Click me",
    one_of_these_two_pending_intents
).build()

and add it to NotificationCompat.Builder.

However, I'm not able to add many PendingIntents to that action as it only accepts one. So I can either open the app, or do the background logic, not both of them.

There was no problem prior to Android 10 as we could always launch an Activity from BroadcastReceiver. But starting from Android 10, it's not possible as apps from background should not start activities. They suggest handling it using... notification but I'm just coming from the notification click!

Any ideas how to deal with that situation?

Upvotes: 1

Views: 190

Answers (1)

CommonsWare
CommonsWare

Reputation: 1007584

I want to move the app to the foreground and do some background work simultaneously

Have the activity start the background work.

If you also need to use this activity in a mode where it does not start this background work, use an Intent extra, an Intent action string, or some in-memory flag to state that this is a scenario where you want the background work to be performed.

Upvotes: 2

Related Questions