39

I want to wait 5 seconds before starting another public void method. The thread sleep was not working for me. If there is a way of wait() without using Threads I would love to know that.

public void check(){
    //activity of changing background color of relative layout
}

I want to wait 3 seconds before changing the relative layout color.

Dharman
  • 30,962
  • 25
  • 85
  • 135
  • 1
    Possible duplicate of [How to pause / sleep thread or process in Android?](http://stackoverflow.com/questions/1520887/how-to-pause-sleep-thread-or-process-in-android) – till Jan 15 '17 at 18:05
  • 2
    @till as specified i checked these but they did not work for me,yet thanks for considering :) –  Jan 15 '17 at 18:10
  • 1
    Cannot actually see the difference between the answer of the referenced question and your selected answer... – till Jan 22 '17 at 15:03

8 Answers8

96

See if this works for you. Be sure to import the android.os.Handler

      Handler handler = new Handler();
            handler.postDelayed(new Runnable() {
                public void run() {
                    // yourMethod();
                }
            }, 5000);   //5 seconds

or Kotlin

Handler().postDelayed({
    // yourMethod()
}, 5000)
seekingStillness
  • 4,833
  • 5
  • 38
  • 68
  • It gives an error saying Handler is an Abstract cannot be instantiated –  Jan 15 '17 at 18:16
  • I think it's an error from my side,i'll check it again with a fresh mind tomorrow –  Jan 15 '17 at 18:17
  • 4
    Use this Handler `android.os.Handler`. You're using the logging Handler and that one doesn't have a `postDelay` method. You're also getting that not initiated error cause you have to implement some methods to it cause you're using the Logging handler – Jcorretjer Apr 21 '17 at 00:02
  • This one should be an answer. – danyapd Mar 19 '20 at 14:29
47

just add one-liner with lambda

(new Handler()).postDelayed(this::yourMethod, 5000);

edit for clarification: yourMethod refers to the method which you want to execute after 5000 milliseconds.

Schniddi
  • 57
  • 1
  • 1
  • 7
Mike Antipiev
  • 486
  • 5
  • 6
  • Good and fast solution, but this one will not work for all of needs. Good example - when you need to wait before executing / calling activity method from Adapter. – danyapd Mar 19 '20 at 14:29
  • is this synchronous or asynchronous ? – Jitin Nov 29 '20 at 00:24
  • 1
    this does not really wait does it, it just executes a function at a later time . . . – Jitin Nov 29 '20 at 00:37
  • 1
    (new Handler(Looper.getMainLooper())).postDelayed(null, 5000); as no augument constructure is depricated and if you want to wait without any method call pass null – Raja Nagendra Kumar Feb 15 '21 at 12:27
13

you can use java handlers to achieve your task:

Handler handler = new Handler();
handler.postDelayed(new Runnable() {
    public void run() {
     // Actions to do after 5 seconds
    }
}, 5000);

for more information read the following url:

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

Abandoned Cart
  • 4,512
  • 1
  • 34
  • 41
6

For import use: import android.os.Handler;

new Handler().postDelayed(new Runnable() {
    public void run() {
        // yourMethod();
    }
}, 5000); // 5 seconds
Samuel Liew
  • 76,741
  • 107
  • 159
  • 260
Eman Sallam
  • 301
  • 3
  • 3
3

This works for me:

    val handler = Handler()
    handler.postDelayed({
        // your code to run after 2 second
    }, 2000)
Biplob Das
  • 2,818
  • 21
  • 13
1

what I prefer is

(new Handler()).postDelayed(this::here is your method,2000);
Sam
  • 241
  • 3
  • 7
0

One line in Java 8

new Handler().postDelayed(() -> check(), 3000);

This is clean and nice for reading

Daniel Beltrami
  • 756
  • 9
  • 22
-1

I posted this answer to another question, but it may also help you.

Class:

import android.os.Handler;
import android.os.Looper;

public class Waiter {

WaitListener waitListener;
int waitTime = 0;
Handler handler;
int waitStep = 1000;
int maxWaitTime = 5000;
boolean condition = false;

public Waiter(Looper looper, final int waitStep, final int maxWaitTime){

    handler = new Handler(looper);
    this.waitStep = waitStep;
    this.maxWaitTime = maxWaitTime;

}

public void start(){

    handler.post(new Runnable() {
        @Override
        public void run() {

            waitListener.checkCondition();

            if (condition) {

                waitListener.onConditionSuccess();

            } else {
                if (waitTime <= maxWaitTime) {

                    waitTime += waitStep;
                    handler.postDelayed(this, waitStep);

                } else {

                    waitListener.onWaitEnd();
                }
            }
        }
    });

}

public void setConditionState(boolean condition){
    this.condition = condition;
}

public void setWaitListener(WaitListener waitListener){
    this.waitListener = waitListener;
}

}

Interface:

public interface WaitListener {

public void checkCondition();

public void onWaitEnd();

public void onConditionSuccess();

}

Usage example:

ConnectivityManager mConnMgr = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
final int result = mConnMgr.startUsingNetworkFeature(ConnectivityManager.TYPE_MOBILE, "enableMMS");

final Waiter waiter = new Waiter(getMainLooper(), 1000, 5000);
waiter.setWaitListener(new WaitListener() {

            @Override
            public void checkCondition() {
                Log.i("Connection", "Checking connection...");
                NetworkInfo networkInfo = mConnMgr.getNetworkInfo(ConnectivityManager.TYPE_MOBILE_MMS);
                waiter.setConditionState(networkInfo.isConnected());
            }

            @Override
            public void onWaitEnd() {
                Log.i("Connection", "No connection for sending");
                //DO
            }

            @Override
            public void onConditionSuccess() {
                Log.i("Connection", "Connection success, sending...");
                //DO
            }

});

waiter.start();
Abandoned Cart
  • 4,512
  • 1
  • 34
  • 41
Samet
  • 917
  • 12
  • 26