Last active
December 17, 2020 13:03
-
-
Save raulccabreu/9c4a45432347b7af76ca0ad0959ae233 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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