Я пишу приложение для Android, и мне нужно установить Timer, который будет выполнять метод каждую секунду, а затем остановится, как только логическая переменная (установленная вышеупомянутым методом) станет true.
Вот обзор того, что я пытаюсь сделать:
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();
}
}
Изменить: я обновил код выше, чтобы отразить то, что я хотел бы сделать. Я надеюсь, что я смогу сделать установленную флешку равной true, а затем продолжить выполнение someMethod, но я уверен, что это не так просто! Возможно, мне нужно создать новый поток из TimerMethod(), чтобы выполнить код из строки done == true
?
Все взаимодействия с пользовательским интерфейсом должны выполняться из основного (UI) потока. В вашем случае вы вызывали someMethod() из TimerTask, который является отдельным потоком. Обработчик используется для взаимодействия с вашим основным потоком из вспомогательной нити.
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();
}
};