【问题标题】:Android notifications: open Activity and run BroadcastReceiver when tapping a button using multiple PendingIntentsAndroid 通知:使用多个 PendingIntents 点击按钮时打开 Activity 并运行 BroadcastReceiver
【发布时间】:2022-01-15 19:54:57
【问题描述】:

我想要实现的目标:我的通知有一个按钮。当用户点击它时,我想将应用程序移到前台并同时做一些后台工作。

要实现第一个,我会像这样使用PendingIntent

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

对于第二个,我声明了一个广播接收器,它在其onReceive 中执行一些后台逻辑。 PendingIntent 看起来像这样:

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

那么通常我会使用Builder 创建一个NotificationCompat.Action,例如:

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

并将其添加到NotificationCompat.Builder

但是,我无法在该操作中添加许多 PendingIntents,因为它只接受一个。所以我可以打开应用程序,也可以做后台逻辑,而不是两者兼而有之。

在 Android 10 之前没有问题,因为我们总是可以从 BroadcastReceiver 启动 Activity。但从 Android 10 开始,它是 not possible,因为来自后台的应用程序不应启动活动。他们建议使用...通知来处理它,但我只是来自通知点击!

任何想法如何处理这种情况?

【问题讨论】:

    标签: android android-notifications android-pendingintent


    【解决方案1】:

    我想把应用移到前台,同时做一些后台工作

    让活动开始后台工作。

    如果您还需要在不启动此后台工作的模式下使用此活动,请使用Intent extra、Intent 操作字符串或一些内存中的标志来说明这是一个场景您希望在哪里执行后台工作。

    【讨论】:

    • 它会改变整个应用程序用 Compose 编写的任何内容吗?我的意思是,我的 MainActivity 只是导航逻辑的宿主(NavHost 等)。
    • @adek111:“它会改变整个应用程序用 Compose 编写的任何内容吗?” -- 我没想到会这样。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-05-14
    相关资源
    最近更新 更多