0

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.

AuthenticReplica
  • 870
  • 15
  • 39
  • better use for this WorkManager https://developer.android.com/topic/libraries/architecture/workmanager/basics – Olena Y Sep 26 '18 at 08:16
  • use job scheduler when in background and in foreground don't use Timer, use handelr instead – hemen Sep 26 '18 at 08:29

2 Answers2

0

I recommend you look into AlarmManager to achieve this. You don't have to reinvent the wheel for this one. It allows you to wake the app by setting the time intervals.

alarmMgr.setRepeating(
        AlarmManager.RTC_WAKEUP,
        calendar.timeInMillis,
        1000 * 60 * 20,
        alarmIntent
)

Also, keep in mind that startService will no longer work on Android 8 phones come November 1st. I recommend using WorkManager instead.

Josh
  • 386
  • 5
  • 14
0

I have used this code in my project and it worked smoothly :

   public void setAlarm() {

    Intent serviceIntent = new Intent(this, CheckRecentRun.class);
    PendingIntent pi = PendingIntent.getService(this, 131313, serviceIntent,
                                                PendingIntent.FLAG_CANCEL_CURRENT);

    AlarmManager am = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
    am.set(AlarmManager.RTC_WAKEUP, System.currentTimeMillis() + delay, pi);
    Log.v(TAG, "Alarm set");        
}
public void sendNotification() {

    Intent mainIntent = new Intent(this, MainActivity.class);
    @SuppressWarnings("deprecation")
    Notification noti = new Notification.Builder(this)
        .setAutoCancel(true)
        .setContentIntent(PendingIntent.getActivity(this, 131314, mainIntent,
                          PendingIntent.FLAG_UPDATE_CURRENT))
        .setContentTitle("We Miss You!")
        .setContentText("Please play our game again soon.")
        .setDefaults(Notification.DEFAULT_ALL)
        .setSmallIcon(R.drawable.ic_launcher)
        .setTicker("We Miss You! Please come back and play our game again soon.")
        .setWhen(System.currentTimeMillis())
        .getNotification();

    NotificationManager notificationManager
        = (NotificationManager) this.getSystemService(Context.NOTIFICATION_SERVICE);
    notificationManager.notify(131315, noti);

    Log.v(TAG, "Notification sent");        
}

where I did took reference for my project this link :

https://stackoverflow.com/a/22710380/7319704

Abhinav Gupta
  • 2,225
  • 1
  • 14
  • 30
  • The MainActivity.PREFS is not recognised, what happens if I don't check if notifications are enabled? And where should I call this class? – AuthenticReplica Sep 26 '18 at 08:31