In mobile development often there is a need to run a method couple of times, or on a fixed schedule , like playing an animation or fetching data every some seconds, according to the Android's best practices, it is recommended to use the Handler object, the following snippet can come in handy when you have a lot of reoccurring tasks
import android.os.Bundle;
public interface IReoccurringTask {
void run(Bundle bundle);
}
import android.os.Bundle;
import android.os.Handler;
public class ReoccurringTaskScheduler {
private Handler handler = new Handler();
private Runnable runnable;
private IReoccurringTask reoccurringTask;
private ReoccurringTaskScheduler(){}
public ReoccurringTaskScheduler(IReoccurringTask reoccurringTask) {
this.reoccurringTask=reoccurringTask;
}
public void Schedule(long initDelay, final long interval) {
runnable = new Runnable() {
@Override
public void run() {
try {
reoccurringTask.run(null);
} catch (Exception e) {
e.printStackTrace();
} finally {
handler.postDelayed(this, interval);
}
}
};
handler.postDelayed(runnable, initDelay);
}
public void Schedule(final Bundle bundle, long initDelay, final long interval) {
runnable = new Runnable() {
@Override
public void run() {
try {
reoccurringTask.run(bundle);
} catch (Exception e) {
e.printStackTrace();
} finally {
handler.postDelayed(this, interval);
}
}
};
handler.postDelayed(runnable, initDelay);
}
public void cancel() {
if (runnable != null)
handler.removeCallbacks(runnable);
}
}
and you can define your custom logic like this
private class ReoccurringLogicClass implements IReoccurringTask{
@Override
public void run(Bundle bundle) {
//reoccurring logic
}
}
and then use it like this
ReoccurringTaskScheduler rTask=
new ReoccurringTaskScheduler(new ReoccurringLogicClass()).Schedule(1000,2000);
and cancel it like this
rTask.cancel();
Happy coding :)