Search code examples
androidalarmmanagerandroid-pendingintent

How to trigger an alarm only once in Android?


I set an alarm when the user lands on a certain activity, which is triggered after a certain time. How can I check if this alarm has already been triggered or not, so that it doesn't get set again if the user goes back to this activity ? I can only prevent the alarm getting set again if it's already scheduled but not triggered with this :

alarmIntent = PendingIntent.getBroadcast(context, requestCode, intent, PendingIntent.FLAG_NO_CREATE);
    if (alarmIntent != null) {
        // Alarm is already set
        return;
    }
    alarmIntent = PendingIntent.getBroadcast(context, requestCode, intent, 0);

But this does not work if it's already triggered, as the alarm will be deleted afterwards so alarmIntent will be null


Solution

  • You can make use of shared preferences to check whether it is set or not.

    if(!setFlag)
    {
        Intent myIntent = new Intent(FirstActivity.this, LogoutService.class);
        pendingIntent = PendingIntent.getService(FirstActivity.this, 0, myIntent, 0);
        AlarmManager alarmManager = (AlarmManager)getSystemService(ALARM_SERVICE);
        Calendar calendar = Calendar.getInstance();
        calendar.setTimeInMillis(System.currentTimeMillis());
        calendar.add(Calendar.MINUTE, 10); //Minutes
        alarmManager.set(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), pendingIntent);
    }