通知取消无效

时间:2018-07-31 14:55:51

标签: android firebase

当我拥有一台设备时,通知取消功能有效。但是,当我再添加一个具有另一个ID的设备时,它不会取消任何通知。我不明白我在做什么错。

这是一些代码

private void cancelNotification(RemoteMessage remoteMessage) 
{
    int id = Integer.parseInt(remoteMessage.getData().get("id"));
    NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
    notificationManager.cancel(id);
}

private void sendNotification(RemoteMessage remoteMessage) 
{
    Intent intent = new Intent(this, Activity.class);
    intent.putExtra("url",remoteMessage.getData().get("url"));
    PendingIntent pintent = PendingIntent.getActivity(this, (int) System.currentTimeMillis(), intent , 0);

    Uri defaultSoundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);

    Notification notificationBuilder = new Notification.Builder(this)
            .setLargeIcon(BitmapFactory.decodeResource(getResources(),R.drawable.splash_launcher))
            .setSmallIcon(R.drawable.splash_launcher)
            .setContentTitle(remoteMessage.getData().get("title"))
            .setContentText(remoteMessage.getData().get("text"))
            .setAutoCancel(true)
            .setSound(defaultSoundUri)
            .setContentIntent(pintent)
            .build();

    int id = Integer.parseInt(remoteMessage.getData().get("id"));
    NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
    notificationManager.notify(id, notificationBuilder);
}

1 个答案:

答案 0 :(得分:0)

您显示的代码没有错。要取消您之前发送的通知,您必须使用与调用cancel函数相同的ID来调用notify函数。如果您的代码RemoteMessage不起作用,则您赋予cancelNotification函数的ID与您赋予RemoteMessage函数的sendNotification的ID不同。