当应用程序处于前台并且调用onMessageReceived时不显示通知

时间:2019-02-08 06:27:23

标签: android firebase android-notifications firebase-notifications

当我收到fcm消息且APP处于后台时,我试图显示通知。我尝试了各种通知方式,但没有运气。通知不会显示

这是代码

public void onMessageReceived(RemoteMessage remoteMessage) {
        Log.d(GlobalVar.TAG, "From: " + remoteMessage.getFrom());
        super.onMessageReceived(remoteMessage);


        String channelId = getString(R.string.notification_channel_id);
        NotificationCompat.Builder builder = new  NotificationCompat.Builder(this, channelId)
                .setSmallIcon(R.mipmap.ic_launcher)
                .setContentTitle(remoteMessage.getNotification().getTitle())
                .setContentText(remoteMessage.getNotification().getBody()).setAutoCancel(true);
        NotificationManager manager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);

        manager.notify(0, builder.build());

    }

我知道这是因为我得到了日志而被调用。 如果应用程序在后台运行,则FCM将显示通知。当应用程序处于前台时,上面的代码没有显示它 有什么建议吗?

PS:我在Application类中创建了频道

我在日志猫中没有收到错误。我还按照下面的代码设置所有通知设置。请注意,我的设备在后台时已经从FCM接收并显示通知。但是当它处于前台并且“ I”处理通知的显示时,它将不起作用

2 个答案:

答案 0 :(得分:1)

希望您的服务器通过data键向您发送通知。

正如我看到的代码所示,您正在使用 remoteMessage.getNotification()

获取通知数据

现在,您必须对它们以data键发送的服务器端脚本进行更改,如下所述You can test temporary before changing server code

{
 "to" : "YOUR_FCM_TOKEN_WILL_BE_HERE",
 "collapse_key" : "type_a",
 "data" : {
     "body" : "Body of Your Notification in Data",
     "title": "Title of Your Notification in Title",
     "key_1" : "Value for key_1",
     "key_2" : "Value for key_2"
 }
}

然后您将收到如下信息:

@Override
public void onMessageReceived(RemoteMessage remoteMessage) {
    super.onMessageReceived(remoteMessage);

    Log.d(TAG, "From: " + remoteMessage.getFrom());

    // Check if message contains a data payload.
    if (remoteMessage.getData().size() > 0) {
        Log.d(TAG, "Message data payload: " + remoteMessage.getData());
    }
}

了解更多信息

enter image description here

希望您会在此方面获得帮助。如果您有任何问题,请告诉我。

答案 1 :(得分:-4)

如果您不使用自己的服务器,那么您将无法实现。您需要使用自己的服务器来修改JSON格式:

{
 "to" : "YOUR_FCM_TOKEN_WILL_BE_HERE",
 "collapse_key" : "type_a",
 "notification" : {
     "body" : "Body of Your Notification in Data",
     "title": "Title of Your Notification in Title",
     "key_1" : "Value for key_1",
     "key_2" : "Value for key_2"
 }
}

收件人:

{
 "to" : "YOUR_FCM_TOKEN_WILL_BE_HERE",
 "collapse_key" : "type_a",
 "data" : {
     "body" : "Body of Your Notification in Data",
     "title": "Title of Your Notification in Title",
     "key_1" : "Value for key_1",
     "key_2" : "Value for key_2"
 }
}

当服务器将“通知”标签修改为“数据”时,只有您可以在后台接收通知。

相关问题