首页 > 解决方案 > 为什么我在打开活动时收到通知?

问题描述

编辑:有人在 STACKOVERFLOW 上有解决方案吗?

我正在使用 Firebase 数据库,并希望在添加新孩子后立即显示通知。

我正在使用“ChildEventListener”来获取它。

这是我的代码:

 dbProducts.addChildEventListener(new ChildEventListener() {
                @Override
                public void onChildAdded(@NonNull DataSnapshot dataSnapshot, @Nullable String s) {

//                    Toast.makeText(ShowNotifActivity.this, "Child Added ", Toast.LENGTH_SHORT).show();

                    Intent intent = new Intent(ShowNotifActivity.this, MainActivity.class);
                    intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                    PendingIntent pendingIntent = PendingIntent.getActivity(getApplicationContext(), 0, intent, PendingIntent.FLAG_ONE_SHOT);
                    String channelId = "MyNotifications";
                    NotificationCompat.Builder builder = new NotificationCompat.Builder(getApplicationContext(), channelId)
                            .setSmallIcon(R.drawable.notification)
                            // .setLargeIcon(R.drawable.ic_notifications_active_black_24dp)

                            .setContentTitle("New Notification")
                            .setContentText("Click here to View ");
                    ;
                    NotificationManager manager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
                    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                        NotificationChannel channel = new NotificationChannel(channelId, "MyNotifications", NotificationManager.IMPORTANCE_DEFAULT);
                        manager.createNotificationChannel(channel);
                    }
                    manager.notify(0, builder.build());

                }

                @Override
                public void onChildChanged(@NonNull DataSnapshot dataSnapshot, @Nullable String s) {
//                    Toast.makeText(ShowNotifActivity.this, "Child Changed", Toast.LENGTH_SHORT).show();
                }

                @Override
                public void onChildRemoved(@NonNull DataSnapshot dataSnapshot) {

                }

                @Override
                public void onChildMoved(@NonNull DataSnapshot dataSnapshot, @Nullable String s) {

                }

                @Override
                public void onCancelled(@NonNull DatabaseError databaseError) {

                }
            });

当在 firebase 数据库中添加新的孩子时,如何只显示一次通知。

问题是,只要我打开 Activity ,即使我没有更新通知也会触发它更改或在数据库中添加任何内容。如何修复

标签: androidfirebase-realtime-databaseandroid-notifications

解决方案


当您使用addChildEventListener在数据库中的某个位置附加侦听器时,onChildAdded将为该位置的每个孩子调用一次,即使它不是新的。这就是为什么您的通知总是显示的原因。

如果您只想获得“新”项目,您将需要想出一种方法来确定哪些孩子对用户来说实际上是新的,并在您的查询中过滤这些孩子。也许时间戳或其他标志对您有用。


推荐阅读