Search code examples
androidmultithreadingdelay

Android time delay


How to make a delay that could call a function after some time but the thread still should be running. Is there any better way than this.

new Thread(new Runnable() { 
    public void run(){
        try{ Thread.sleep(recordtime); }
        catch(Exception e){}

        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                reset();
            }
        });
    }
}).start();

Solution

  • To run some code on Ui thread , after some delay:

       Handler h = new Handler(Looper.getMainLooper());
    
        Runnable r = new Runnable() {
            @Override
            public void run() {
                //--code run in Main, UI thread  
            }
        };
    
        h.postDelayed(r,2000); //-- run after 2 seconds
    

    Handler require a Looper on target thread. UI thread already has it, other threads need to be configured first.

    Other options are:

    Timer:

      Timer t = new Timer();
    
        t.schedule(new TimerTask() {
            @Override
            public void run() {
               //--code run in separate thread  
            }
        },2000);
    

    And ScheduledExecutorService:

        ScheduledExecutorService se = Executors.newSingleThreadScheduledExecutor();
    
        se.schedule(new Runnable() {
            @Override
            public void run() {
                //--code run in separate thread
            }
        },2, TimeUnit.SECONDS);