如何在 firestore android studio 中获取新添加数据的通知?

How to get notifications of newly added data in firestore android studio?

我正在我的应用程序上做一个通知,我正在使用 firestore。我的问题是当 snapshotlistener 检测到数据库中有新添加的数据时,我想向用户发送通知但是当我打开应用程序时,即使我没有添加新数据,它也会立即显示现有通知.我需要一些条件,在这些条件下我只能获取新添加的数据,或者如果我的数据库数据中缺少一些需要克服此问题的东西。下面是我的数据库结构。

db.collection("Buyers")
                .document(userID)
                .collection("Notifications")
                .addSnapshotListener(new EventListener<QuerySnapshot>() {
                    @Override
                    public void onEvent(@Nullable QuerySnapshot snapshots, @Nullable FirebaseFirestoreException e) {
                        if (e != null) {
                            Log.e(LOG_DB, e.toString());
                            return;
                        }
                        for (DocumentChange dc : snapshots.getDocumentChanges()) {

                            if (dc.getType() == DocumentChange.Type.ADDED) {
                                String title = dc.getDocument().getData().get("notificationTitle").toString();
                                String body = dc.getDocument().getData().get("notificationBody").toString();

                                //Method to set Notifications
                                getNotification(title, body);
                            }
                        }
                    }
                });

我能够得到我想要的,但我不确定这是否是正确的方法。

Calendar calendar = Calendar.getInstance();
    calendar.add(Calendar.MINUTE, -5);
    Date before = calendar.getTime();

    Calendar calendar1 = Calendar.getInstance();
    Date until = calendar1.getTime();

    for (DocumentChange dc : snapshots.getDocumentChanges()) {
        Date date = (Date) dc.getDocument().getData().get("notificationDate");
        if (dc.getType() == DocumentChange.Type.ADDED) {
            if (!before.after(date) && !until.before(date)){
                Log.d("life", "Data: "+date);
                String title = dc.getDocument().getData().get("notificationTitle").toString();
                String body = dc.getDocument().getData().get("notificationBody").toString();
                getNotification(title, body);
            }
        }
    }

我在这里所做的是检索当前时间和当前时间减去 5 分钟。(您可以选择延迟多少分钟)然后设置条件它必须只显示延迟 5 分钟内的通知。

注: 我知道这不是正确的做法,但这得到了我想要的结果。如果您不想要我的回答,请告诉我并post您自己的回答,以便我确认您的回答。

如果您只想发送通知,您可以使用 Firebase 云消息,它可以提供您尝试自己实现的功能。 https://firebase.google.com/docs/cloud-messaging

如果您想在 Firestore 中的数据发生更改后发送通知,您可以使用 FireStore 触发器 (https://firebase.google.com/docs/functions/firestore-events) and send a Notification via a firebase function call (Send push notifications using Cloud Functions for Firebase)

我遇到了类似的问题,我是这样解决的:

  1. 获取您当前添加的项目的数量并保存在“共享首选项”中

  2. 打开应用程序后获取当前项目数并与共享首选项中保存的数量进行比较

  3. 设置一个条件,如果当前项目数大于共享首选项中保存的数量,则调用通知。