12

Sometimes we need to delay a code before it runs.

This is doable by the Handler.postDelayed(Runnable) or CountdownTimer.

Which one is better in terms of performance?

See the sample code below

Handler

        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                 //DO SOMETHING
            }
        }, 1000);

CountDownTimer

        new CountDownTimer(1000, 1000) {
            public void onFinish() {
                 //DO SOMETHING
            }
            public void onTick(long millisUntilFinished) {}
        }.start();
N J
  • 27,217
  • 13
  • 76
  • 96
JayVDiyk
  • 4,277
  • 22
  • 70
  • 135

3 Answers3

11

The Handler should offer you better performances as CountDownTimer contains itself a Handler as you can see here.

E-Kami
  • 2,529
  • 5
  • 30
  • 50
8

I agree that Handler is offering a better performance. But on a side note, you should keep in mind that CountDownTimer object will be destroyed after completed. A Handler will continue to exist after finished. If you only need a temporary timer then CountDownTimer is preferable. Otherwise, use a Handler.

minh bo
  • 81
  • 1
  • 3
  • This should be the accepted answer. It is the only that explains that "why". Besides, all the links provided in the other answers, no longer lead to a functioning web page. – WebViewer Jan 12 '23 at 14:55
1

Use Handler,Android Handler is Good.

See Here, What Others say About Handler

Uttam Panchasara
  • 5,735
  • 5
  • 25
  • 41