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

Android examples for java.lang:Thread

Description

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

Demo Code

// Copyright (c) 2012 The Chromium Authors. All rights reserved.
//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  ww.j  av  a 2  s.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 r, long delayMillis) {
        getUiThreadHandler().postDelayed(r, delayMillis);
    }

    private 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