Timer in Android

6 November 2023
Share

Timer in Android is used for scheduling or delaying code execution at a specific movement.

Implementation

Create a Timer object and initialize it.

timer=new Timer();
            timer.schedule(new TimerTask() {
                @Override
                public void run() {
                    //Executed code
                Log.d("Timer","Executed");
                }
            },3000);
        });

The code in the run method is executed after 3 milliseconds(that 3 ms is the delay).

To repeat execution at specific intervals, pass delay and period parameters.

After launching the app for the first time, the code is executed after a 2ms delay, and then every 1ms thereafter.

Start, Pause, Stop operation on Timer

Create the 3 buttons for the start, pause, and stop the timer.

To start the timer write the following code on the start button click.

btnStart.setOnClickListener(v -> {
            timer = new Timer();
            timer.schedule(new TimerTask() {
                @Override
                public void run() {
                    //Executed code
                    Log.d("Timer In Android", x + "");
                    x++;
                }
            }, 0, 1000);
        });

To Pause /Pause the timer use the same code.

btnPause.setOnClickListener(v -> {
            timer.cancel();
            timer = null;
        });

Issue due to multiple instances of a timer

Do the following operation on the app.

  1. Start timer

2. Pause timer

3. Start once again

4. Stop and Start again

5. Start once again then things are going weird.

This issue is due to the creation of multiple instances of a timer on every click of start. To solve this just add the null check on the start click.

btnStart.setOnClickListener(v -> {
            if(timer!=null){
                return;
            }
            timer = new Timer();
            timer.schedule(new TimerTask() {
                @Override
                public void run() {
                    //Executed code
                    Log.d("Timer In Android", x + "");
                    x++;
                }
            }, 0, 1000);
        });

If after these changes crash issue occurs then it is due to the use of cancel operation on the timer object on the pause and stop buttons so we need to also add a null check here.

on Pause.

on Stop.

runOnUIThread

Now we just want to display the log value in the textview but if we directly set this value as

textView.setText(x+"");

CalledFromWrongThreadException

Then it will give an error CalledFromWrongThreadException.

This error means only the UI or Main thread is allowed to update the text value or other words we can update the appearance of views only on the UI or Main thread.

for now to solve this, just run the required code on the UI thread as below.

To gain a better understanding of threading in Android, I recommend reading the article Threading in Android (rishiz.site)

timer.schedule(new TimerTask() {
                @Override
                public void run() {
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            textView.setText(x+"");
                            x++; 
                        }
                    });
                }
            }, 0, 1000);

App:

Timer app