如何取消特定日期的重复通知

时间:2016-05-30 15:44:53

标签: android android-intent alarmmanager android-notifications repeatingalarm

好吧,我已经尝试过寻找上述问题的答案,但到目前为止,我的努力一直是徒劳的。 我已经在alarmmanager类的帮助下创建了一个警报器,它会定期启动通知(可能大约5天)。 下面是按钮的onClick()内部发生警报的实现代码。

AlarmManager alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);

    Intent notificationIntent = new Intent("android.media.action.DISPLAY_NOTIFICATION");
    notificationIntent.addCategory("android.intent.category.DEFAULT");

    PendingIntent broadcast = PendingIntent.getBroadcast(this, 100, notificationIntent, PendingIntent.FLAG_UPDATE_CURRENT);

    Calendar cal = Calendar.getInstance();
    if(fromDateEtxt.getText().toString().length()>0) {
        cal.add(Calendar.HOUR_OF_DAY, 10);
        alarmManager.setRepeating(AlarmManager.RTC_WAKEUP,cal.getTimeInMillis(), 5 * 24 * 60 * 60 * 1000, broadcast);

    }

广播接收器的代码。

public class AlarmReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
    Intent notificationIntent = new Intent(context, NotificationActivity.class);

    TaskStackBuilder stackBuilder = TaskStackBuilder.create(context);
    stackBuilder.addParentStack(NotificationActivity.class);
    stackBuilder.addNextIntent(notificationIntent);

    PendingIntent pendingIntent = stackBuilder.getPendingIntent(0, PendingIntent.FLAG_UPDATE_CURRENT);

    NotificationCompat.Builder builder = new NotificationCompat.Builder(context);

    Notification notification = builder.setContentTitle("Demo App Notification")
            .setContentText("New Notification From Demo App..")
            .setTicker("New Message Alert!")
            .setSmallIcon(R.mipmap.ic_launcher)
            .setContentIntent(pendingIntent).build();

    NotificationManager notificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
    notificationManager.notify(0, notification);
}}

除了启动警报之外,onClick()方法也会更改活动。现在我面临的问题是我真的不知道如何停止重复警报。我想在特定日期停止闹钟。其次,我很困惑是否使用alarm.cancel取消警报或使用另一个警报取消之前的警报,如here所示。除此之外,我想知道警报是否可以从其他活动中取消,或者这一点似乎是不必要的,并且可以预先设定日期限制?

1 个答案:

答案 0 :(得分:0)

您需要使用与cancel使用的AlarmManager相同的PendingIntentsetRepeating上的Intent intent = new Intent(this, AlarmReceive.class); PendingIntent sender = PendingIntent.getBroadcast(this, 0, intent, 0); AlarmManager alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE); alarmManager.cancel(sender);

示例代码 -

AlarmManager

至于您在特定日期取消它的要求,您可以使用PendingIntent设置另一个闹铃。将BroadcastReceiver(可能带有@media (max-width: 992px) { body { width: 100vw; overflow-x: hidden; } nav { -webkit-transform: translateX(100%); -ms-transform: translateX(100%); transform: translateX(100%); opacity: 1; transition: -webkit-transform 300ms ease-in-out, opacity 300ms ease-in-out; transition: transform 300ms ease-in-out, opacity 300ms ease-in-out; text-align: center; position: absolute; top: 144px; } )传递给它,取消类似于示例代码的重复警报。