There is a task to show an alert at a specific date and time that the user specifies. When trying to do via TimerTask does not come out to show the alert at the right time.

Timer timer = new Timer(); TimerTask task = new TimerTask() { @Override public void run() { thatDay.set(Calendar.DAY_OF_MONTH, Integer.parseInt(date.substring(0, 2))); thatDay.set(Calendar.MONTH, Integer.parseInt(date.substring(3, 5))); thatDay.set(Calendar.YEAR, Integer.parseInt(date.substring(6,10))); thatDay.set(Calendar.HOUR_OF_DAY, Integer.parseInt(time.substring(0, 2))); thatDay.set(Calendar.MINUTE, Integer.parseInt(time.substring(3, 5))); Intent notificationIntent = new Intent(context, ToDoActivity.class); notificationIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); PendingIntent contentIntent = PendingIntent.getActivity(context, 0, notificationIntent, PendingIntent.FLAG_CANCEL_CURRENT); Notification.Builder builder = new Notification.Builder(context); builder.setContentIntent(contentIntent) .setSmallIcon(R.drawable.ic_launcher) .setWhen(System.currentTimeMillis()) .setContentTitle("Напоминание MyNotes") .setContentText(description); Notification notification = builder.build(); notification.defaults = Notification.DEFAULT_SOUND; NotificationManager notificationManager = (NotificationManager) context .getSystemService(Context.NOTIFICATION_SERVICE); notificationManager.notify(Integer.parseInt(id), notification); } }; timer.schedule(task, thatDay.getTime()); 

If in timer.schedule transfer just a delay in milliseconds, it works But when you try to specify the difference between the dates in milliseconds

 thatDay.getTimeInMillisec() - System.currentTimeInMillisec() 

I get an error, delay < 0

If you specify thatDay.getTime() second parameter, the alert is executed immediately, but not at the specified time ..

PS Time and date lines are set ("12/26/2015", "15:00")

  • In your current code, all the parsing of the string and the initialization of the date is done inside TimerTask.run , i.e. the code that initializes the date will be executed only when the timer is activated and the task is executed. - zRrr
  • Thank you, made a date parsing method above, but now the alert does not appear at all - Vladyslav Tyshchenko
  • @zRrr Please post your commentq as an answer. - Nicolas Chabanovsky

0