Skip to content Skip to sidebar Skip to footer

Android Countdowntimer Class Lagging Main Thread

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

Solution 1:

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.

intstartCountdown=5;
int currentCountdown;
HandlercountdownHandler=newHandler();
TimercountdownTimer=newTimer();
publicvoidstartCountdownTimer() {
    currentCountdown = startCountdown;
    for (inti=0; i <= startCountdown; i++) {
        TimerTasktask=newTimerTask() {
            @Overridepublicvoidrun() {
                countdownHandler.post(doA);
            }
        };
        countdownTimer.schedule(task, i * 1000);
    }
}
finalRunnabledoA=newRunnable() {
    @Overridepublicvoidrun() {
        if (currentCountdown != 0) {
            tvTextView.setText("" + currentCountdown);
        currentCountdown--;
        } else {
            currentCountdown = startCountdown;
            startCountdownTimer();
        }
    }
};

Solution 2:

Try to use Handler and runnable instead of CountDownTimer. Here is a good article about this approach

http://www.mopri.de/2010/timertask-bad-do-it-the-android-way-use-a-handler/

One more thing you could try is

voidcountdownTimer() {

    finalRunnablerunnable=newRunnable() {
        @Overridepublicvoidrun() {
            tvTextView.setText(display);
        }
    };
    longmin= countdownMins * 60000;
    longsec= countdownSecs * 1000;
    longmilliseconds= min + sec;
    timer = null;
    timer = newCountDownTimer(milliseconds, 1000) {

        publicvoidonTick(long millisUntilFinished) {

            longmins= millisUntilFinished / 60000;
            longsecs= millisUntilFinished % 60000 / 1000;
            finalStringdisplay= String.format("%02d:%02d", mins, secs);
            textView.post(runnable);
        }

        publicvoidonFinish() {
            countdownTimer();
        }
    }.start();
}

Solution 3:

If you countdown with changing your TextView fast and frequently. You have to set your TextView width and height in a fix number, or it will lag while calculating your view scale.

Post a Comment for "Android Countdowntimer Class Lagging Main Thread"