Search code examples
javaandroidandroid-studiotimertask

Android java:Execute a function repeatedly with a delay dynamically set based on some conditions


I am basically trying to fetch latitude and longitude from a different class which is executed every 30 seconds initially.The fetching should be made faster when the latitude, longitude values reaches near my target latitude, longitude at a rate of say 5 seconds, and if the distance to target is beyond say 100 km range, the fetching of values should be say at a rate of 5 minutes. I tried with timer task but am unable to reschedule within the timer task.

If not through timer task, is there any other way to achieve the same? My code will look something similar to the below mentioned

timer = new Timer();
myTimerTask = new MyTimerTask();
timer.schedule(myTimerTask, 0, 30000);//default delay 30 seconds
class MyTimerTask extends TimerTask {
@Override
public void run() {
latitude = gps.getlatitude();
longitude = gps.getlongitude();
int distance =getdistance(latitude,longitude,target_latitude,target_longitude);
if(distance <50)
//execute timer task with 5 second delay
else if (distance >100)
//execute timer task with 5 minutes delay
}

Solution

  • Use Handler class. It has utility methods such as postDelayed(Runnable r, long delayMillis) andpostAtTime(Runnable r, long uptimeMillis)`.

    Once you execute a callback, check how far are you from your target lat and long and accordingly vary delayMillis. Handler is the closest to absolute reliability you get. If you need more robust behaviour then AlarmManager is an option (but might be an overkill)