How to start / stop Runnable / Handler?

I am trying to maintain databases synchronized between a Webservice and an Android application. The code below works, but I am facing some problems:

  • Every time I go to the main page of the application, a new endless process starts.
  • The process never ends.

Can someone explain how to start and stop this process as I want?
I want this process to run every 5 minutes, but only once and when the application 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(); } 
+6
source share
3 answers

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 a Boolean and run the loop, while boolean is true and makes sleep for another thread, and the application leaves a boolean false.

+3
source

will use this code:

 public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); final Handler handler = new Handler(); final Thread r = new Thread() { public void run() { // DO WORK Mantenimiento(); // Call function. handler.postDelayed(this, 1000000); } }; r.start(); // THIS IS DIFFERENT } 
0
source

Every 5 minutes? You even know what handler.postDelayed(this, 1000000); does handler.postDelayed(this, 1000000); ? It runs runnable every 16.7 minutes. It’s not very difficult to learn how to convert minutes to milliseconds.

handler.removeCallbacks() and the boolean variable that you would check before postDelayed() has already been mentioned.

0
source

Source: https://habr.com/ru/post/915793/


All Articles