I have a button, when I press it some data is fetched from FirebaseDatabase
and then a notification
is fired.
Here's how:
aReference.child(rID).addChildEventListener(new ChildEventListener() {
@Override
public void onChildAdded(DataSnapshot dataSnapshot, String s) {
if (dataSnapshot.getValue() != null) {
Map<String, String> newRequest = (Map<String, String>) dataSnapshot.getValue();
uAU = newRequest.get("pName");
final int m = (int) ((new Date().getTime() / 1000L) % Integer.MAX_VALUE);
Intent notificationIntent = new Intent(getBaseContext(), NotificationARBroadcastReceiver.class);
notificationIntent.putExtra(NotificationARBroadcastReceiver.NOTIFICATION, getNotificationAU());
PendingIntent pendingIntent = PendingIntent.getBroadcast(getBaseContext(), m, notificationIntent, PendingIntent.FLAG_UPDATE_CURRENT);
AlarmManager alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
alarmManager.set(AlarmManager.ELAPSED_REALTIME_WAKEUP, 0, pendingIntent);
}
}
});
Here's NotificationARBroadcastReceiver.class
:
public class NotificationARBroadcastReceiver extends BroadcastReceiver {
public static String NOTIFICATION = "notification";
public static NotificationManager mNotifyMgr;
public static int m;
@Override
public void onReceive(Context context, Intent intent) {
m = (new Random()).nextInt(10000);
Log.d("mMain", String.valueOf(m));
mNotifyMgr =
(NotificationManager) context.getSystemService(NOTIFICATION_SERVICE);
Notification notification = intent.getParcelableExtra(NOTIFICATION);
notification.defaults |= Notification.DEFAULT_SOUND;
notification.defaults |= Notification.DEFAULT_VIBRATE;
mNotifyMgr.cancel(m);
mNotifyMgr.notify(m, notification);
}
}
Here's getNotificationAU()
:
private Notification getNotificationAU() {
mBuilder = new NotificationCompat.Builder(getBaseContext())
.setSmallIcon(R.mipmap.app_icon_1)
.setContentTitle("title")
.setContentText(***);
Intent resultIntent = new Intent(getBaseContext(), MainActivity.class);
PendingIntent resultPendingIntent = PendingIntent.getActivity(
getBaseContext(),
0,
resultIntent,
PendingIntent.FLAG_UPDATE_CURRENT
);
mBuilder.setAutoCancel(true);
mBuilder.setContentIntent(resultPendingIntent);
return mBuilder.build();
}
The problem is that on pressing the button even once, notifications are fired multiple times and many same notifications are shown in the status bar.
Why is this happening and how to fire only one notification?
Please let me know.
Adding
mNotifyMgr.cancelAll();
(wheremNotifyMgr
is theNotificationManager
) beforemNotifyMgr.notify(m, notification);
did the job for me!