Scheduling recurring tasks in the service

I need to repeat a task every 1 hour in the background (I am sending some information to my server).

  • I tried to use the service with a post post handler calling it myself.

       handler = new Handler(); 
    runable = new Runnable() { 
    
        @Override 
        public void run() { 
            try{
    
            //sending info to server....
    
            }
            catch (Exception e) {
                // TODO: handle exception
            }
            finally{
                //also call the same runnable 
                handler.postDelayed(this, 1000*60*60); 
            }
        } 
    }; 
    handler.postDelayed(runable, 1000*60*60); 
    
          

It didn't work, in a short 1 minute it worked fine, when I changed it for 5 minutes it worked for about 5 repetitions and then the time got wrong and after an hour the service was shut down.

  1. I want to try and use the AlarmManager, but in the documentation it says, "Since Android 4.4 (API level 19), all recurring alarms are inaccurate", does anyone know how inaccurate it is? is it seconds ?, minutes? can i rely on this to work on time?

  2. Does anyone have any other suggestions for repeating tasks in a service?

thank

+3


source to share


1 answer


You can use this code to call oncreate method again or any other thing



public void callAsynchronousTask() {
    final Handler handler = new Handler();
    Timer timer = new Timer();
    TimerTask doAsynchronousTask = new TimerTask() {
        @Override
        public void run() {
            handler.post(new Runnable() {
                public void run() {
                    try {
                        onCreate();

                    } catch (Exception e) {

                    }
                }
            });
        }
    };
    timer.schedule(doAsynchronousTask, 0, 1000); //execute in every 1000 ms
}

      

+2


source







All Articles