How to make a timer in the android application? Just use java.util.Timer ?
3 answers
There is something in the OS - CountDownTimer In general, here's 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 remembered. Here's another dock for you .
Only the timer works once (the one that is java.util.Timer ), such is its feature, and you need to intercept an IllegalStateException .
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) { } } If you need a simple timer, you can use the Chronometer .
For example, put the chronometer in the layout :
<Chronometer android:id="@+id/chronometer" android:layout_width="wrap_content" android:layout_height="wrap_content"/> In Activity , we initialize the Chronometer , we get the time since 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 on the screen a normal ticking timer.
The format of the time output can be changed in setFormat(String format)