Android Timer Schedule

Below is a snippet of the code that I use in my project to plan a task

mTimer = new Timer(); mTimer.schedule(new TimerTask() { @Override public void run() { //Do Something } }, interval, interval); 

It works great. I get an event after the specified interval. But it cannot send any event if the date is set less than the current one from the settings.

Does anyone know why this behavior occurs?

+5
source share
2 answers

Timer does not work when you change the system clock, because it is based on System.currentTimeMillis() , which is not monotonous.

Timer not an Android class. This is the Java class that exists in the Android API to support existing non-Android libraries. It's almost always a bad idea to use Timer in your new Android code. Use the Handler for temporary events that occur throughout the life of your applications or services. Handler based on SystemClock.uptimeMillis() , which is monotonous. Use Alarm for time events that should occur even if your application is not running.

+4
source

Use this code .. this will help you.

 Timer t; seconds = 10; public void startTimer() { t = new Timer(); //Set the schedule function and rate t.scheduleAtFixedRate(new TimerTask() { @Override public void run() { runOnUiThread(new Runnable() { @Override public void run() { if (seconds == 0) { t.cancel(); seconds = 10; // DO SOMETHING HERE AFTER 10 SECONDS Toast.makeText(this,"Time up",Toast.LENGTH_SHORT).show(); } seconds -= 1; } }); } }, 0, 1000); } 
0
source

Source: https://habr.com/ru/post/1240053/


All Articles