首页 > 解决方案 > Notification.addAction 在应用程序后台或关闭时不起作用

问题描述

我正在使用 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 模拟器上进行测试。

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

标签: androidfirebasefirebase-cloud-messagingandroid-notifications

解决方案


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

  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")
        ...

推荐阅读