代码之家  ›  专栏  ›  技术社区  ›  Snake

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

  •  2
  • Snake  · 技术社区  · 6 年前

    当收到fcm消息并且应用程序在后台时,我尝试显示通知。我试过不同口味的通知,但没有运气。通知不会显示

    这是密码

    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());
    
        }
    

    有什么建议吗?

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

    我在日志猫里没有错误。我还设置了所有的通知设置如下代码。请注意,我的设备在后台时已经接收并显示来自FCM的通知。但是当它在前台并且“我”处理通知的显示时,它就不起作用了

    2 回复  |  直到 6 年前
        1
  •  1
  •   Pratik Butani Umesh N    6 年前

    希望你的服务器正在向你发送通知 data

    我在这里看到了您的代码,您使用 remoteMessage.getNotification()

    数据 按键如下 ( 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

    希望你能在这方面得到帮助。有什么问题一定要告诉我。

        2
  •  -4
  •   Pratik Butani Umesh N    6 年前

    如果您不使用自己的服务器,那么您就无法实现这一点。您需要使用自己的服务器来修改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"
     }
    }
    

    当您的服务器将用“data”修改“notification”标记时,只有您可以在后台接收通知。