Determine if we are currently on the UI Thread, if we are, execute the ACTION requested, otherwise action is posted to the UI Thread and function returns without delay - Android java.lang

Android examples for java.lang:Thread

Description

Determine if we are currently on the UI Thread, if we are, execute the ACTION requested, otherwise action is posted to the UI Thread and function returns without delay

Demo Code


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

public class Main {
    private static Handler uiHandler;

    /**/*from  ww w.  j a v a2s .  co  m*/
     * Determine if we are currently on the UI Thread, if we are, execute the ACTION requested, otherwise action is posted to the UI Thread
     * and function returns without delay
     *
     * @param action procedure to run on the UI Thread
     */
    public static void runOnUiThread(final Runnable action) {
        if (isOnUiThread()) {
            action.run();
        } else {
            postOnUiThread(action);
        }
    }

    /**
     * Check to see whether current thread is also the UI Thread
     *
     * @return TRUE when current thread is the UI Thread
     */
    public static boolean isOnUiThread() {
        return Looper.getMainLooper().getThread() == Thread.currentThread();
    }

    /**
     * Same as calling #postOnUiThread(action,false)
     */
    public static void postOnUiThread(final Runnable action) {
        postOnUiThread(action, false);
    }

    /**
     * Always post action to the UI Thread for execution
     *
     * @param action procedure to run on the UI Thread
     * @param wait   true if we should wait for action to complete before returning to calling process
     */
    public static void postOnUiThread(final Runnable action,
            final boolean wait) {
        if (uiHandler == null) {
            uiHandler = new Handler(Looper.getMainLooper());
        }

        uiHandler.post(new Runnable() {
            @Override
            public void run() {
                synchronized (action) {
                    action.run();
                    if (wait) {
                        action.notify();
                    }
                }
            }
        });

        waitForAction(action, wait);

    }

    protected static void waitForAction(final Runnable action, boolean wait) {
        if (wait) {
            synchronized (action) {
                try {
                    action.wait();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}

Related Tutorials