Android CountDown Timer With Just Maths

Just Maths app has a timer which is used to track the time in which user has to answer as many questions as possible with either Yes or No option. We will create a timer which ticks every second as a countdown timer or stopwatch. This is going to be a simple timer implemented using the Handler in Android.

cheezycode_android_stopwatch_and_timer


Execution of your android app is done on main thread which handles all your interaction with your user. All long running tasks are done on other threads. Now in this case you want a timer which ticks every second. Do you think that implementing it with the help of for loop is a good idea? No. Running such code with the loop will block your main thread and stops other operations. So we need a way to create a new thread which ticks every second and help us to implement the stopwatch timer in android. Other thing that is important is only main thread updates the user interface, meaning other thread that you created for timer will not update the UI. You need a way to update the textview as well via main thread.


Handler Class Android


We will use Handler in Android. This class provides a way to execute your code at some point in future and this will be executed in its own thread. Handler also provides a way to interact with the main thread for any updates to the user interface. Handler class has various methods for scheduling code to be executed. We will use post(Runnable) and postDelayed(Runnable,long) for creating simple timer in android. post(Runnable) runs straight away whereas postDelayed(Runnable, long) runs after certain milliseconds which is passed as long value. Below is the code snippet for the simple timer in android -

private int seconds = 10; //THIS WILL RUN FOR 10 SECONDS    
private boolean stopTimer = false;

private void timer() {
    final Handler handler = new Handler();
    handler.post(new Runnable() {
  
 @Override
        public void run() {
            seconds--;
            if (seconds < 0) {
                // DO SOMETHING WHEN TIMES UP
                stopTimer = true;
            }
            if(stopTimer == false) {
                handler.postDelayed(this, 1000);
            }
        }
  
    });
}

Android Timer Code Explanation


In above code snippet, Handler object is created and post(Runnable) is called to execute the code. This code will be executed immediately and in its execution itself other post(Runnable, 1000) call is made with 1000 milliseconds to make a timer. In simple words, you first execute something and say execute the same code again after 1 second = 1000 milliseconds. When required seconds are completed you stop the timer. It is like a cycle.

cheezycode_android_stopwatch_and_timer_logic
Android Handler Logic For StopWatch and Countdown Timer


Let us know for any concerns or query. Happy Reading.


Comments

  1. Hi guys. I like the explanation about using handlers for countdown timer. I do have a question. How would you write it for example: repeating it 3 times.In generaly:as above it runs from 10 to zero and repeats 3 times and ends? Enjoy

    ReplyDelete
    Replies
    1. Didn't get your question. Can you please elaborate more?

      -CheezyCode

      Delete
    2. Ok,let say you use the same code to countdown from 10sec to zero as above. Then you want to repeat it when is finished(reaches zero number) three times. Let say we are doing sport interval countdwon app: three rounds which last 10sec and when round is finished(reaches zero number) it repeats three times(again from 10 to 0). I hope u understand? Cheers

      Delete
    3. Yes got your point. You want something like HIIT Interval kind of app. What you can do is - Create a timer that runs for 30 seconds. In run() method where you decrement your counter, check the value of counter i.e. if it is 30 or 20 or 10 using switch case.

      switch(seconds)
      {
      case 30:
      break;
      case 20:
      // WRITE CODE WHAT YOU WANT TO EXECUTE WHEN ONE INTERVAL COMPLETES
      break;
      }

      Hope it helps. Happy Learning @CheezyCode.

      Delete
  2. Great idea,thank you. Is it posible to use the same code switch statement as above, if I would add pause 5sec between rounds? Cheers

    ReplyDelete
    Replies
    1. Yes, just add case based on your application. Cheers.

      Delete
  3. can I get some more functionalities of android like GPS or messaging

    ReplyDelete
  4. my app is getting crashed again and again it says app unfortunately stoped how do i know what is the problem beacse my app hane no error....

    ReplyDelete
  5. Error is cannot assign a value to final variable stopTimer

    ReplyDelete
  6. hello sir i don't understand code and you voice is very fast
    can you help me for learn

    ReplyDelete
    Replies
    1. Hi, Which video are you playing Hindi or English?
      We have playlist for android in both languages:
      English: https://www.youtube.com/playlist?list=PLRKyZvuMYSIMLGcXqzQBEzxgfDq7D_GZT

      Hindi: https://www.youtube.com/playlist?list=PLRKyZvuMYSIN9sVZTfDm4CTdTAzDQyLJU

      Let us know where you are facing the issue.

      Cheers!!!

      Delete
  7. Sir I am a beginner, and I don't know what to write before and after it. Please guide me through all process. and there is no source code for including timer in your main program as well. Help me.

    ReplyDelete

Post a Comment

Hey there, liked our post. Let us know.

Please don't put promotional links. It doesn't look nice :)

Popular posts from this blog

Create Android Apps - Getting Started

Polymorphism in Kotlin With Example