Reputation: 3759
I use this function to create alarm, if alarm already created, it will cancel the alarm, if not, create alarm
But it is not work, the alarmUp is never false
How to check if the alarm exists?
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);
}
}
Upvotes: 2
Views: 68
Reputation: 95568
You have the right idea, but the order is wrong. You need to do this:
boolean alarmUp = (PendingIntent.getActivity(getApplicationContext(), 0, intent, PendingIntent.FLAG_NO_CREATE) != null);
before you do this:
PendingIntent sender = PendingIntent.getActivity(getApplicationContext(), 0, intent, 0);
The reason that alarmUp
is always true is because you have just previously created the PendingIntent
yourself!
Upvotes: 2