当应用程序处于前台时未收到通知,单击通知时也未收到有效负载数据

Not receiving notification when app is in foreground also not receiving payload data when clicking on notification

所以,我试图在应用程序处于后台或前台时收到通知,并尝试将数据有效负载从 firebase 控制台发送到 android 应用程序 activity,但我得到了这个

  1. 我在应用程序处于后台时收到通知
  2. 应用在前台时收不到通知
  3. 此外,我从 firebase 控制台获取的数据负载,密钥 "str",未显示在 activity

请告诉我问题出在哪里,如何解决。

private static final String TAG = "FirebaseMessagingServic";

public FirebaseMessagingService() {
}

String value = "0";
@Override
public void onMessageReceived(RemoteMessage remoteMessage) {
    // Check if message contains a data payload.
    if (remoteMessage.getData().size() > 0) {
        Log.d(TAG, "Message data payload: " + remoteMessage.getData());
        value = remoteMessage.getData().get("str"); //key text in quotes

    }
    String title = remoteMessage.getNotification().getTitle(); //get title
    String message = remoteMessage.getNotification().getBody(); //get message

    sendNotification(title, message, value);
    // Check if message contains a notification payload.
  /*  if (remoteMessage.getNotification() != null) {



        Log.d(TAG, "Message Notification Title: " + title);
        Log.d(TAG, "Message Notification Body: " + message);


    }*/
}

@Override
public void onDeletedMessages() {

}

private void sendNotification(String title,String messageBody, String value) {
    Intent intent = new Intent(this, CS101noti.class);
    SharedPreferences prefs = getSharedPreferences("MyApp", MODE_PRIVATE);
    prefs.edit().putString("body", value).apply();

    intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);

    PendingIntent pendingIntent = PendingIntent.getActivity(this, 0 /* Request code */, intent,
            PendingIntent.FLAG_ONE_SHOT);

    Uri defaultSoundUri= RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
    NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this)
            .setSmallIcon(R.mipmap.ic_launcher)
            .setContentTitle(title)
            .setContentText(messageBody)
            .setAutoCancel(true)
            .setSound(defaultSoundUri)
            .setContentIntent(pendingIntent);

    NotificationManager notificationManager =
            (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);

    notificationManager.notify(0 /* ID of notification */, notificationBuilder.build());
}

我已经解决了:)

您只需要从 REST API 或 Postman 发送数据负载,并在 Java 代码中获取数据值, 它会像魅力一样工作:)