标签:
另,Activity的MainUI线程默认是有消息队列的。所以在Activity中新建Handler时,不需要先调用Looper.prepare()。
那么遇到了有多Low的问题呢:
项目中重写了一个HandlerThread,然后定义了post方法,然后在主线程中如下实现:
AsyncHandler.post(new Runnable() {
@Override
public void run() {
try {
Looper.prepare();
// 一坨要异步执行的代码******
Looper.loop();
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
那么明眼人一看就看出问题来了 ,这代码一跑异步代码肯定执行不到啊,为啥呢,且看下prepare的实现:
/** Initialize the current thread as a looper.
* This gives you a chance to create handlers that then reference
* this looper, before actually starting the loop. Be sure to call
* {@link #loop()} after calling this method, and end it by calling
* {@link #quit()}.
*/
public static void prepare() {
prepare(true);
}
private static void prepare(boolean quitAllowed) {
if (sThreadLocal.get() != null) {
throw new RuntimeException("Only one Looper may be created per thread");
}
sThreadLocal.set(new Looper(quitAllowed));
}
So,简单,却是问题~
Android 线程 Looper.prepare()、Looper.loop() 使用
标签:
原文地址:http://blog.csdn.net/yangdeli888/article/details/44313345