give a delay of few seconds without using threads

一曲冷凌霜 提交于 2019-12-30 03:23:09

问题


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


回答1:


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




回答2:


Call delayed method from a static context

public final class Config {
    public static MainActivity context = null;
}

In MainActivity:

@Override
protected void onCreate(final Bundle savedInstanceState) {
    ...
    Config.context = this;
    ...
}

...

public void execute_method_after_delay(final Callable<Integer> method, int millisec)
{
    final Handler handler = new Handler();
    handler.postDelayed(new Runnable() {
        @Override
        public void run() {
            try {
                method.call();
            }
            catch (Exception e) {

            }
        }
    }, millisec);
}

From any class using static methods:

private static void a_static_method()
{

    int delay = 3000;
    Config.context.execute_method_after_delay(new Callable<Integer>() {
        public Integer call() {
            return method_to_call();
        }
    }, delay);


}

public static Integer method_to_call()
{
    // DO SOMETHING


来源:https://stackoverflow.com/questions/6704020/give-a-delay-of-few-seconds-without-using-threads

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!