为什么从Firebase检索数据时会多次触发通知?

时间:2016-12-28 05:57:00

标签: android firebase notifications broadcastreceiver android-notifications

我有一个按钮,当我按下它时,会从FirebaseDatabase获取一些数据,然后触发notification

以下是:

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();
}

问题是按下按钮一次,通知会多次触发,状态栏中会显示许多相同的通知。

为什么会发生这种情况以及如何只触发一个通知?

请告诉我。

1 个答案:

答案 0 :(得分:0)

mNotifyMgr.cancelAll();之前添加mNotifyMgr(其中NotificationManagermNotifyMgr.notify(m, notification);)为我完成了这项工作!