Android之Looper使用

looper介绍

Looper类别用来为一个线程开启一个消息循环。

默认情况下Android中新诞生的线程是没有开启消息循环的。(主线程除外,主线程系统会自动为其创建Looper对象,开启消息循环)

Looper对象通过MessageQueue来存放消息和事件。一个线程只能有一个Looper,对应一个MessageQueue。

通常是通过Handler对象来与Looper交互的。Handler可看做是Looper的一个接口,用来向指定的Looper发送消息及定义处理方法。

常用的方法:

方法 含义
Looper.myLooper() 获取当前进程的looper对象。
Looper.getMainLooper() 用于获取主线程的Looper对象。

常见错误

在非主线程中直接new Handler()会报如下的错误:

E/AndroidRuntime( 6173): Uncaught handler: thread Thread-8 exiting due to uncaught exception
E/AndroidRuntime( 6173): java.lang.RuntimeException: Can't create handler inside thread that has not called Looper.prepare()

原因是因为非主线程中默认没有创建Looper对象,需要先调用Looper.prepare()启用Looper。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章