我正在编写一个Android应用程序,我需要设置一个Timer,每隔一秒执行一次方法,然后一旦布尔变量(由前面提到的方法设置)变为真,就停止。
以下是我正在尝试做的事情的概述:
boolean done = false;
public void someMethod() {
if(done == false) {
myTimer = new Timer(); //Set up a timer, to execute TimerMethod repeatedly
myTimer.schedule(new TimerTask() {
@Override
public void run() {
TimerMethod();
}
}, 0, 1000);
}
if(done == true) {
//TimerMethod will eventually set 'done' to true. When this happen, do layout modifying stuff here. Causes error as non-UI thread is executing the layout modifying stuff. Do I spawn a new UI thread here to do it? If so, how? :/
}
}
TimerMethod() {
String result = someServerMethod();
if(result == "theResultWeWant") {
myTimer.cancel(); //stop the timer - we're done!
done = true; //set 'done' to true so the line of code in someMethod() will now run
someMethod();
}
}
编辑:我已更新上面的代码以反映我想要做的事情。我希望我可以将完成的flash设置为true,然后继续执行someMethod,但我确定它不是那么简单!我是否需要从TimerMethod()生成一个新线程来执行done == true
行的代码?
答案 0 :(得分:2)
所有UI交互都需要从主(UI)线程完成。在你的情况下,你从TimerTask调用someMethod(),这是一个单独的线程。处理程序用于与辅助线程中的主线程交互。
public void someMethod() {
myTimer = new Timer(); //Set up a timer, to execute TimerMethod repeatedly
myTimer.schedule(new TimerTask() {
@Override
public void run() {
TimerMethod();
}
}, 0, 1000);
}
}
TimerMethod() {
String result = someServerMethod();
if(result.equals("theResultWeWant")) {
myTimer.cancel(); //stop the timer - we're done!
mHandler.sendEmptyMessage(0): //send message to handler to update UI
}
}
private Handler mHandler = new Handler(){
public void handleMessage(Message msg) {
doUIMethod();
}
};