Asserts that the current thread is running on the main thread. - Android Android OS

Android examples for Android OS:Thread

Description

Asserts that the current thread is running on the main thread.

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 .  j  av a2 s. co m*/
     * Asserts that the current thread is running on the main thread.
     */
    public static void assertOnUiThread() {
        assert runningOnUiThread();
    }

    /**
     * @return true iff the current thread is the main (UI) thread.
     */
    public static boolean runningOnUiThread() {
        return getUiThreadHandler().getLooper() == Looper.myLooper();
    }

    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