简体   繁体   中英

Notification popping up just as I set notification : android studio alarm manager

Weird situation I'm in as in my application, just after I set time and pass the hour and minute values as arguments in the method setReminder, just after few seconds a notification pops up. Rather than at the given time.

public void setReminder(Context context, long reminderHour, long reminderMinute){

        Intent intent =new Intent(context,NotificationBroadcast.class);
        Log.d("Reminder Time set :", reminderHour+":"+reminderMinute);
        PendingIntent pendingIntent = PendingIntent.getBroadcast(context,0, intent,0);
        Log.d("setReminder", "WORKING");
        AlarmManager alarmManager = (AlarmManager) context.getSystemService(context.ALARM_SERVICE);
        long timeAtButtonClick = System.currentTimeMillis();
        Calendar calendar = Calendar.getInstance();
        calendar.setTimeInMillis(System.currentTimeMillis());
        Calendar datetimetoalarm = Calendar.getInstance(Locale.getDefault());
        datetimetoalarm.setTimeInMillis(System.currentTimeMillis());
        StudyGoal studyGoal= StudyGoal.getStudyGoalObject();
        datetimetoalarm.set(Calendar.HOUR_OF_DAY, (int) reminderHour);
        datetimetoalarm.set(Calendar.MINUTE, (int) reminderMinute);
        datetimetoalarm.set(Calendar.SECOND, 0);
        datetimetoalarm.set(Calendar.MILLISECOND, 0);
        alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, datetimetoalarm.getTimeInMillis(), (1000 * 60 * 60 * 24), pendingIntent);
        Log.d("SetReminder:", "WORKING");
        Log.d("Reminder Time set :", reminderHour+":"+reminderMinute);
}

Turns out, while using alarm manager, if the set time is lesser than the current time, the reminder will be triggered immediately. To solve that, you will have to add a small if statement like follows... It will simply add a day to your set time which will push the notification for the next day. if(reminderTime.before(Calendar.getInstance())){ reminderTime.add(Calendar.DATE,1); }

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