Post the supplied FutureTask to run on the main thread. - Android Android OS

Android examples for Android OS:Thread

Description

Post the supplied FutureTask to run on the main thread.

Demo Code


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

import java.util.concurrent.FutureTask;

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

    /**/*from ww  w  .j  ava 2 s.c o  m*/
     * Post the supplied FutureTask to run on the main thread. The method will not block, even if
     * called on the UI thread.
     *
     * @param task The FutureTask to run
     * @return The queried task (to aid inline construction)
     */
    public static <T> FutureTask<T> postOnUiThread(FutureTask<T> task) {
        getUiThreadHandler().post(task);
        return task;
    }

    public static void postOnUiThread(Runnable r) {
        getUiThreadHandler().post(r);
    }

    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