0
我寫了一些計時器。我想在單擊開始按鈕後在textview
中顯示它。 我做了什麼。 每次我使用線程多次更新UI
timer = new Thread(new Runnable() {
@Override
public void run() {
while (!stopedButton) {
time = "";
if (timerMinutes >= 60) {
timerMinutes = 0;
timerHours++;
}
if (timerHours < 10)
time = "0" + String.valueOf(timerHours) + ":";
else
time = String.valueOf(timerHours) + ":";
if (timerMinutes < 10)
time += "0" + String.valueOf(timerMinutes);
else
time += String.valueOf(timerMinutes);
runOnUiThread(new Runnable() {
public void run() {
if (!stopedButton) {
mTimeFromStartValue.setText(time);
timerMinutes++;
} else {
timerMinutes = 0;
timerHours = 0;
}
}
});
Log.e(TAG, ""+timerHours);
Log.e(TAG, ""+timerMinutes);
Log.e(TAG, time);
try {
Thread.sleep(1 * 1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
});
所以它工作正常,但停車後,然後每一次啓動,並做了很多次後,我的計時器開始工作快。我儘量避免這種情況,我認爲我不需要每次都創建新的計時器。但我也需要在停止開始後有工作計時器。
我寫了一些像這樣的代碼:
if(timer.isAlive()){
timer.resume();
}else{
timer.start();
}
但我得到這個異常:java.lang.IllegalThreadStateException: Thread already started
那麼如何解決這個問題?
對於這種行爲在Android中推薦的方法是的TimerTask –