Timer in the Android app

How do I make a timer in an android app? Simple to use java.util.Timer?

Author: diralik, 2011-08-16

3 answers

There is this in the OS - CountDownTimer In general, here is an example for you:

Timer timer = new Timer();
timer.schedule(new UpdateTimeTask(), 0, 1000); //тикаем каждую секунду без задержки 
//задача для таймера
class UpdateTimeTask extends TimerTask {
    public void run() {
        ...
    } 
}

Actually, try CountDownTimer first. Oh, I remember. Here's another dock.

Only the timer works once (the one that java.util.Timer), this is its feature, and you need to intercept IllegalStateException.

 11
Author: DroidAlex, 2017-11-18 22:48:04

You can use CountDownTimer.

public class MyTimer extends CountDownTimer
{

    public MyTimer(long millisInFuture, long countDownInterval) 
    {
          super(millisInFuture, countDownInterval);
    }

    @Override
    public void onFinish() 
    {
        // Do something...
    }

    public void onTick(long millisUntilFinished) 
    {

    }

}
 8
Author: AndroidDev, 2011-08-16 12:36:47

If you need a simple timer, you can use Chronometer.

For example, in layout we put chronometer:

<Chronometer
android:id="@+id/chronometer"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>

In Activity, we initialize Chronometer, get the time from the start of the application, and set it as the base for our Cronometer:

Chronometer chronometer = (Chronometer) findViewById(R.id.chronometer);
long startTime = SystemClock.elapsedRealtime();
chronometer.setBase(startTime);

We get a normal ticking timer on the screen.

The time output format can be changed in setFormat(String format)

 1
Author: Alex Kisel, 2017-10-12 22:39:51