I implemented a notification builder inside a childEventListener in order for my users to receive notifications when new posts are available... the notification builder method is:
public void showNotification() {
NotificationCompat.Builder mBuilder =
new NotificationCompat.Builder(this)
.setSmallIcon(R.drawable.app_logo)
.setContentTitle("new post")
.setContentText("Check it out guys");
Intent resultIntent = new Intent(this, MainActivity.class);
android.support.v4.app.TaskStackBuilder stackBuilder = android.support.v4.app.TaskStackBuilder.create(this);
stackBuilder.addParentStack(MainActivity.class);
stackBuilder.addNextIntent(resultIntent);
PendingIntent resultPendingIntent = stackBuilder.getPendingIntent(0,PendingIntent.FLAG_UPDATE_CURRENT);
mBuilder.setContentIntent(resultPendingIntent);
mBuilder.setAutoCancel(true);
NotificationManager mNotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
int mId;
mId = 1;
mNotificationManager.notify(mId, mBuilder.build());
}
and inside the onCreate() method I have
mDatabasePosts = FirebaseDatabase.getInstance().getReference().child("posts");
mDatabasePosts.addChildEventListener(new ChildEventListener() {
@Override
public void onChildAdded(DataSnapshot dataSnapshot, String s) {
showNotification();
}
@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) {
}
});
my users are notified when a child is added to the database but they are also receiving that notification when they load the app... I tried implementing this on the onPause() but then the notification appear everytime they press the home button. Please advise where do I go wrong.
Thanks!