1、Looper类用来为一个线程开启一个消息循环
android 中新诞生的线程是没有开启消息循环的(主线程除外,主线程系统会自动为其创建 Looper 对象,开启消息循环)。Looper 对象通过 MessageQueue 来存放消息和事件。一个线程只能有一个 Looper,对应一个 MessageQueue。
2、 Looper.prepare();
在非主线程中直接 new Handler() 会报如下的错误:
java.lang.RuntimeException: Can't create handler inside thread that has not called Looper.prepare()
原因: 非主线程中默认没有创建 Looper 对象,需要先调用 Looper.prepare();
启用 Looper。
3、Looper.loop();
让 Looper 开始工作,从消息队列里取消息,处理消息。
注意: 写在 Looper.loop();
之后的代码不会被执行,这个函数内部是一个循环。
在子线程使用Handler的方法
new Thread(new Runnable() {
@Override
public void run() {
Looper.prepare();
Handler handler=new Handler();
Looper.loop();
}
}).start();