最近在线程中使用handler例如:
final Handler mhandler = new Handler();
new Thread(new Runnable() {
@Override
public void run() {
Looper.prepare();
mhandler.post(new Runnable() {
@Override
public void run() {
// code
}
});
}
});
会遇到这两个问题:
线程中不加Looper.prepare(); 会报错:
Can't create handler inside thread that has not called Looper.prepare()
线程中加入Looper.prepare();还会报错:
java.lang.RuntimeException: Only one Looper may be created per thread
到底我改加不加,要怎么加????
解决方法:
方法一:
在主线程中创建Handler(不用添加Looper.prepare())。
方法二:
如果Handler是在子线程中创建的,那就handler在创建的时候,传入context.getMainLooper()参数(不用添加Looper.prepare())
Handler mhandler = new Handler(context.getMainLooper());