give a delay of few seconds without using threads

前端 未结 2 1888
渐次进展
渐次进展 2020-12-31 19:53

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

2条回答
  •  温柔的废话
    2020-12-31 20:17

    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().

提交回复
热议问题