0
我有一個按鈕,當我按下它時,有些數據從FirebaseDatabase
中取出,然後notification
被激發。爲什麼通知在從Firebase檢索數據時多次被觸發?
方法如下:
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);
}
}
});
這裏的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);
}
}
這裏的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();
}
問題是,在按下按鈕甚至一度,通知被解僱多次並且狀態欄中會顯示許多相同的通知。
爲什麼發生這種情況,以及如何觸發一個通知?
請讓我知道。
看起來你有多個孩子在'aReference.child(rID)'下,每個'onChildAdded'都會顯示新的通知 – Wilik
@Wilik是的,有多個孩子。那麼,即使在這種情況下,我怎麼才能顯示通知? –
它取決於您的通知目的,您可以改爲使用ValueEventListener,爲每個通知設置相同的ID,或檢查在發佈新通知之前是否顯示通知。 – Wilik