我使用此功能创建闹钟,如果已经创建闹钟,它将取消闹钟,如果没有,则创建闹钟
但它不起作用,alarmUp永远不会错误
如何检查警报是否存在?
public void alarm(int hour, int minutes)
{
Intent intent = new Intent(getApplicationContext(),AlarmActivity.class);
PendingIntent sender = PendingIntent.getActivity(getApplicationContext(), 0, intent, 0);
Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.HOUR, 24);
calendar.set(Calendar.HOUR_OF_DAY, hour);
calendar.set(Calendar.MINUTE, minutes);
calendar.set(Calendar.SECOND, 0);
boolean alarmUp = (PendingIntent.getActivity(getApplicationContext(), 0, intent, PendingIntent.FLAG_NO_CREATE) != null);
AlarmManager am = (AlarmManager) getApplicationContext().getSystemService(getApplicationContext().ALARM_SERVICE);
if(!alarmUp)
{
am.set(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), sender);
}
else
{
am.cancel(sender);
}
}
答案 0 :(得分:1)
你有正确的想法,但顺序错了。你需要这样做:
boolean alarmUp = (PendingIntent.getActivity(getApplicationContext(), 0, intent, PendingIntent.FLAG_NO_CREATE) != null);
在你这样做之前:
PendingIntent sender = PendingIntent.getActivity(getApplicationContext(), 0, intent, 0);
alarmUp
始终为真的原因是因为您之前刚刚创建了PendingIntent
!