Post the supplied Runnable to run on the main thread after the given amount of time. - Android Android OS

Android examples for Android OS:Thread

Description

Post the supplied Runnable to run on the main thread after the given amount of time.

Demo Code


//package com.java2s;
import android.os.Handler;
import android.os.Looper;

public class Main {
    private static final Object sLock = new Object();
    private static boolean sWillOverride = false;
    private static Handler sUiThreadHandler = null;

    /**/*  w  w w. jav a 2s  . co  m*/
     * Post the supplied Runnable to run on the main thread after the given amount of time. The
     * method will not block, even if called on the UI thread.
     *
     * @param task The Runnable to run
     * @param delayMillis The delay in milliseconds until the Runnable will be run
     */
    public static void postOnUiThreadDelayed(Runnable task, long delayMillis) {
        getUiThreadHandler().postDelayed(task, delayMillis);
    }

    public static Handler getUiThreadHandler() {
        synchronized (sLock) {
            if (sUiThreadHandler == null) {
                if (sWillOverride) {
                    throw new RuntimeException(
                            "Did not yet override the UI thread");
                }
                sUiThreadHandler = new Handler(Looper.getMainLooper());
            }
            return sUiThreadHandler;
        }
    }
}

Related Tutorials