java - 应用程序关闭时不会检索 FCM 通知

标签 java android firebase android-studio firebase-cloud-messaging

我正在将 Firebase 云消息传递的通知检索到我的 Android 应用程序中。但问题是当我的应用程序打开或处于运行状态时,在这种情况下只有我的应用程序正在检索通知。如果我没有使用我的应用程序或者我的应用程序未打开,并且我发送了任何推送通知,表明我的应用程序中未检索到通知。

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

        mFirestore = FirebaseFirestore.getInstance();

        if (remoteMessage.getData() != null) {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O)
                sendNotificationAPI26(remoteMessage);

            else
                sendNotification(remoteMessage);
        }
    }

    private void sendNotification(RemoteMessage remoteMessage) {

        isNotificationMatching = false;
        Intent intent = new Intent(this, Dashboard.class);
        intent.putExtra("notificationFragment", "showNotifications");
        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);

        PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent, PendingIntent.FLAG_ONE_SHOT);


        final Map<String, String> data = remoteMessage.getData();

        String title = data.get("title");
        String description = data.get("description");
        String url = data.get("url");
        String code = data.get("code");
        String actual_price = data.get("actual_price");
        String deal_price = data.get("deal_price");
        String key = data.get("key");
        final String id = data.get("id");

        mFirestore.collection("notifications").get().addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() {
            public void onComplete(@NonNull Task<QuerySnapshot> task) {
                if (task.isSuccessful()) {
                    for (QueryDocumentSnapshot document : task.getResult()) {
                        if (document.getData().get("id").equals(id)) {
                            isNotificationMatching = true;
                            break;
                        }
                    }

                    if (!isNotificationMatching) {
                        postDataToFirebaseServer(data);
                    }

                } else {
                    Log.d(TAG, "Error getting documents: ", task.getException());
                }
            }
        });


        Uri defaultSoundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
        NotificationCompat.Builder builder = new NotificationCompat.Builder(this)
                .setSmallIcon(R.drawable.app_logo)
                .setContentText(title)
                .setAutoCancel(true)
                .setSound(defaultSoundUri);
        builder.setContentIntent(pendingIntent);

        NotificationManager noti = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
        noti.notify(new Random().nextInt(), builder.build());
    }

    private void postDataToFirebaseServer(Map<String, String> data) {

        Map<String,Object> postDataMap = new HashMap<>();
        postDataMap.put("title", data.get("title"));
        postDataMap.put("description", data.get("description"));
        postDataMap.put("url", data.get("url"));
        postDataMap.put("id", data.get("id"));
        postDataMap.put("code", data.get("code"));
        postDataMap.put("actual_price", data.get("actual_price"));
        postDataMap.put("deal_price", data.get("deal_price"));
        postDataMap.put("key", data.get("key"));

        postDataMap.put("timestamp", FieldValue.serverTimestamp());


        mFirestore.collection("notifications").add(postDataMap).addOnSuccessListener(new OnSuccessListener<DocumentReference>() {
            @Override
            public void onSuccess(DocumentReference documentReference) {
//                Toast.makeText(getA.this, "Success", Toast.LENGTH_SHORT);
            }
        }).addOnFailureListener(new OnFailureListener() {
            @Override
            public void onFailure(@NonNull Exception e) {
                String error = e.getMessage();
//                Toast.makeText(Testing.this, "Failed", Toast.LENGTH_SHORT);
            }
        });

    }

    private void sendNotificationAPI26(RemoteMessage remoteMessage) {
        Intent intent = new Intent(this, Dashboard.class);
        intent.putExtra("notificationFragment", "showNotifications");
        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);

        PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent, PendingIntent.FLAG_ONE_SHOT);

        final Map<String, String> data = remoteMessage.getData();

        String title = data.get("title");
        String description = data.get("description");
        String url = data.get("url");
        String code = data.get("code");
        String actual_price = data.get("actual_price");
        String deal_price = data.get("deal_price");
        String key = data.get("key");
        final String id = data.get("id");

        mFirestore.collection("notifications").get().addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() {
            public void onComplete(@NonNull Task<QuerySnapshot> task) {
                if (task.isSuccessful()) {
                    for (QueryDocumentSnapshot document : task.getResult()) {
                        if (document.getData().get("id").equals(id)) {
                            isNotificationMatching = true;
                            break;
                        }
                    }

                    if (!isNotificationMatching) {
                        postDataToFirebaseServer(data);
                    }

                } else {
                    Log.d(TAG, "Error getting documents: ", task.getException());
                }
            }
        });

        NotificationHelper helper;
        Notification.Builder builder;

        Uri defaultSoundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
        helper = new NotificationHelper(this);
        builder = helper.getLootBoxNotification(title, description, url, id, code, actual_price, deal_price, key, defaultSoundUri);
        helper.getManager().notify(new Random().nextInt(), builder.build());
        builder.setContentIntent(pendingIntent);

    }
}

我希望当我的应用程序关闭或不处于运行状态时,发送任何推送通知,该通知也将在应用程序内部检索。

最佳答案

尝试从有效负载中删除“通知” key 并仅提供“数据” key 。

正文/有效负载/JSON 请求:

{
    "collapse_key": "type_a",
    "notification": {
        "badge": "2",
        "module": "announcements",
    "action": "announcementAddedByWarden",
    "id": "2455",
    "title": "Test Notification",
    "body": "Check Notification"
},
"data": {
    "badge": "2",
    "module": "Announcement",
    "id": "2455",
    "title": "Test Notification",
    "body": "Check Notification"
},
"registration_ids": [
    "dJokCoAJRfyHpL3y9rQWxL:APA91bGNszapf1bnQapVHW1CMLT14SXMmjYBmXooRUiiMEWpvawkZ9Kv5SzRz4cnqHhnwFGWT3uXfzgGn3ygysJE1bkfG0nNomCtL_ikDzE0TiP0TZjhQBDSj_1ydFUyrnQKNSnszqgW",
    "dAdFOnor6FE:APA91bHM2FiBf3nfuqcQixr5syVnUcICI8bnA0rxAp1noFLfU9DozGSyJl2jK2wf0EQfIuywA6_1b0_CUmZQoFq1Nhuuz2-bH3uO6MqZ-kfog8TD8USZTUb3MHeK1z6Mtx7RQNAi3UZP"
 ]
}

您可以从有效负载中删除数据对象,如下面的代码 fragment 所示:

 "data": {
    "badge": "2",
    "module": "Announcement",
    "id": "2455",
    "title": "Test Notification",
    "body": "Check Notification"
},

正确的格式为:

{
"collapse_key": "type_a",
"notification": {
    "badge": "2",
    "module": "announcements",
    "action": "announcementAddedByWarden",
    "id": "2455",
    "title": "Test Notification",
    "body": "Check Notification"
},
"registration_ids": [
    "dJokCoAJRfyHpL3y9rQWxL:APA91bGNszapf1bnQapVHW1CMLT14SXMmjYBmXooRUiiMEWpvawkZ9Kv5SzRz4cnqHhnwFGWT3uXfzgGn3ygysJE1bkfG0nNomCtL_ikDzE0TiP0TZjhQBDSj_1ydFUyrnQKNSnszqgW",
    "dAdFOnor6FE:APA91bHM2FiBf3nfuqcQixr5syVnUcICI8bnA0rxAp1noFLfU9DozGSyJl2jK2wf0EQfIuywA6_1b0_CUmZQoFq1Nhuuz2-bH3uO6MqZ-kfog8TD8USZTUb3MHeK1z6Mtx7RQNAi3UZP"
  ]
}

关于java - 应用程序关闭时不会检索 FCM 通知,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57580464/

相关文章:

java - 文本框无法正常工作

android - 为什么 Messenger 应用程序会在应用程序强制停止时收到消息?

javascript - Firebase pubsub 函数计划无效的计划或时区

android - 正在进行的通知可以忽略

firebase - 错误 : 16 UNAUTHENTICATED: Failed to retrieve auth metadata with error: Could not refresh access token

android - 使用 kotlin for android 应用程序将 pdf 文件上传到 firebase 存储

java - 拖放和调整元素大小

java - Hibernate设计模式问题

java - 在 SwingUtilities.invokeLater 中放置(和不放置)什么?

android - 如何检查处理程序是否有回调