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

Android examples for java.lang:Thread

Description

Post the supplied FutureTask to run on the main thread.

Demo Code

// Copyright (c) 2012 The Chromium Authors. All rights reserved.
//package com.java2s;

import java.util.concurrent.FutureTask;
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;

    /**//from w  w w .  j  a  v  a  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;
    }

    /**
     * Post the supplied Runnable to run on the main thread. The method will not block, even if
     * called on the UI thread.
     *
     * @param task The Runnable to run
     */
    public static void postOnUiThread(Runnable r) {
        getUiThreadHandler().post(r);
    }

    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