先看一段代码
new Thread(){ Handler handler=null; public void run(){ handler =new Handler(); }; }.start();
运行之后会抛出 Can't create handler inside thread that has not called Looper.prepare()
我们来看源码
public Handler(Callback callback, boolean async) {
mLooper = Looper.myLooper(); if (mLooper == null) { throw new RuntimeException( "Can't create handler inside thread " + Thread.currentThread() + " that has not called Looper.prepare()"); } mQueue = mLooper.mQueue; mCallback = callback; mAsynchronous = async;
}
当mLooper为空时,抛出了异常,因为该线程中的Looper还没有创建
所以我们再构造Handler之前,为当前线程设置Looper对象如下
new Thread(){ Handler handler=null; public void run(){ Looper.prepare(); handler =new Handler(); Looper.loop(); }; }.start();
Looper.prepare();来创建Looper,创建了Looper也就是有了自己的消息队列,但是我们还需执行Looper.loop();启动消息循环,这样才能被执行