有什么方法可以在后台使用 FirebaseMessagingService 从推送通知中获取数据吗?

mar*_*337 4 android android-service firebase firebase-cloud-messaging android-push-notification

我正在使用FirebaseMessagingService我的推送通知。它按照应用程序中的预期工作。onMessageReceived被调用,我可以获取通知标题和正文+数据有效负载,并根据有效负载数据发送反应到我Activity使用的LocalBroadcastManager.

但后台推送通知存在问题。这只会在后台显示通知,但不会创建它,onMessageReceived因为如果应用程序在后台,则无法调用此函数。

根据文档,推送通知的数据部分存储extras在 Activity 恢复时可以找到。我已经有这个功能并且它正在工作。但问题是我没有标题和消息,因为它没有发送到onMessageReceived,我无法捕获此信息。

有什么方法可以获取吗?因为我需要在应用程序内的对话框窗口中显示它。推送通知不仅仅是文本和标题,也不仅仅是向用户提供的信息,而是会执行一些操作。

接收通知标题、正文和负载FirebaseMessagingService

override fun onMessageReceived(msg: RemoteMessage?) {
        val pNotification = msg?.notification
        val payload = msg?.data
        if (pNotification != null){
            val ntitle = pNotification.title
            val nMsg = pNotification.body
        }
        //working with payload - creating notification and Intent for LocalBroadcastmanager
}
Run Code Online (Sandbox Code Playgroud)

从内部的额外部分捕获有效负载onResume()

private fun maybeFindBackgroundPayload(extras: Bundle?){
        if (extras != null){
            extras.keySet().forEach { key->
                val keyValue = extras[key]
                App.log("BackgroundKeyValues: $keyValue")
                if (key.equals("gcm.notification.body", ignoreCase = true) && keyValue != null){
                    ...
                    //Working with payload data key value - dont have title and body
                }
            }
        }
    }
Run Code Online (Sandbox Code Playgroud)

Der*_*mas 8

不幸的是,它不可能按照您希望的方式工作。

如果推送通知的有效负载中有通知部分,并且您的应用程序位于后台,则永远不会调用 onMessageReceived。该通知由 firebase 自动创建并显示。无法拦截此行为并修改通知或执行任何其他操作。只有单击通知后,您的应用程序才会获得控制权。

当应用程序位于前台时,正如您所提到的, onMessageReceived 将始终被调用。

确保在所有情况下(前台、后台和应用程序终止)调用 onMessageReceived 的唯一方法是从 firebase 发送仅数据负载。也就是说,删除 firebase 有效负载正文的通知部分并将内容(标题、正文等)放入有效负载的数据部分。并在 onMessageReceived 中将此标题、正文等分配给您正在创建的通知。

以下是 Firebase 的有效负载:

{
"registration_ids":[
  "firebase_token"
],
"data":{
    "body":"body of notification",
    "title":"title of notification",
    "otherdatakey":"otherdatavalue"
}
}
Run Code Online (Sandbox Code Playgroud)

然后在 onMessageReceived 函数中,您需要显式提取标题和正文并将其分配给通知(当然还有您想要执行的任何其他操作):

@Override
public void onMessageReceived(RemoteMessage message) {
Map<String, String> dataMap = message.getData();
String title = dataMap.get("title");
String body = dataMap.get("body");
String otherdatavalue = dataMap.get("otherdatakey");
NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this)
            .setContentTitle(title)
            .setContentText(body)
            .setContentIntent(pendingIntent);//To handle click of notification

}
Run Code Online (Sandbox Code Playgroud)