How to start/stop Runnable/Handler?

Zartch picture Zartch · May 15, 2012 · Viewed 25.8k times · Source

I'm trying to maintain databases synchronized between a Webservice and Android app. The code below is working, but I encounter some problems:

  • Every time I go to main page of App a new infinite process is started.
  • The process never ends

Can anyone explain how to start and stop this process as I wish?
I want this process to run every 5 minutes, but only once and when the app is open.

public void onCreate(Bundle savedInstanceState) {   
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

    final Handler handler = new Handler();
    final Runnable r = new Runnable() {
        public void run() {
            // DO WORK
            Mantenimiento();
            // Call function.
            handler.postDelayed(this, 1000000);
        }
    };
    r.run();
}

Answer

Dheeresh Singh picture Dheeresh Singh · May 15, 2012

either use TimerTask:

http://thedevelopersinfo.wordpress.com/2009/10/18/scheduling-a-timer-task-to-run-repeatedly/ http://android.okhelp.cz/timer-simple-timertask-java-android-example/

or

can take Boolean and run the loop while boolean is true and make sleep to other thread and while leaving app make Boolean false.