Created
January 21, 2014 13:52
-
-
Save RomanIakovlev/8540439 to your computer and use it in GitHub Desktop.
On Android, this can be used to schedule callbacks back on the caller thread, if it has a Looper installed, or to the UI thread otherwise.
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
package com.example.concurrent; | |
import android.os.Handler; | |
import android.os.Looper; | |
import java.util.concurrent.Executor; | |
/** | |
* When the calling thread has a Looper installed (like the UI thread), an instance of ExecuteOnCaller will submit | |
* Runnables into the caller thread. Otherwise it will submit the Runnables to the UI thread. | |
*/ | |
public class ExecuteOnCaller implements Executor { | |
private static ThreadLocal<Handler> threadLocalHandler = new ThreadLocal<Handler>() { | |
@Override | |
protected Handler initialValue() { | |
Looper looper = Looper.myLooper(); | |
if (looper == null) | |
looper = Looper.getMainLooper(); | |
return new Handler(looper); | |
} | |
}; | |
private final Handler handler = threadLocalHandler.get(); | |
@Override | |
public void execute(Runnable command) { | |
handler.post(command); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment