Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use handler as a timer in android?

    Handler handler = new Handler();    
    if (v.getId() == R.id.play){    
       handler.postDelayed(new Runnable() {                    
       public void run() {
           play.setBackgroundResource(R.drawable.ilk);
       }
   }, 2000);    
       play.setText("Play");    
}

I want to set background first and then after 2 seconds later, code will continue next line which is play.setText("Play"); and goes like that. Instead of this, first text appears. 2 seconds later background changes.

like image 912
Enes Avatar asked Aug 07 '16 11:08

Enes


People also ask

What is the use of handler in Android?

A Handler allows you to send and process Message and Runnable objects associated with a thread's MessageQueue . Each Handler instance is associated with a single thread and that thread's message queue. When you create a new Handler it is bound to a Looper .

What is the difference between Android timer and a handler to do action every n seconds?

Handler is better than TimerTask . The Java TimerTask and the Android Handler both allow you to schedule delayed and repeated tasks on background threads. However, the literature overwhelmingly recommends using Handler over TimerTask in Android (see here, here, here, here, here, and here).

How do you use kotlin handler on Android?

You can use Handler to add a Runnable object or messages to the Looper to execute the code on the thread associated with the Looper. Android associates each Handler instance with a single thread and that thread's message queue. Whenever you create a new Handler instance, it is tied up to a single Looper .


1 Answers

Handler.postDelayed returns immediately. And next line is executed. After indicated milliseconds, the Runnable will be executed.

So your code should be like this:

void doFirstWork() {
    Handler handler = new Handler();

    if (v.getId() == R.id.play){

       handler.postDelayed(new Runnable() {
           public void run() {
               play.setText("Play");
               doNextWork();
           }
       }, 2000);

       play.setBackgroundResource(R.drawable.ilk);
    }
}

void doNextWork() {
    ...
}
like image 147
nshmura Avatar answered Sep 21 '22 04:09

nshmura