问题
Edit : DO anyone have a solution for this on STACKOVERFLOW ?
I am using Firebase Database and wanted to show notification as soon as new child is added.
I am using "ChildEventListener" to acquire it.
Here is my code:
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) {
}
});
How can the Notification be shown only once as a new child is added in firebase database.
the problem is as soon as i open the Activity , the notification triggers even when i have not updated it changed or added anything in the database. How can it be fixed
回答1:
When you use addChildEventListener
to attach a listener at a location in the database, onChildAdded
will get called once for each child at that location, even if it isn't new. That's why your notification is always showing.
If you only want to get "new" items, you will need to come up with a way to determine which children are actually new to the user, and filter for those children in your query. Maybe a timestamp or some other flag will work for you.
来源:https://stackoverflow.com/questions/59446732/why-i-get-the-notification-just-opening-the-activity