gpt4 book ai didi

android - 闹钟管理器取消不工作 Android

转载 作者:太空狗 更新时间:2023-10-29 16:11:37 46 4
gpt4 key购买 nike

我已经为约会提醒创建了一个闹钟管理器,它运行良好。但是当我想取消闹钟时,它仍然会准时响起。警报取消不起作用。下面是设置和取消闹钟的代码。谢谢

设置报警管理器的代码

AlarmManager alarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);    
Intent notificationIntent = new Intent("android.media.action.APPOINTMENT_REMINDER_NOTIFICATION");
notificationIntent.putExtra("APPOINTMENT_TIME", date);
notificationIntent.putExtra("APPOINTMENT_ID", appointment_id);
notificationIntent.addCategory("android.intent.category.DEFAULT");
PendingIntent broadcast = PendingIntent.getBroadcast(context, 100, notificationIntent, PendingIntent.FLAG_UPDATE_CURRENT);
Calendar cal = Calendar.getInstance();
cal.add(Calendar.SECOND, time_remaining);
alarmManager.setExact(AlarmManager.RTC_WAKEUP, cal.getTimeInMillis(), broadcast);

取消闹钟

Intent intent = new Intent("android.media.action.APPOINTMENT_REMINDER_NOTIFICATION");
//PendingIntent.getBroadcast(context, 100, intent, PendingIntent.FLAG_UPDATE_CURRENT).cancel();
//Intent intent = new Intent(context, AlarmReceiver.class);
//alarmManager.cancel(PendingIntent.getService(context, 100, intent, 0));
PendingIntent pIntent = PendingIntent.getBroadcast(context, 100, intent, PendingIntent.FLAG_UPDATE_CURRENT);
AlarmManager alarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
alarmManager.cancel(pIntent);
pIntent.cancel();

最佳答案

使用 alammanager 时首先要记住的是 -
您必须在创建和取消警报时使用相同的上下文

This includes their action, data, type, class, and categories are the same. This does not compare any extra data included in the intents.

在这种情况下,您可以使用 getApplicationContext() 使事情变得简单。所以下面的代码应该可以工作 -

设置闹钟-

AlarmManager alarmManager = (AlarmManager) getApplicationContext().getSystemService(Context.ALARM_SERVICE);
Intent notificationIntent = new Intent("android.media.action.APPOINTMENT_REMINDER_NOTIFICATION");
notificationIntent.putExtra("APPOINTMENT_TIME", date);
notificationIntent.putExtra("APPOINTMENT_ID", appointment_id);
notificationIntent.addCategory("android.intent.category.DEFAULT");
PendingIntent broadcast = PendingIntent.getBroadcast(getApplicationContext(), 100, notificationIntent, PendingIntent.FLAG_UPDATE_CURRENT);

Calendar cal = Calendar.getInstance();
cal.add(Calendar.SECOND, time_remaining);
alarmManager.setExact(AlarmManager.RTC_WAKEUP, cal.getTimeInMillis(), broadcast);

取消闹钟 -

PendingIntent pIntent = PendingIntent.getBroadcast(getApplicationContext(), 100, intent, PendingIntent.FLAG_UPDATE_CURRENT);
AlarmManager alarmManager = (AlarmManager) getApplicationContext().getSystemService(Context.ALARM_SERVICE);
alarmManager.cancel(pIntent);

关于android - 闹钟管理器取消不工作 Android,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46078206/

46 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com