Fire notification at every 24 hours and at exact time of 8 AM

后端 未结 4 1012
再見小時候
再見小時候 2020-12-08 02:39

I am using AlarmManager() to fire notification and repeat it at every 24 hours.

My code is on onCreate() in Splash Activity which fires fi

4条回答
  •  爱一瞬间的悲伤
    2020-12-08 03:44

    Do as chintan suggested. To get a clear picture, the exact solution might look something similar to the below:

    Intent myIntent = new Intent(Splash.this, AlarmReceiver.class);
    PendingIntent pendingIntent = PendingIntent.getBroadcast(Splash.this, 0, myIntent, 0);
    AlarmManager alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);
    
    Calendar firingCal= Calendar.getInstance();
    Calendar currentCal = Calendar.getInstance();
    
    firingCal.set(Calendar.HOUR, 8); // At the hour you wanna fire
    firingCal.set(Calendar.MINUTE, 0); // Particular minute
    firingCal.set(Calendar.SECOND, 0); // particular second
    
    long intendedTime = firingCal.getTimeInMillis();
    long currentTime = currentCal.getTimeInMillis();
    
    if(intendedTime >= currentTime){ 
       // you can add buffer time too here to ignore some small differences in milliseconds
       // set from today
       alarmManager.setRepeating(AlarmManager.RTC, intendedTime, AlarmManager.INTERVAL_DAY, pendingIntent);
    } else{
       // set from next day
       // you might consider using calendar.add() for adding one day to the current day
       firingCal.add(Calendar.DAY_OF_MONTH, 1);
       intendedTime = firingCal.getTimeInMillis();
    
       alarmManager.setRepeating(AlarmManager.RTC, intendedTime, AlarmManager.INTERVAL_DAY, pendingIntent);
    }
    

提交回复
热议问题