Eveli
Eveli

Reputation: 498

Android - clock lags

i have a problem with my self-written-in-app-clock...

it freezes sometimes. once it freezes for 2 seconds another time for up to 10 seconds. The time is shown correctly, but not fluently...

Here my Code:

    CDT_2 = new CountDownTimer(250, 250) {
        @Override
        public void onTick(long millisUntilFinished) {
            {
                getDate();

                int C_hours_output = C_hours - C_hours_basic;
                int C_minutes_output = C_minutes - C_minutes_basic;
                int C_seconds_output = C_seconds - C_seconds_basic;

                if (C_seconds_output < 0) {
                    C_seconds_output = C_seconds_output + 60;
                    C_minutes_output = C_minutes_output - 1;
                }
                if (C_seconds_output < 10) {
                    STR_seconds = "0"
                            + Integer.valueOf(C_seconds_output).toString();
                } else {
                    STR_seconds = Integer.valueOf(C_seconds_output)
                            .toString();
                }
                if (C_minutes_output < 0) {
                    C_minutes_output = C_minutes_output + 60;
                    C_hours_output = C_hours_output - 1;
                }
                if (C_minutes_output < 10) {
                    STR_minutes = "0"
                            + Integer.valueOf(C_minutes_output).toString();
                } else {
                    STR_minutes = Integer.valueOf(C_minutes_output)
                            .toString();
                }
                if (C_hours_output < 0) {
                    C_hours_output = 0;
                }
                if (C_hours_output < 10) {
                    STR_hours = "0"
                            + Integer.valueOf(C_hours_output).toString();
                } else {
                    STR_hours = Integer.valueOf(C_hours_output).toString();
                }
                ((TextView) acti.findViewById(R.id.TV_time_e01))
                        .setText(STR_seconds);
                ((TextView) acti.findViewById(R.id.TV_time_e0))
                        .setText(STR_minutes + ".");
                ((TextView) acti.findViewById(R.id.TV_time_e1))
                        .setText(STR_hours + ":");
            }
        }

        @Override
        public void onFinish() {
            CDT_2.start();
        }
    }.start();

thanks in advance

Upvotes: 0

Views: 356

Answers (1)

MJMWahoo06
MJMWahoo06

Reputation: 258

The CountDownTimer class does not run on a separate thread, so it is splitting time with UI events and work. See this post for details.

You are better off implementing this with a Handler or Runnable. You can update your TextView elements using Activity.runOnUiThread

See these posts for similar solutions:

Android: How do I display an updating clock in a TextView

Android - implement a custom timer/clock

Upvotes: 1

Related Questions