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

后端 未结 4 1019
再見小時候
再見小時候 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条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-12-08 03:28

    Appu answer helped me a lot but if you want a fixed version of it a bit more readable and shorted look at this:

    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_OF_DAY, 8); // At the hour you wanna fire
    firingCal.set(Calendar.MINUTE, 0); // Particular minute
    firingCal.set(Calendar.SECOND, 0); // particular second
    
    if(firingCal.compareTo(currentCal) < 0) { 
       firingCal.add(Calendar.DAY_OF_MONTH, 1);
    } 
    Long intendedTime = firingCal.getTimeInMillis();
    alarmManager.setRepeating(AlarmManager.RTC, intendedTime , AlarmManager.INTERVAL_DAY, pendingIntent);
    

提交回复
热议问题