Reputation: 136
I'm trying to maintain databases synchronized between a Webservice and Android app. The code below is working, but I encounter some problems:
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();
}
Upvotes: 7
Views: 27457
Reputation: 905
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.
Upvotes: 2
Reputation: 12587
would 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
}
Upvotes: 0
Reputation: 15701
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.
Upvotes: 4