Android 如何启动/停止 Runnable/Handler?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10601145/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to start/stop Runnable/Handler?
提问by Zartch
I'm trying to maintain databases synchronized between a Webservice and Android app. The code below is working, but I encounter some problems:
我正在尝试维护 Web 服务和 Android 应用程序之间同步的数据库。下面的代码正在运行,但我遇到了一些问题:
- Every time I go to main page of App a new infinite process is started.
- The process never ends
- 每次我进入 App 的主页时,都会启动一个新的无限进程。
- 过程永无止境
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.
谁能按照我的意愿解释如何开始和停止这个过程?
我希望此过程每 5 分钟运行一次,但仅在应用程序打开时运行一次。
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();
}
采纳答案by Dheeresh Singh
either use TimerTask:
要么使用 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/
http://thedevelopersinfo.wordpress.com/2009/10/18/scheduling-a-timer-task-to-run-repeatedly/http://android.okhelp.cz/timer-simple-timertask-java-android-例子/
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.
可以采用布尔值并在布尔值为真时运行循环并使其他线程休眠,而在离开应用程序时使布尔值为假。
回答by The incredible Jan
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.
每5分钟?你甚至知道是什么handler.postDelayed(this, 1000000);
吗?它每 16.7 分钟启动一次 runnable。找出如何将分钟转换为毫秒并不难。
handler.removeCallbacks()
and the boolean variable which you would check before postDelayed()
were already mentioned.
handler.removeCallbacks()
并且postDelayed()
已经提到了您之前要检查的布尔变量。
回答by thepoosh
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
}