I have developed an android application which fetches data from online db server like parse.com. I want to schedule a process, that fetches data and updates view every 10 or 20 secs, to execute again and again with fixed delay even if the application is not turned on. I have seen other answers but confused that to use alarm manager or scheduleexecutor. and if alarm manager then please can somebody put code for alarm manager that is optimally designed such a way that battery is not drained out or so otherwise scheduleexecutor should be used then please post code implementing it. I tried but could not achieve even a simple scheduling. Thank you in advance!
You should use a Service
that contains a Handler
to set the delay. The basics of how to set up a Service
are in the android docs. Based on what you're describing, what I would do is control the Service
from within onStartCommand
private static final int LOOP_TIME = 1000 * 20; //20 seconds
private Handler loopHanlder = new Handler();
private Runnable taskToRepeat = new Runnable(){
@Override
public void run(){
//whatever you want to loop
}
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
handler.postDelayed(taskToRepeat, LOOP_TIME);
}
Then all you have to do is start or stop your Service
with an intent from within your Activity
. I'm assuming you want to have the service run constantly once started. If you don't you can just add a flag to the Intent
each time you broadcast and control your service that way, switching actions. But this basic set up should get you going.