Android CountDownTimer类滞后主线程 [英] Android CountDownTimer Class Lagging Main Thread
问题描述
我正尝试使用android.os.CountDownTimer通过文本视图从字面上显示倒数计时器,以达到适应性目的.我遇到的问题是计时器似乎无法在主线程上运行,即倒数将跳2-4秒,并且明显被滞后"-计时器旨在处于无休止的循环中,直到停止按钮被按下为止按下.
I am trying to use android.os.CountDownTimer to literally show a countdown timer via a textview for fitness purposes. The issue I am having is the timer seems to be having trouble running on the main thread i.e. the countdown will jump 2-4 secs and is clearly being "lagged" - the timer is intended to be in an endless loop until a stop button is pressed.
我是Java和Android的新手,无法弄清楚如何运行倒数计时器并更新UI,而不会发生任何冲突或滞后.
I am new to Java and Android and cannot figure out how to get the countdown timer running and updating the UI without any conflicts or lagging.
我试图将CountDown放到Handler/Runnable和一个Asynctask中,但是没有运气.
I have attempted to put the CountDown in a Handler/Runnable and an Asynctask with no luck.
MainActivity
MainActivity
CountDownTimer timer;
void countdownTimer() {
long min = countdownMins * 60000;
long sec = countdownSecs * 1000;
long milliseconds = min+sec;
timer = null;
timer = new CountDownTimer(milliseconds, 1000) {
public void onTick(long millisUntilFinished) {
long mins = millisUntilFinished / 60000;
long secs = millisUntilFinished % 60000 / 1000;
String display = String.format("%02d:%02d", mins, secs);
tvTextView.setText(display);
}
public void onFinish() {
countdownTimer();
}
}.start();
}
非常感谢任何可以向我展示如何使它在主线程中运行的人,这样我的UI元素将变得平滑.
Many thanks to anyone who can show me how to get this running off the main thread so my UI elements will be smooth.
推荐答案
我决定采用另一种方法,该方法非常适合我的目的.没有滞后或线程问题,可以轻松地一遍又一遍地重启.希望这可以帮助某人.
I decided to take a different approach which has served my purposes very well. No lag or thread issues and can easily be restarted over and over. Hope this helps someone out.
int startCountdown = 5;
int currentCountdown;
Handler countdownHandler = new Handler();
Timer countdownTimer = new Timer();
public void startCountdownTimer() {
currentCountdown = startCountdown;
for (int i = 0; i <= startCountdown; i++) {
TimerTask task = new TimerTask() {
@Override
public void run() {
countdownHandler.post(doA);
}
};
countdownTimer.schedule(task, i * 1000);
}
}
final Runnable doA = new Runnable() {
@Override
public void run() {
if (currentCountdown != 0) {
tvTextView.setText("" + currentCountdown);
currentCountdown--;
} else {
currentCountdown = startCountdown;
startCountdownTimer();
}
}
};
这篇关于Android CountDownTimer类滞后主线程的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!