Android - 在计时器内重复运行一个线程
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/11639251/
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
Android - Run a thread repeatingly within a timer
提问by sarkolata
First of all, I could not even chose the method to use, i'm reading for hours now and someone says use 'Handlers', someone says use 'Timer'. Here's what I try to achieve:
首先,我什至无法选择使用的方法,我现在读了几个小时,有人说使用“处理程序”,有人说使用“计时器”。这是我试图实现的目标:
At preferences, theres a setting(checkbox) which to enable / disable the repeating job. As that checkbox is checked, the timer should start to work and the thread should be executed every x seconds. As checkbox is unchecked, timer should stop.
在首选项中,有一个设置(复选框)可以启用/禁用重复作业。当该复选框被选中时,计时器应该开始工作并且线程应该每 x 秒执行一次。由于未选中复选框,计时器应停止。
Here's my code:
这是我的代码:
Checking whether if checkbox is checked or not, if checked 'refreshAllServers' void will be executed which does the job with timer.
检查复选框是否被选中,如果选中'refreshAllServers' void 将被执行,它使用计时器完成工作。
boolean CheckboxPreference = prefs.getBoolean("checkboxPref", true);
if(CheckboxPreference == true) {
Main main = new Main();
main.refreshAllServers("start");
} else {
Main main = new Main();
main.refreshAllServers("stop");
}
The refreshAllServers void that does the timer job:
执行计时器工作的 refreshAllServers void:
public void refreshAllServers(String start) {
if(start == "start") {
// Start the timer which will repeatingly execute the thread
} else {
// stop the timer
}
And here's how I execute my thread: (Works well without timer)
这是我执行线程的方式:(无需计时器即可正常工作)
Thread myThread = new MyThread(-5);
myThread.start();
What I tried?
我尝试了什么?
I tried any example I could see from Google (handlers, timer) none of them worked, I managed to start the timer once but stoping it did not work. The simpliest & understandable code I saw in my research was this:
我尝试了可以从 Google 看到的任何示例(处理程序、计时器),它们都不起作用,我设法启动了一次计时器,但停止它不起作用。我在研究中看到的最简单易懂的代码是这样的:
new java.util.Timer().schedule(
new java.util.TimerTask() {
@Override
public void run() {
// your code here
}
},
5000
);
回答by Tuna Karakasoglu
Just simply use below snippet
只需简单地使用下面的代码片段
private final Handler handler = new Handler();
private Runnable runnable = new Runnable() {
public void run() {
//
// Do the stuff
//
handler.postDelayed(this, 1000);
}
};
runnable.run();
To stop it use
要停止它使用
handler.removeCallbacks(runnable);
Should do the trick.
应该做的伎俩。
回答by sarkolata
Thanks to everyone, I fixed this issue with using Timer.
感谢大家,我使用 Timer 解决了这个问题。
timer = new Timer();
timer.scheduleAtFixedRate(
new java.util.TimerTask() {
@Override
public void run() {
for (int i = 0; i < server_amount; i++) {
servers[i] = "Updating...";
handler.sendEmptyMessage(0);
new MyThread(i).start();
}
}
},
2000, 5000);
回答by Code Droid
Use a CountDownTimer. The way it works is it will call a method on each tick of the timer, and another method when the timer ends. At which point you can restart if needed. Also I think you should probably be kicking off AsyncTask rather than threads. Please don't try to manage your own threads in Android. Try as below. Its runs like a clock.
使用倒计时计时器。它的工作方式是它会在计时器的每个滴答声中调用一个方法,并在计时器结束时调用另一个方法。此时,您可以根据需要重新启动。此外,我认为您可能应该启动 AsyncTask 而不是线程。请不要尝试在 Android 中管理自己的线程。尝试如下。它像时钟一样运行。
CountDownTimer myCountdownTimer = new CountDownTimer(30000, 1000) {
public void onTick(long millisUntilFinished) {
mTextField.setText("seconds remaining: " + millisUntilFinished / 1000);
// Kick off your AsyncTask here.
}
public void onFinish() {
mTextField.setText("done!");
// the 30 seconds is up now so do make any checks you need here.
}
}.start();
回答by Maxim
I would think to use AlarmManager http://developer.android.com/reference/android/app/AlarmManager.html
我想使用 AlarmManager http://developer.android.com/reference/android/app/AlarmManager.html
If checkbox is on call method where
如果复选框在调用方法中
AlarmManager alarmManager = (AlarmManager)SecureDocApplication.getContext()
.getSystemService(Context.ALARM_SERVICE);
PendingIntent myService = PendingIntent.getService(context, 0,
new Intent(context, MyService.class), 0);
long triggerAtTime = 1000;
alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, triggerAtTime, 5000 /* 5 sec*/,
myService);
If checkbox is off cancel alarm manager
如果复选框关闭取消警报管理器
alarmManager.cancel(myService);
回答by cloudsurfin
"[ScheduledThreadPoolExecutor] class is preferable to Timer when multiple worker threads are needed, or when the additional flexibility or capabilities of ThreadPoolExecutor (which this class extends) are required."
“[ScheduledThreadPoolExecutor] 类在需要多个工作线程时比 Timer 更可取,或者需要 ThreadPoolExecutor(该类扩展)的额外灵活性或功能时。”
per...
每...
https://docs.oracle.com/javase/7/docs/api/java/util/concurrent/ScheduledThreadPoolExecutor.html
https://docs.oracle.com/javase/7/docs/api/java/util/concurrent/ScheduledThreadPoolExecutor.html
It's not much more than the handler, but has the option of running exactly every so often (vice a delay after each computation completion).
它不比处理程序多多少,但可以选择每隔一段时间运行一次(每次计算完成后都有一个延迟)。
import java.util.concurrent.ScheduledThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
...
final int THREAD_POOL_SIZE = 10;
final int START_DELAY = 0;
final int TIME_PERIOD = 5;
final TimeUnit TIME_UNIT = TimeUnit.SECONDS;
ScheduledThreadPoolExecutor pool;
Runnable myPeriodicThread = new Runnable() {
@Override
public void run() {
refreshAllServers();
}
};
public void startTimer(){
pool.scheduleAtFixedRate(myPeriodicThread,
START_DELAY,
TIME_PERIOD,
TIME_UNIT);
}
public void stopTimer(){
pool.shutdownNow();
}