I found a tutorial for scheduled notifications using Timer and TimerTask and I'm trying to implement it in my project to send a notification every day at a certain time. However, it is only firing the notification on the current day if the specified time hasn't passed and doesn't come up the next day.
These are the timer methods being used in my Notification Service class:
public void startTimer() {
//set a new Timer
timer = new Timer();
//initialize the TimerTask's job
initializeTimerTask();
//schedule the timer
Calendar today = Calendar.getInstance();
Calendar tomorrow = Calendar.getInstance();
tomorrow.set(Calendar.HOUR_OF_DAY, 17);
tomorrow.set(Calendar.MINUTE, 2);
tomorrow.set(Calendar.SECOND, 0);
if(today.compareTo(tomorrow) > 0)
tomorrow.add(DATE, 1);
long initialDelay = tomorrow.getTimeInMillis() - today.getTimeInMillis();
timer.scheduleAtFixedRate(timerTask, initialDelay, 1000*60*60*24);
}
public void initializeTimerTask() {
timerTask = new TimerTask() {
public void run() {
//use a handler to run a toast that shows the current timestamp
handler.post(new Runnable() {
public void run() {
sendNotification();
}
});
}
};
}
I'm calling the Notification Service class in the onStop() method in my MainActivity.class using:
startService(new Intent(this, NotificationService.class));
I'm not sure if this is the correct place to call it and I'm not able to debug and see if the Timer is working after the app is closed.