android - 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但没有任何运气。
解决方案
该问题是由我们的服务器发送的通知格式引起的。格式是
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")
...
推荐阅读
- ios - iOS 15:为通知启用“在应用程序中配置”选项
- arrays - 如何根据 C 中的用户输入创建交换二维数组元素的函数?
- r - 将格式化为字符的无空格日期转换为日期
- java - 创建一个返回 ArrayList 的方法
- r - RMD (PDF) 中的 ggforce facet_wrap_paginate 生成半页图
- android - 错误:无法将元素类型“TextSpan”分配给列表类型“Widget”-Flutter
- nsurlsession - 如何正确测试通用链接?
- android - 像 BottomAppBar 垂直的东西?
- embedded - Flashwrite 在 dsPIC33EV256GM0022 中不起作用
- python - 使用fuzzyWuzzy在名称值上有效地连接两个熊猫数据框