Run the runnable on a non-UI thread - Android java.lang

Android examples for java.lang:Thread

Description

Run the runnable on a non-UI thread

Demo Code

/**//w w w  .  j a v  a  2  s  . com
 * Various utilities functions for NCA
 * 
 * @author sonal.agarwal
 * 
 * @Copyright (c) 2014 Nymi Inc. All rights reserved.
 */
import java.util.concurrent.ScheduledThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import android.content.Context;
import android.content.res.Configuration;
import android.graphics.Typeface;
import android.os.Build;
import android.os.Handler;
import android.os.Looper;
import android.os.Vibrator;
import android.util.Log;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;

public class Main{
    protected static ScheduledThreadPoolExecutor executor;
    /**
     * Run the runnable on a non-UI thread
     * 
     * @param runnable
     *            the runnable
     * @return a ScheduledFuture to managing the task
     */
    public static ScheduledTask runTask(Runnable runnable) {
        return runTaskAfterMillies(runnable, 0);
    }
    /**
     * Run a task on a non-UI thread after the delay
     * 
     * @param runnable
     *            the runnable
     * @param delay
     *            the delay to run the task, it is in milliseconds
     * @return a ScheduledFuture to managing the task
     */
    public static ScheduledTask runTaskAfterMillies(Runnable runnable,
            long delay) {
        if (executor == null) {
            synchronized (SystemUtils.class) {
                if (executor == null) {
                    executor = new ScheduledThreadPoolExecutor(2);
                }
            }
        }

        if (delay > 0) {
            return new ScheduledTask(executor.schedule(runnable, delay,
                    TimeUnit.MILLISECONDS), runnable);
        } else {
            executor.execute(runnable);
            return null;
        }
    }
}

Related Tutorials