Search code examples
javaandroidalarmmanager

Having problems with "snoozing" alarm


Does anyone know how to do snooze function and where I am going wrong?

My default snooze time is 5 minutes. It worked fine until restart the
application and then does not work again. If I clear the cache and data its works again.

 public void onClick(View view) {

    SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(getBaseContext());
    int iSnoozeLeft = settings.getInt(PuzzleAlarm.SNOOZE_LEFT, 1);
    if (iSnoozeLeft != 0) {
      Intent activate = new Intent(AlarmNotification.this, AlarmReceiver.class);
      PendingIntent alarmIntent = PendingIntent.getBroadcast(AlarmNotification.this, 0, activate, 0);
      AlarmManager alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);

      int iMinutes = Preferences.getSnooze(settings, AlarmNotification.this);
      Calendar calendar = Calendar.getInstance();
      calendar.roll(Calendar.MINUTE, iMinutes);
      alarmManager.set(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), alarmIntent);

      SharedPreferences.Editor editor = settings.edit();
      editor.putInt(PuzzleAlarm.SNOOZE_LEFT, iSnoozeLeft - 1); // disabling
      // Commit the edits!
      editor.commit();
    }`

Solution

  • PendingIntent.getBroadcast(AlarmNotification.this, 0, activate, 0);

    Make sure you aren't using "0" for your other alarm ID. In other case your "snooze" code will overwrite that previous alarm.