Android中Looper简介

(2011-07-18 09:01:22) 转载
标签:

杂谈

分类:Android学习
1) Looper类别用来为一个线程开启一个消息循环。默认情况下Android中新诞生的线程是没有开启消息循环的。(主线程除外,主线程系统会自动为其创建Looper对象,开启消息循环)

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

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

默认情况下Handler会与其被定义时所在线程的Looper绑定,比如,在主线程中定义,其是与主线程的Looper绑定。

mainHandler = new Handler() 等价于new Handler(Looper.myLooper()).

Looper.myLooper():Return the Looper object associated with the current thread 获取当前进程的looper对象。

还有一个类似的 Looper.getMainLooper() 用于获取主线程的Looper对象。

(3) 在非主线程中直接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。

(4) Looper.loop(); 让Looper开始工作,从消息队列里取消息,处理消息。

注意:写在Looper.loop()之后的代码不会被执行,这个函数内部应该是一个循环,当调用mHandler.getLooper().quit()后,loop才会中止,其后的代码才能得以运行。

(5) 基于以上知识,可实现主线程给子线程(非主线程)发送消息。

把下面例子中的mHandler声明成类成员,在主线程通过mHandler发送消息即可。

(6) Android官方文档中Looper的介绍:

Class used to run a message loop for a thread. Threads by default do not have a message loop associated with them; to create one, callprepare()in the thread that is to run the loop, and thenloop()to have it process messages until the loop is stopped.

Most interaction with a message loop is through theHandlerclass.

This is a typical example of the implementation of a Looper thread, using the separation ofprepare()andloop()to create an initial Handler to communicate with the Looper.

class LooperThread extends Thread {
public Handler mHandler;

public void run() {
Looper.prepare();

mHandler = new Handler() {
public void handleMessage(Message msg) {
// process incoming messages here
}
};

Looper.loop();
}
}

更多相关文章

  1. 解析 ViewTreeObserver 源码,体会观察者模式、Android消息传递(下)
  2. Android 开发艺术探索笔记(十五) 之 Android 的线程和线程池
  3. android消息推送-XMPP
  4. 使用GCM服务(Google Cloud Messaging)实现Android消息推送
  5. Android 事件处理基于Handler 消息处理
  6. Android学习笔记Android线程模型解析
  7. [置顶] Android消息异步机制(ThreadLocal、MessageQueue、Looper

随机推荐

  1. Android---多线程的处理
  2. AndroidUI设计之布局-详细解析布局实现
  3. Android(安卓)开发之旅:又见Hello World!
  4. Android读取手机通讯录实现
  5. Android应用程序的自动更新升级(自身升级
  6. Android(安卓)SDK Document 框架导读的翻
  7. Android:Camera2开发详解(上):实现预览、
  8. 在任意位置获取应用程序Context
  9. Android直播推流学习
  10. Windows环境下Android(安卓)NDK环境搭建