give a delay of few seconds without using threads

前端 未结 2 1876
渐次进展
渐次进展 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:23

    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 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() {
            public Integer call() {
                return method_to_call();
            }
        }, delay);
    
    
    }
    
    public static Integer method_to_call()
    {
        // DO SOMETHING
    

提交回复
热议问题