Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

give a delay of few seconds without using threads

Tags:

android

delay

How can I give a delay of few seconds without using threads.some function that I can call anywhere for giving delay. Android built-in function is highly preferred. Thanks

like image 531
Waheed Khan Avatar asked Jul 15 '11 07:07

Waheed Khan


People also ask

How do you delay a thread in java?

The easiest way to delay a java program is by using Thread. sleep() method. The sleep() method is present in the Thread class. It simply pauses the current thread to sleep for a specific time.

Which of the following sleep method will give a delay of 5 seconds in thread execution?

Sleep method causes current thread to pause for specific duration of time. We can use Thread's class sleep static method delay execution of java program. Here is sample code to the same. Please note that Unit of time is milliseconds for sleep method, that's why we have passed 5000 for 5 secs delay.

How do you stop a program from few seconds in java?

sleep(5000) pause your execution for 5 sec and resume it again. If your have any code after this statement than it will executed after 5 sec of pause. OR it will execute code written after your if/else is completed.

How do you pause in java?

“java pause for 5 seconds” Code Answersleep(2000); // set time delay to 2 seconds.. System. out. println(i++); // output : every output will display after 2 seconds..


1 Answers

Use a Handler, and send either a simple message or a Runnable to it using a method such as postDelayed().

For example, define a Handler object to receive messages and Runnables:

private Handler mHandler = new Handler();

Define a Runnable:

private Runnable mUpdateTimeTask = new Runnable() {
    public void run() {
        // Do some stuff that you want to do here

    // You could do this call if you wanted it to be periodic:
        mHandler.postDelayed(this, 5000 );

        }
    };

Cause the Runnable to be sent to the Handler after a specified delay in ms:

mHandler.postDelayed(mUpdateTimeTask, 1000);

If you don't want the complexity of sending a Runnable to the Handler, you could also very simply send a message to it - even an empty message, for greatest simplicity - using method sendEmptyMessageDelayed().

like image 77
Trevor Avatar answered Sep 20 '22 13:09

Trevor