定义一个包含主线程looper的线程池
public class MainExecutor extends AbstractExecutorService {
private final Handler mHandler;
public MainExecutor(Looper looper) {
mHandler = new Handler(looper);
}
public Handler getHandler() {
return mHandler;
}
@Override
public void execute(Runnable runnable) {
if (getHandler().getLooper() == Looper.myLooper()) {
runnable.run();
} else {
getHandler().post(runnable);
}
}
/**
* Same as execute, but never runs the action inline.
*/
public void post(Runnable runnable) {
getHandler().post(runnable);
}
...
}
在工具类中将他定义为findl
public class Executors {
/**
* Returns the executor for running tasks on the main thread.
*/
public static final MainExecutor MAIN_EXECUTOR =
new MainExecutor(Looper.getMainLooper());
}
使用方法
MAIN_EXECUTOR.execute(new Runnable() {
@Override
public void run() {
//执行代码
}
});