Chat App using Firebase: Get notification when new message received - Android
<p>I am developing a chat app using Firebase Realtime Database. I have been able to send and receive messages properly. Now, I want to implement notification whenever new message is received. For that, I have created a <code>Service</code> which listens to database changes using <code>ChildEventListener</code> and creates notification. The problem is that I am creating notification in <code>onChildAdded</code> method and this method fires both for existing node in database and new one. This is causing notification to be created multiple times for same message whenever user navigate back and forth from app. </p>

<p>Here is how I am implementing it:</p>

<pre><code>chatMsgsRef.orderByChild(FirebaseDBKeys.LOCATION_LAST_UPDATED).addChildEventListener(new ChildEventListener() {

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

                ChatMessage message = dataSnapshot.getValue(ChatMessage.class);

                if (!message.getSenderId().equals(currentUserId)) {

                    mNotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);

                    NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(NotificationsService.this)
                            .setSmallIcon(R.drawable.message)
                            .setContentTitle("New Message from " + message.getReceipientName())
                            .setContentText(message.getMessage())
                            .setOnlyAlertOnce(true)
                            .setSound(RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION));
                    mBuilder.setAutoCancel(true);
                    mBuilder.setLocalOnly(false);


                    mNotificationManager.notify(NOTIFICATION_ID, mBuilder.build());

                }
            }

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

            }

            @Override
            public void onChildRemoved(DataSnapshot dataSnapshot) {

            }

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

            }

            @Override
            public void onCancelled(DatabaseError databaseError) {

            }
        });
</code></pre>

<p>How can I implement notifications in the way it works in other chat applications like whatsapp, etc.??</p>