Looper.loop() android线程中的消息循环
来源:互联网 发布:路由器突然连不上网络 编辑:程序博客网 时间:2024/05/07 14:05
Looper用于封装了android线程中的消息循环,默认情况下一个线程是不存在消息循环(message loop)的,需要调用Looper.prepare()来给线程创建一个消息循环,调用Looper.loop()来使消息循环起作用,从消息队列里取消息,处理消息。
注:写在Looper.loop()之后的代码不会被立即执行,当调用后mHandler.getLooper().quit()后,loop才会中止,其后的代码才能得以运行。Looper对象通过MessageQueue来存放消息和事件。一个线程只能有一个Looper,对应一个MessageQueue。
以下是Android API中的一个典型的Looper thread实现:
//Handler不带参数的默认构造函数:new Handler(),实际上是通过Looper.myLooper()来获取当前线程中的消息循环,
//而默认情况下,线程是没有消息循环的,所以要调用 Looper.prepare()来给线程创建消息循环,然后再通过,Looper.loop()来使消息循环起作用。
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();
}
另,Activity的MainUI线程默认是有消息队列的。所以在Activity中新建Handler时,不需要先调用Looper.prepare()。
什么时候使用Looper.prepare()
参照源码:
public static final void prepare() { if (sThreadLocal.get() != null) { throw new RuntimeException("Only one Looper may be created per thread"); } sThreadLocal.set(new Looper()); }
使线程拥有自己的消息列队,主线程拥有自己的消息列队,一般线程创建时没有自己的消息列队,消息处理时就在主线程中完成,如果线程中使用Looper.prepare()和Looper.loop()创建了消息队列就可以让消息处理在该线程中完成
http://blog.csdn.net/lwuit/article/details/6796464
- Looper.loop() android线程中的消息循环
- Looper.loop() android线程中的消息循环
- Looper.loop() android线程中的消息循环
- Looper.loop() android线程中的消息循环
- Android温习:Looper.loop() android线程中的消息循环
- android 线程中创建消息循环Looper.prepare() Looper.loop()
- Android 线程 Looper.prepare()、Looper.loop()
- Android 线程 Looper.prepare()、Looper.loop()
- Android 线程 Looper.prepare()、Looper.loop();
- Android 线程 Looper.prepare()、Looper.loop();
- Android 线程 Looper.prepare()、Looper.loop() 使用
- Android 线程 Looper.prepare()、Looper.loop()
- Android 线程 Looper.prepare()、Looper.loop() Looper.prepare()和Looper.loop() —深入版
- Android面试:主线程中的Looper.loop()一直无限循环为什么不会造成ANR?(转)
- Android面试:主线程中的Looper.loop()一直无限循环为什么不会造成ANR?(转)
- android Looper线程消息通信
- HandlerThread:带消息循环(Looper)的线程
- Android中 主线程 Looper.loop() 死循环?
- OpenEjb使用笔记--让Tomcat可以部署EJB
- the power of IT (it’s not all in energy consumption
- 0-1背包问题
- poj 2533 Longest Ordered Subsequence 很水的最长递增序列
- 智能物流刻不容缓 动态数据仓库举足轻重
- Looper.loop() android线程中的消息循环
- NYT“Power, Pollution”引起西方IT界巨大反响,悖论否?
- 英语练习44 Are you having fun?
- HTTP Response Status Code -- HTTP响应代码中文详解
- 百度地图JS版本API常见问题
- 字符,字节和编码
- char、varchar、text和nchar、nvarchar、ntext的区别
- 黑客对决:东亚vs东欧 业余的不只是一点点!
- Struts2应用流程注解 .