调用notification.cancel后通知未被取消

4

我创建了带有操作按钮的通知。当点击操作按钮时,会调用广播接收器。我将通知ID传递到意图中。

在广播接收器中,我执行以下操作:

int notifId = intent.getIntExtra(Constants.NOTIF_ID, 0);
NotificationManager mNotificationManager = 
        (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);   

mNotificationManager.cancel(notifId);

这是我生成通知的方式。
int notifId = Util.random.nextInt(9000);
Intent mIntent = new Intent(con, NotificationBroadcastReceiver.class);
mIntent.putExtra(Constants.NOTIF_CODE, codeReason);
mIntent.putExtra(Constants.NOTIF_ID, notifId);

PendingIntent mPendingIntent = PendingIntent.getBroadcast(con, 0, mIntent , 0);

NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(con)
        .setSmallIcon(R.drawable.icon)
        .setContentTitle("test")
        .setPriority(Notification.PRIORITY_MAX)
        .setAutoCancel(true)
        .addAction(R.drawable.ic_launcher, "action", mPendingIntent);

// Creates an explicit intent for an Activity in your app
Intent resultIntent = new Intent(con, MainActivity.class);

PendingIntent resultPendingIntent = PendingIntent.getActivity(
        con, 0, resultIntent, PendingIntent.FLAG_UPDATE_CURRENT
);

mBuilder.setContentIntent(resultPendingIntent);
NotificationManager mNotificationManager =
        (NotificationManager) con.getSystemService(Context.NOTIFICATION_SERVICE);

mBuilder.setDefaults(
        Notification.DEFAULT_SOUND |
        Notification.DEFAULT_VIBRATE |
        Notification.DEFAULT_LIGHTS
);

// mId allows you to update the notification later on.
mNotificationManager.notify(notifId, mBuilder.build());

但是,即使我知道我正在使用日志语句来执行代码,通知仍不会被隐藏/解除。

为什么?


1
你能展示一下生成通知的代码吗? - Arslan Ashraf
代码已更新,notifId是随机生成的数字,之前已传入。 - Snake
你在哪里设置你的 notifId?因为我认为问题出在你的 notifId 上,取消通知所使用的 id 应该与生成通知时使用的 id 相同。 - Arslan Ashraf
但我只生成了一个!我在上面的代码中设置了断点,只运行一次。 - Snake
好的。我也在考虑同样的事情。 - Pankaj
显示剩余9条评论
2个回答

1
  1. 检查您的ID是否为零。
  2. 通过startForeground()检查通知是否未与其他服务绑定。

1
我找到了答案。我“认为”由于2个待处理意图具有相同的con和req代码,它们最终会修改它们的意图值。我通过使用2个不同的请求代码来确保唯一的Pending Intents来修复它。因此,我获得了相同的notifId。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接