323

I want to make a pause between two lines of code, Let me explain a bit:

-> the user clicks a button (a card in fact) and I show it by changing the background of this button:

thisbutton.setBackgroundResource(R.drawable.icon);

-> after let's say 1 second, I need to go back to the previous state of the button by changing back its background:

thisbutton.setBackgroundResource(R.drawable.defaultcard);

-> I've tried to pause the thread between these two lines of code with:

try {
    Thread.sleep(1000);
} catch (InterruptedException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
}

However, this does not work. Maybe it's the process and not the Thread that I need to pause?

I've also tried (but it doesn't work):

new Reminder(5);

With this:

public class Reminder {

Timer timer;

        public Reminder(int seconds) {
            timer = new Timer();
            timer.schedule(new RemindTask(), seconds*1000);
        }

        class RemindTask extends TimerTask {
            public void run() {
                System.out.format("Time's up!%n");
                timer.cancel(); //Terminate the timer thread
            }
        }  
    }

How can I pause/sleep the thread or process?

hichris123
  • 10,145
  • 15
  • 56
  • 70
Hubert
  • 16,012
  • 18
  • 45
  • 51
  • 6
    Oh, just use the classic thread pause block:while (true) {} – KristoferA Mar 07 '10 at 05:54
  • 9
    @KristoferA-Huagati.com I am not sure if you are being sarcastic or indeed there is some Dalvik/Android magic so that this is acceptable on Android. Can you please clarify? Sorry for doubting but I ask because while `(!conditionCheck()) {}` is usually discouraged. – Miserable Variable May 29 '12 at 22:08
  • 1
    "However, this does not work." "I've also tried (but it doesn't work)" This is a classic example of saying there's a problem without giving the symptoms. In what way did these attempts fail to meet your requirements? Did the thread not pause? Did you get an error message? – LarsH Jul 17 '17 at 21:52

12 Answers12

483

One solution to this problem is to use the Handler.postDelayed() method. Some Google training materials suggest the same solution.

@Override
public void onClick(View v) {
    my_button.setBackgroundResource(R.drawable.icon);

    Handler handler = new Handler(); 
    handler.postDelayed(new Runnable() {
         @Override 
         public void run() { 
              my_button.setBackgroundResource(R.drawable.defaultcard); 
         } 
    }, 2000); 
}

However, some have pointed out that the solution above causes a memory leak because it uses a non-static inner and anonymous class which implicitly holds a reference to its outer class, the activity. This is a problem when the activity context is garbage collected.

A more complex solution that avoids the memory leak subclasses the Handler and Runnable with static inner classes inside the activity since static inner classes do not hold an implicit reference to their outer class:

private static class MyHandler extends Handler {}
private final MyHandler mHandler = new MyHandler();

public static class MyRunnable implements Runnable {
    private final WeakReference<Activity> mActivity;

    public MyRunnable(Activity activity) {
        mActivity = new WeakReference<>(activity);
    }

    @Override
    public void run() {
        Activity activity = mActivity.get();
        if (activity != null) {
            Button btn = (Button) activity.findViewById(R.id.button);
            btn.setBackgroundResource(R.drawable.defaultcard);
        }
    }
}

private MyRunnable mRunnable = new MyRunnable(this);

public void onClick(View view) {
    my_button.setBackgroundResource(R.drawable.icon);

    // Execute the Runnable in 2 seconds
    mHandler.postDelayed(mRunnable, 2000);
}

Note that the Runnable uses a WeakReference to the Activity, which is necessary in a static class that needs access to the UI.

tronman
  • 9,862
  • 10
  • 46
  • 61
  • 3
    It works, but that's a pretty inconvenient way to introduce delays throughout code, right? – Ehtesh Choudhury Jan 20 '12 at 19:14
  • 4
    I'm not sure what you mean by "inconvenient". The Handler's postDelayed method is designed to tell Android that you want a bit of code to be executed after a certain amount of time has passed. – tronman Feb 16 '12 at 19:45
  • 27
    after 2 years and this code just helped me! thanks @tronman!! :) – Melvin Lai Jun 04 '12 at 09:53
  • This works great, but how come you didn't get an error "Cannot refer to a non-final variable my_button inside an inner class defined in a different method"? That's what I get, so I have to mark my_button as final. – Noumenon May 02 '13 at 10:11
  • 2
    You can simply copy it to another (final) variable like so `final Button mynewbutton = mybutton;` and use `mynewbutton` in the Handler and the Runnable from there on. – Dzhuneyt May 17 '13 at 13:19
  • 2
    @MelvinLai after 5 years and this code just helped me! :) – gabrieloliveira Nov 26 '15 at 18:13
  • @HardikParmar No, just running what is in run() once after a 2 second delay. – tronman Mar 10 '16 at 17:10
  • add missing @Override to run method – user3294126 Apr 12 '16 at 15:23
  • This causes a memory leak (of the context) because of the use of an anonymous class, doesn't it? – source.rar Nov 07 '16 at 15:41
  • @source.rar - Thanks for bringing that to my attention. I've updated my solution which no longer contains a memory leak. – tronman Jan 02 '17 at 21:37
  • Thanks, but you don't need to create myHandler class here – beginner Apr 04 '20 at 09:19
203

You can try this one it is short

SystemClock.sleep(7000);

WARNING: Never, ever, do this on a UI thread.

Use this to sleep eg. background thread.


Full solution for your problem will be: This is available API 1

findViewById(R.id.button).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(final View button) {
                button.setBackgroundResource(R.drawable.avatar_dead);
                final long changeTime = 1000L;
                button.postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        button.setBackgroundResource(R.drawable.avatar_small);
                    }
                }, changeTime);
            }
        });

Without creating tmp Handler. Also this solution is better than @tronman because we do not retain view by Handler. Also we don't have problem with Handler created at bad thread ;)

Documentation

public static void sleep (long ms)

Added in API level 1

Waits a given number of milliseconds (of uptimeMillis) before returning. Similar to sleep(long), but does not throw InterruptedException; interrupt() events are deferred until the next interruptible operation. Does not return until at least the specified number of milliseconds has elapsed.

Parameters

ms to sleep before returning, in milliseconds of uptime.

Code for postDelayed from View class:

/**
 * <p>Causes the Runnable to be added to the message queue, to be run
 * after the specified amount of time elapses.
 * The runnable will be run on the user interface thread.</p>
 *
 * @param action The Runnable that will be executed.
 * @param delayMillis The delay (in milliseconds) until the Runnable
 *        will be executed.
 *
 * @return true if the Runnable was successfully placed in to the
 *         message queue.  Returns false on failure, usually because the
 *         looper processing the message queue is exiting.  Note that a
 *         result of true does not mean the Runnable will be processed --
 *         if the looper is quit before the delivery time of the message
 *         occurs then the message will be dropped.
 *
 * @see #post
 * @see #removeCallbacks
 */
public boolean postDelayed(Runnable action, long delayMillis) {
    final AttachInfo attachInfo = mAttachInfo;
    if (attachInfo != null) {
        return attachInfo.mHandler.postDelayed(action, delayMillis);
    }
    // Assume that post will succeed later
    ViewRootImpl.getRunQueue().postDelayed(action, delayMillis);
    return true;
}
Gelldur
  • 11,187
  • 7
  • 57
  • 68
  • 22
    And let the Android UI freeze? Don't do this. – shkschneider Aug 10 '13 at 17:24
  • android.os.SystemClock.sleep(x); – cowlinator May 17 '14 at 00:46
  • 3
    Ctrl + Shift + O (Eclipse auto import) – Gelldur May 17 '14 at 09:08
  • @gelidur : Doing this in a bg thread would do what? That bg th read still needs to postdelay or runonuithread to change the button. Not good. – RichieHH Jul 29 '14 at 07:37
  • This is only for sleep. Thanks to that you don't need to write those ugly lines with empty catch. – Gelldur Aug 07 '14 at 13:54
  • 14
    Gelldur, you are missing the point of @RichieHH's comment. Compared to the **answer which was accepted 3 years before you posted**, what you suggest does not help OP solve his problem. Reason: The code, both as shown by OP, and as shown in the accepted answer, **is running inside a UI handler**. Saying `OMG of course do this in background thread` is irrelevant, unless you show HOW to put it in background thread. At which time, you will discover that you have an answer more complicated than the already accepted answer. Did I mention that a better solution was accepted three years ago? :P – ToolmakerSteve Sep 12 '14 at 17:52
  • 2
    ... forgot to mention that what makes this suggestion particularly off-purpose to the question, is that OP explicitly wants to do UI action after the delay. So, you would have a solution in which you've created a background thread (already more heavy-weight than is needed to solve the problem), slept, and then you have to (somehow) get back to the UI thread. `Handler + postRunnable` accomplishes all this, in a single step. Without the system overhead of creating a second thread. – ToolmakerSteve Sep 12 '14 at 18:01
  • @ToolmakerSteve yes but if your code already runs on say an async task, this solution works perfectly without changing the async task. perfect for mocking code – Jono May 25 '16 at 08:38
  • 2
    @ToolmakerSteve happy now :D ? Main question is: "How to pause / sleep thread or process in Android?" so my answer was simple :). If someone google for "how to sleep thread" this question will show. He/She is probably looking for my answer :P. But ok i added full response ;) – Gelldur May 25 '16 at 08:55
  • This freezes the UI thread, even if you run it on any other thread. – Behnam Apr 27 '17 at 04:58
  • @Behnam you are doing something wrong here. Simply it can't freeze other thread than executed one. Remember that `button.postDelayed(new Runnable()` is running on UI Thread! – Gelldur Apr 27 '17 at 09:32
32

I use this:

Thread closeActivity = new Thread(new Runnable() {
  @Override
  public void run() {
    try {
      Thread.sleep(3000);
      // Do some stuff
    } catch (Exception e) {
      e.getLocalizedMessage();
    }
  }
});
Philipp Reichart
  • 20,771
  • 6
  • 58
  • 65
Byt3
  • 337
  • 3
  • 2
  • 5
    What is the `e.getLocalizedMessage()` supposed to do? – Philipp Reichart Mar 26 '12 at 22:28
  • i use e.getLocalizedMessage() when i need a simple, general and quick exception message – Byt3 Mar 30 '12 at 17:02
  • 1
    But I bet you don't do this in the situation OP asks about, inside a UI click method, which is going to make further updates to the UI. The accepted `Handler/postDelayed` solution has two advantages: (1) avoids system overhead of 2nd thread, (1) runs on UI thread, so can make UI changes without causing an exception. – ToolmakerSteve Sep 12 '14 at 18:04
  • 1
    Not directly related to the main goal of the question but you shouldn't catch Exception. Rather catch InterruptedException. By catching Exception, you will catch everything that could go wrong, thus hiding problems that you would otherwise caught. – Herve Thu Feb 03 '16 at 21:19
21

I use CountDownTime

new CountDownTimer(5000, 1000) {

    @Override
    public void onTick(long millisUntilFinished) {
        // do something after 1s
    }

    @Override
    public void onFinish() {
        // do something end times 5s
    }

}.start(); 
IIIIIIIIIIIIIIIIIIIIII
  • 3,958
  • 5
  • 45
  • 70
vudandroid
  • 319
  • 2
  • 4
16

You probably don't want to do it that way. By putting an explicit sleep() in your button-clicked event handler, you would actually lock up the whole UI for a second. One alternative is to use some sort of single-shot Timer. Create a TimerTask to change the background color back to the default color, and schedule it on the Timer.

Another possibility is to use a Handler. There's a tutorial about somebody who switched from using a Timer to using a Handler.

Incidentally, you can't pause a process. A Java (or Android) process has at least 1 thread, and you can only sleep threads.

Daniel Yankowsky
  • 6,956
  • 1
  • 35
  • 39
9

In addition to Mr. Yankowsky's answers, you could also use postDelayed(). This is available on any View (e.g., your card) and takes a Runnable and a delay period. It executes the Runnable after that delay.

Melquiades
  • 8,496
  • 1
  • 31
  • 46
CommonsWare
  • 986,068
  • 189
  • 2,389
  • 2,491
9

This is what I did at the end of the day - works fine now :

@Override
    public void onClick(View v) {
        my_button.setBackgroundResource(R.drawable.icon);
        // SLEEP 2 SECONDS HERE ...
        final Handler handler = new Handler(); 
        Timer t = new Timer(); 
        t.schedule(new TimerTask() { 
                public void run() { 
                        handler.post(new Runnable() { 
                                public void run() { 
                                 my_button.setBackgroundResource(R.drawable.defaultcard); 
                                } 
                        }); 
                } 
        }, 2000); 
    }
Hubert
  • 16,012
  • 18
  • 45
  • 51
5

Or you could use:

android.os.SystemClock.sleep(checkEvery)

which has the advantage of not requiring a wrapping try ... catch.

nkr
  • 3,026
  • 7
  • 31
  • 39
aaaa
  • 51
  • 1
  • 1
5

This is my example

Create a Java Utils

    import android.app.ProgressDialog;
    import android.content.Context;
    import android.content.Intent;

    public class Utils {

        public static void showDummyWaitingDialog(final Context context, final Intent startingIntent) {
            // ...
            final ProgressDialog progressDialog = ProgressDialog.show(context, "Please wait...", "Loading data ...", true);

            new Thread() {
                public void run() {
                    try{
                        // Do some work here
                        sleep(5000);
                    } catch (Exception e) {
                    }
                    // start next intent
                    new Thread() {
                        public void run() {
                        // Dismiss the Dialog 
                        progressDialog.dismiss();
                        // start selected activity
                        if ( startingIntent != null) context.startActivity(startingIntent);
                        }
                    }.start();
                }
            }.start();  

        }

    }    
Stefano
  • 75
  • 1
  • 1
  • 3
    Yet another answer added years after the question was already well-solved, that isn't relevant to the question, because it doesn't deal with the stated desire to be able to perform UI work. You can't do UI work here, because you are running on a new thread. Not on the UI thread. – ToolmakerSteve Sep 12 '14 at 18:08
  • 1
    On the UX side of things, showing a blocking dialog to the user to load data is ... not good. – 2Dee Mar 16 '15 at 08:39
  • If we don't need ui changes, I suppose this approach is better than running Handlers on the main thread. But what about the Timer class or running a Handler explicitly on a different Thread? – JCarlosR Dec 18 '20 at 19:19
2

If you use Kotlin and coroutines, you can simply do

GlobalScope.launch {
   delay(3000) // In ms
   //Code after sleep
}

And if you need to update UI

GlobalScope.launch {
  delay(3000)
  GlobalScope.launch(Dispatchers.Main) {
    //Action on UI thread
  }
}
Guillaume
  • 6,214
  • 2
  • 13
  • 14
1

I know this is an old thread, but in the Android documentation I found a solution that worked very well for me...

new CountDownTimer(30000, 1000) {

    public void onTick(long millisUntilFinished) {
        mTextField.setText("seconds remaining: " + millisUntilFinished / 1000);
    }

    public void onFinish() {
        mTextField.setText("done!");
    }
}.start();

https://developer.android.com/reference/android/os/CountDownTimer.html

Hope this helps someone...

John Byrne
  • 41
  • 2
0
  class MyActivity{
    private final Handler handler = new Handler();
    private Runnable yourRunnable;
    protected void onCreate(@Nullable Bundle savedInstanceState) {
       // ....
       this.yourRunnable = new Runnable() {
               @Override
               public void run() {
                   //code
               }
            };

        this.handler.postDelayed(this.yourRunnable, 2000);
       }


     @Override
  protected void onDestroy() {
      // to avoid memory leaks
      this.handler.removeCallbacks(this.yourRunnable);
      }
    }

And to be double sure you can be combined it with the "static class" method as described in the tronman answer

beginner
  • 2,366
  • 4
  • 29
  • 53