而不是自定义消息

而不是自定义消息

本文介绍了当应用程序未运行时,FCM 显示默认消息而不是自定义消息的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

问题:我的 FCM 代码针对不同的情况显示不同的消息:

案例 1:应用程序运行时显示自定义通知正文

案例 2:当应用在后台运行时,它会显示自定义通知正文

案例 3:当应用程序未运行时,它会显示从 FCM 收到的默认消息,而不是自定义消息

代码:

/* 类扩展 FirebaseMessagingService() */覆盖乐趣 onMessageReceived(remoteMessage: RemoteMessage) {尝试 {/* 其他一些代码 */val pendingIntent = PendingIntent.getActivity(this, 0, Intent(), PendingIntent.FLAG_ONE_SHOT)val builder = NotificationCompat.Builder(this, "" + R.string.notification_channel_id).setSmallIcon(R.mipmap.ic_launcher_round).setContentTitle(remoteMessage.notification!!.title).setContentText(getString(R.string.custom_message_body)).setAutoCancel(真).setContentIntent(待定意图)val manager = getSystemService(Context.NOTIFICATION_SERVICE) 作为 NotificationManagerif (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {val channel = NotificationChannel("" + R.string.notification_channel_id, "警报通道", NotificationManager.IMPORTANCE_DEFAULT)manager.createNotificationChannel(通道)}manager.notify(0, builder.build())/* super.onMessageReceived(remoteMessage) 被删除以防止默认功能 */} 捕捉(e:异常){e.printStackTrace()}}
解决方案

这是意料之中的.FCM 对应用程序状态(前台和后台/已终止)有不同的行为.根据您的用例,您应该通过从服务器发送的有效负载来处理此问题.

从服务器发送的消息必须以通知"或数据"格式从仪表板或服务器端 API 发送.注意:从 firebase dashobard 您只能发送通知"正文而不是数据.在这种情况下,FCM 会直接显示通知而不给您的应用回调.

服务器端以下是示例格式:

通知类型格式注意:Android系统默认会在通知托盘中显示通知,您不需要显示.

 {"to": "your_token_id",通知" : {"title" : "FCM 通知标题!","body" : "FCM 通知潜台词!",content_available":是的,优先级":高"}}

数据格式(用于在应用中接收回调,在前台和后台)注意:你必须自己处理回调和显示通知.

{"to": "your_token_id",数据" : {"title" : "FCM 通知标题","subtext" : "FCM 通知子标题",类型":999",优先级":高"}}

Android 客户端要处理在您的 Android 接收器中收到的有效负载,请查看官方指南

Problem: My FCM code shows different messages to different cases:

Case 1: When app is running it shows the custom notification body

Case 2: When the app is running in the background it shows custom notification body

Case 3: When the app is not running it shows the default message received from FCM than the custom message

Code:

/* The class extends FirebaseMessagingService() */

override fun onMessageReceived(remoteMessage: RemoteMessage) {
        try {
/* Some other codes */

            val pendingIntent = PendingIntent.getActivity(this, 0, Intent(), PendingIntent.FLAG_ONE_SHOT)
            val builder = NotificationCompat.Builder(this, "" + R.string.notification_channel_id)
                    .setSmallIcon(R.mipmap.ic_launcher_round)
                    .setContentTitle(remoteMessage.notification!!.title)
                    .setContentText(getString(R.string.custom_message_body))
                    .setAutoCancel(true)
                    .setContentIntent(pendingIntent)
            val manager = getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                val channel = NotificationChannel("" + R.string.notification_channel_id, "Alert channel", NotificationManager.IMPORTANCE_DEFAULT)
                manager.createNotificationChannel(channel)
            }
            manager.notify(0, builder.build())

/* super.onMessageReceived(remoteMessage) was REMOVED to prevent default functions */
        } catch (e: Exception) {
            e.printStackTrace()
        }
    }
解决方案

This is expected.FCM has different behaviours for app status (foreground and background / killed).You should handle this by the payload you sent from server, according to your use case.

The msg sent from server has to be sent in either "notification" or "data" format, from dashboard or server side api.Note: From firebase dashobard you can only send "notification" body and not data. In such cases, FCM will directly display the notif without giving a callback to your app.

Server sideBelow are sample formats :

Notification Type FormatNote : Android System will by default display the notification in the notification tray and you don't need to display it.

 {
    "to": "your_token_id",
     "notification" : {
             "title" : "FCM Notification title!",
             "body" : "FCM Notification subtext!",
             "content_available" : true,
             "priority" : "high"
     }
}

Data Format (For receiving callback in app, in foreground and background)Note : You have to handle callback and display notif on your own.

{
    "to": "your_token_id",

    "data" : {
         "title" : "FCM Notification Title ",
         "subtext" : "FCM Notification Sub Title",
         "type" : "999",
         "priority" : "high"
    }
}

Android ClientTo handle the payload received in your Android receiver, checl the official guide here

/* The class extends FirebaseMessagingService() */
 override fun onMessageReceived(remoteMessage: RemoteMessage) {

        Log.d(TAG, "From: ${remoteMessage.from}")

        // Check if message contains a data payload.
        remoteMessage.data.isNotEmpty().let {
            Log.d(TAG, "Message data payload: " + remoteMessage.data)

        if (/* Check if data needs to be processed by long running job */ true) {
            // For long-running tasks (10 seconds or more) use WorkManager.
            scheduleJob()
        } else {
            // Handle message within 10 seconds
            handleNow()
        }
    }

    // Check if message contains a notification payload.
    remoteMessage.notification?.let {
        Log.d(TAG, "Message Notification Body: ${it.body}")
    }

    // Also if you intend on generating your own notifications as a result of a received FCM
    // message, here is where that should be initiated. See sendNotification method below.
}

Check the documentation here

这篇关于当应用程序未运行时,FCM 显示默认消息而不是自定义消息的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-03 19:52