设置 NotificationCompat.Builder java android 的 ID

Setting the ID of NotificationCompat.Builder java android

我目前正在使用以下代码创建警报:

public NotificationCompat.Builder getChannelNotification(AbstractEvent event) {
    Intent activityIntent = new Intent(context, MainActivity.class);
    Intent broadcastIntent = new Intent(context, NotificationReceiver.class);
    broadcastIntent.putExtra("id",event.getId());

    PendingIntent actionIntent = PendingIntent.getBroadcast(context, 0, broadcastIntent, PendingIntent.FLAG_UPDATE_CURRENT);

    return new NotificationCompat.Builder(getApplicationContext(), channelID)
            .setContentTitle(event.getTitle())
            .setContentText("event begins in: " + event.getStartTime)
            .setSmallIcon(R.drawable.android)
            .setShortcutId("1")
            .addAction(R.mipmap.ic_launcher, "Dismiss", actionIntent)
}

这很好地创建了警报,但我试图在按下 "Dismiss" 按钮时关闭警报。

我正尝试在另一个 class 中使用:

NotificationManager manager = context.getSystemService(NotificationManager.class);
manager.cancel(id);

这样就好了,但是我好像不能设置我刚做的闹钟的ID。

如何set/access我刚刚发出的闹钟的ID?

您必须手动创建 id 并将其与通知一起设置并将其存储在 sharedPreferences

NOTIFICATION_ID = notificationPreferences.getInt("notifnumber",0);

一旦你通知,你增加值并存储它

manager.notify(NOTIFICATION_ID, notification);
editor.putInt("notifnumber", NOTIFICATION_ID + 1);
editor.commit();