Search code examples
androidandroid-intentalarmmanagerandroid-pendingintent

To detect existing alarm


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

Solution

  • 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!