简体   繁体   中英

Alarm is getting trigger even for past time

I am setting one repetitive alarm which will get trigger at 9 pm everyday. So I am setting alarm immediately after login. Here is my code.

AlarmManager alarmManager = (AlarmManager) applicationContext.getSystemService(Context.ALARM_SERVICE);
        Intent intent = new Intent(applicationContext, LogoutReceiver.class);
        PendingIntent pendingIntent = PendingIntent.getBroadcast(applicationContext, 100, intent, PendingIntent.FLAG_UPDATE_CURRENT);
        Calendar calendar = Calendar.getInstance();
        int hourOfTheDay = new LocaleTranslation().getIntValue(KeysConstant.AUTO_LOGOUT_TIMER_VALUE, Constants.AUTO_LOGOUT_HOUR_OF_DAY_VALUE);
        int minutes = new LocaleTranslation().getIntValue(KeysConstant.AUTO_LOGOUT_TIMER_MINUTE_VALUE, Constants.AUTO_LOGOUT_MINUTE_VALUE);
        int seconds = new LocaleTranslation().getIntValue(KeysConstant.AUTO_LOGOUT_TIMER_SECOND_VALUE, Constants.AUTO_LOGOUT_SECOND_VALUE);
        calendar.set(Calendar.HOUR_OF_DAY, hourOfTheDay );
        calendar.set(Calendar.MINUTE, minutes );
        calendar.set(Calendar.SECOND, seconds );
        Objects.requireNonNull(alarmManager).setRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), AlarmManager.INTERVAL_DAY, pendingIntent);
        LMPSharedPrefs.getInstance().write(SharedPrefsConstants.PREFS_LOGOUT_SCHEDULER, TIMER_STARTED);

It's working fine and app is getting logout exactly at 9.01 pm. But If i login again, then again it's getting logout. Means my alarm is getting trigger for past time also.

Is there best approach to avoid triggering alarm for past time.

Instead of this:

 calendar.set(Calendar.HOUR_OF_DAY, 21);
        calendar.set(Calendar.MINUTE, 1);
        calendar.set(Calendar.SECOND, 1);

Add this:

 calendar.set(Calendar.HOUR_OF_DAY, hourOfTheDay);
        calendar.set(Calendar.MINUTE, minutes);
        calendar.set(Calendar.SECOND, seconds);

You have initialized and declared your time values but you arent using them in your code.

Update:

   //region Enable Daily Notifications
        calendar = Calendar.getInstance();         
      calendar.setTimeInMillis(System.currentTimeMillis());
     calendar.set(Calendar.HOUR_OF_DAY, 10); //24 Hour.   
   Format - 10am alarm set.
    calendar.set(Calendar.MINUTE, 0);
    calendar.set(Calendar.SECOND, 0);
    // if notification time is before selected time, send. 
 notification the next day
    if (calendar.before(Calendar.getInstance())) {
        calendar.add(Calendar.DATE, 1);
    }
    if (manager != null) {
     //your alarmanager repeating code here
    }

The calendar.before is the main logic here to compare the timings. If before doesnt works than try with after.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM