Creates new HandlerThread and returns new Handler associated with this thread. - Android java.lang

Android examples for java.lang:Thread

Description

Creates new HandlerThread and returns new Handler associated with this thread.

Demo Code


import android.os.Handler;
import android.os.HandlerThread;
import android.os.Looper;
import android.os.Message;
import android.os.Process;
import java.util.concurrent.atomic.AtomicInteger;

public class Main{
    private static AtomicInteger sCounter;
    /**/*from  w w  w.  j a v a  2 s  . co m*/
     * @see #newThread(String, int, Handler.Callback)
     */
    public static Handler newThread(Handler.Callback callback) {
        return newThread(null, Process.THREAD_PRIORITY_LOWEST, callback);
    }
    /**
     * @see #newThread(String, int, Handler.Callback)
     */
    public static Handler newThread(String name, Handler.Callback callback) {
        return newThread(name, Process.THREAD_PRIORITY_LOWEST, callback);
    }
    /**
     * Creates new {@link HandlerThread} and returns new {@link Handler} associated with this thread.
     *
     * @param name     name of thread, in case of null - the default name will be generated
     * @param priority one of constants from {@link android.os.Process}
     * @param callback message handling callback, may be null
     * @return new instance
     */
    public static Handler newThread(String name, int priority,
            Handler.Callback callback) {
        HandlerThread thread = new HandlerThread(name != null ? name
                : newName(), priority);
        thread.start();
        return new Handler(thread.getLooper(), callback);
    }
    private static String newName() {
        AtomicInteger counter = sCounter;
        if (counter == null) {
            counter = new AtomicInteger();
            sCounter = counter;
        }

        return ThreadUtils.class.getSimpleName() + '-'
                + counter.incrementAndGet();
    }
}

Related Tutorials