kmplflcn February 2016

Android Notification re-appears after being opened

I am posting notifications everytime a new announcement is posted. I fetch announcements from Firebase so I call the notification function on onChildAdded(). I'm receiving notifications for every new announcement. However, if there isn't a new announcement, the latest announcement re-appears every once in a while even after opening it.

Notifications class: public class FirebaseBackgroundService extends Service {

private Firebase f = new Firebase("https://infotrack.firebaseio.com/infotrack/announcements");
Query queryAnnouncements = f.orderByChild("timeStamp").limitToLast(1);
Firebase ref = new Firebase("https://infotrack.firebaseio.com/guests");
Firebase userRef = ref.child("users/"+ref.getAuth().getUid()+"/notifications");

@Override
public IBinder onBind(Intent arg0) {
    return null;
}

@Override
public void onCreate() {
    super.onCreate();

            ChildEventListener handler = new ChildEventListener() {

        @Override
        public void onChildAdded(final DataSnapshot dataSnapshot, String s) {

            final AnnouncementsList announcement = dataSnapshot.getValue(AnnouncementsList.class);
            Log.e("announcements", dataSnapshot.getKey());

            userRef.addValueEventListener(new ValueEventListener() {
                @Override
                public void onDataChange(final DataSnapshot notifSnapshot) {
                    Log.e("check", notifSnapshot.getValue().toString());
                    if (notifSnapshot != null) {
                    Notifications notif = notifSnapshot.getValue(Notifications.class);
                        if(!dataSnapshot.getKey().equals(notif.getAnnouncements())){
                            buildNotif("Announcement", announcement.getBody(), "New announcement from Infotrack");
                            userRef.child("announcements").setValue(dataSnapshot.getKey());
                        }
                    }
                }

                @Override
            

Answers


Frank van Puffelen February 2016

When the app connects to the server, Firebase will call onChildAdded() for each existing child at the location. So unless you delete the children, the number of onChildAdded() invocations will keep going up.

You have two options:

  • remove the notification from the database after you've shown it to the user

    public void onChildAdded(DataSnapshot snapshot, String previousChildKey) {
        AnnouncementsList announcement = snapshot.getValue(AnnouncementsList.class);
        buildNotif(announcement.getBody());
        snapshot.getRef().remove();
    }
    
  • mark the notifications that the user has seen and skip those

Most applications go with the first option, since it automatically keeps the queue short.

Post Status

Asked in February 2016
Viewed 3,578 times
Voted 5
Answered 1 times

Search




Leave an answer