Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to start/stop Runnable/Handler?

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();
}
like image 438
Zartch Avatar asked May 15 '12 12:05

Zartch


2 Answers

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.

like image 153
Dheeresh Singh Avatar answered Oct 07 '22 19:10

Dheeresh Singh


Every 5 Minutes? Do you even know what handler.postDelayed(this, 1000000); does? It starts the runnable every 16.7 minutes. It's not very difficult to find out how to convert minutes to milliseconds.

handler.removeCallbacks() and the boolean variable which you would check before postDelayed() were already mentioned.

like image 28
The incredible Jan Avatar answered Oct 07 '22 21:10

The incredible Jan