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 Service
which listens to database changes using ChildEventListener
and creates notification. The problem is that I am creating notification in onChildAdded
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.
Here is how I am implementing it:
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) {
}
});
How can I implement notifications in the way it works in other chat applications like whatsapp, etc.??