首先,我连选择使用,我读了几个小时,现在,有人说用处理程序,有人说用定时器的方法。这是我尽量做到:
在preferences,那里有一个设置(复选框)要启用/禁用重复作业。作为该复选框被选中,定时器应该开始工作,该线程应执行每x秒。由于复选框被选中,定时器应停止。
下面是我的code:
检查是否如果复选框被选中与否,如果选中refreshAllServers无效,将执行由它来完成工作,具有定时器。
布尔复选框preference = prefs.getBoolean(复选框preF,真正的);
如果(复选框preference ==真){
主力主攻=新的Main();
main.refreshAllServers(开始);
} 其他 {
主力主攻=新的Main();
main.refreshAllServers(停止);
}
该refreshAllServers无效,做计时器作业:
公共无效refreshAllServers(字符串开始){
如果(开始==启动){
//开始将repeatingly执行线程计时器
} 其他 {
//停止计时器
}
这就是我如何执行我的主题:(工作良好,没有定时器)
发myThread =新MyThread(-5);
myThread.start();
我试过吗?
我尝试过的例子,我可以看到谷歌(处理程序,计时器)没有人工作,我设法开始计时一次,但回采没有奏效。 该simpliest和放大器;可以理解code我在我的研究中看到的是这样的:
新java.util.Timer中的()。时间表(
新java.util.TimerTask中的(){
@覆盖
公共无效的run(){
//你的code在这里
}
},
5000
);
解决方案
只需简单地使用下面的代码片段
专用处理器处理器=新的处理程序();
runnable.run();
私人可运行可运行=新的Runnable()
{
公共无效的run()
{
//
//做的东西
//
handler.postDelayed(这一点,1000);
}
};
要停止使用。
handler.removeCallbacks(可运行);
应该做的伎俩。
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.
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.
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:
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:
new java.util.Timer().schedule(
new java.util.TimerTask() {
@Override
public void run() {
// your code here
}
},
5000
);
解决方案
Just simply use below snippet
private Handler handler = new Handler();
runnable.run();
private Runnable runnable = new Runnable()
{
public void run()
{
//
// Do the stuff
//
handler.postDelayed(this, 1000);
}
};
To stop it use
handler.removeCallbacks(runnable);
Should do the trick.
上一篇:的IntelliJ和android.support.v7.widget.GridLayoutsupport、android、IntelliJ、GridLayout
下一篇:如何从一个活动位图传递到另一位图