首页 > 解决方案 > java android设置NotificationCompat.Builder的ID

问题描述

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

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

这很好地创建了警报,但是当我按下“解除”按钮时,我试图解除警报。

我正在尝试使用以下方法在另一个类中执行此操作:

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

这很好,但是我似乎无法设置刚刚发出的警报的 ID。

如何设置/访问我刚刚发出的警报的 ID?

标签: androidalarm

解决方案


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

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

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

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

推荐阅读