Skip to content

Instantly share code, notes, and snippets.

@raulccabreu
Last active December 17, 2020 13:03
Show Gist options
  • Save raulccabreu/9c4a45432347b7af76ca0ad0959ae233 to your computer and use it in GitHub Desktop.
Save raulccabreu/9c4a45432347b7af76ca0ad0959ae233 to your computer and use it in GitHub Desktop.
import android.os.Handler;
import android.os.Looper;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public final class ThreadUtils {
private static volatile Handler sMainThreadHandler;
private static volatile ExecutorService sSingleThreadExecutor;
private ThreadUtils() {
}
/**
* Returns a shared UI thread handler.
*/
private static Handler getMainThreadHandler() {
if (sMainThreadHandler == null) {
sMainThreadHandler = new Handler(Looper.getMainLooper());
}
return sMainThreadHandler;
}
public static void toBackground(Runnable runnable) {
if (sSingleThreadExecutor == null) {
sSingleThreadExecutor = Executors.newSingleThreadExecutor();
}
sSingleThreadExecutor.execute(runnable);
}
public static void toMain(Runnable runnable) {
getMainThreadHandler().post(runnable);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment