【问题标题】:Notification.addAction Not working when the app is backgrounded or closedNotification.addAction 在应用程序后台或关闭时不起作用
【发布时间】:2020-10-06 18:57:51
【问题描述】:

我正在使用 FCM 显示推送通知,但是当应用程序在后台运行或关闭时,通知不显示操作。

我收到消息后收到消息并使用NotificationCompat.Builder 构建通知

    val notification: Notification =
      NotificationCompat.Builder(this, getString(R.string.default_notification_channel_id))
        .setContentTitle(message.notification?.title ?: "Title")
        .setContentText(message.notification?.body ?: "Body")
        .setStyle(
          NotificationCompat.BigTextStyle()
            .bigText(message.notification?.body ?: "Grant access?")
        )
        .addAction(getApproveAction(message.data["pushId"] ?: ""))
        .addAction(getRejectAction(message.data["pushId"] ?: ""))
        .setSmallIcon(R.drawable.logo)
        .build()
    val manager = NotificationManagerCompat.from(applicationContext)
    manager.notify(NOTIFICATION_ID, notification)

动作方法看起来非常相似,唯一的区别是动作和ACCEPTED 布尔值。批准操作如下所示:

  private fun getApproveAction(pushId: String): NotificationCompat.Action {
    val approveIntent =
      Intent(this, NotificationActionReceiver::class.java).setAction(getString(R.string.notification_action_approve))
        .apply {
          putExtra(PUSH_ID, pushId)
          putExtra(ACCEPTED, true)
        }
    val approvePendingIntent: PendingIntent =
      PendingIntent.getBroadcast(this, 1, approveIntent, PendingIntent.FLAG_CANCEL_CURRENT)
    return NotificationCompat.Action(R.drawable.done, "Accept", approvePendingIntent)
  }

当应用程序处于前台时,通知会通过两个操作完美显示。但是当应用程序在后台运行或关闭时,我只看到标题和正文,没有任何操作。我正在使用 Android 10 在像素 3a 模拟器上进行测试。

我已尝试将 Intent 格式更新为此处描述的 https://stackoverflow.com/a/47032464/4801470,但没有任何运气。

【问题讨论】:

    标签: android firebase firebase-cloud-messaging android-notifications


    【解决方案1】:

    问题是由我们的服务器发送的通知格式引起的。格式是

      const message = {
        token: pushToken,
        notification: {
          title: 'Title',
          body: 'Body',
        },
        data: {
          pushId,
        },
      };
    

    这意味着当应用程序在后台运行或关闭时,Firebase 正在构建通知本身,并且永远不会调用 add 函数。我们切换到:

    const message = {    
        token: pushToken,
        data: {
          pushId,
          title: 'Title',
          body: 'Body',
        },
      };
    
    

    这完全是数据推送,允许我们完全自己构建通知。

    这也意味着我们必须对构建通知进行另一项小改动。我们不是从消息中获取标题和正文,而是直接从数据中获取它们。

    NotificationCompat.Builder(this, getString(R.string.default_notification_channel_id))
            .setContentTitle(message.data.get("title") ?: "Title")
            .setContentText(message.data.get("body") ?: "Body")
            ...
    

    【讨论】:

      猜你喜欢
      • 2020-06-06
      • 2022-12-11
      • 1970-01-01
      • 2020-10-22
      • 2016-07-17
      • 1970-01-01
      • 1970-01-01
      • 2021-10-16
      • 2020-10-23
      相关资源
      最近更新 更多