当在线程中创建Handler时,会报错。 因为handler源码中使用了对像。具体原因为以下转载内容:
在android 线程run方法中调用
handler = new Handler() {
public void handleMessage(Message msg) {
}
};
会报Can't create handler inside thread that has not called Looper.prepare()
这次的问题 我是在TimerTask 中调用了 handler
解决方法:只需在 handler = new Handler() 前加
Looper.prepare();即可。
原因:
查看源代码发现
new Handler()时有一段
mLooper =Looper.myLooper();
if (mLooper == null) {
throw new RuntimeException(
"Can't create handler inside thread that has not called Looper.prepare()");
}
而 Looper.myLooper();
myLooper的源代码是
public static final Looper myLooper() {
return (Looper)sThreadLocal.get();
}
只需要找到Looper中不让SThreadLocal.get();为空或者往里设置值的方法即可
就是 public static final void prepare() {
if (sThreadLocal.get() != null) {
throw new RuntimeException("Only one Looper may be created per thread");
}
sThreadLocal.set(new Looper());
}