handler
来源:互联网 发布:文章网站数据库设计 编辑:程序博客网 时间:2024/06/03 14:20
1:在主线程中定义一个handler
2:在子线程中用handler发消息
handler.sendmMessage(msg);
msg 有obj what属性
3:重写handlemessage()方法,在方法里更新UI
原理:在子线程中handler发送了一条消息,这条消息进入到主线程中的messagequeue中就是主线程的消息队列.而在主线程创建的时候,Looper消息循环器也创建,并实时监听消息队列中的消息,一旦发现消息,调用handler的handlemessage(),执行完成后消息消失.
在Looper中有这样一个方法:
public static void loop() { final Looper me = myLooper(); if (me == null) { throw new RuntimeException("No Looper; Looper.prepare() wasn't called on this thread."); } final MessageQueue queue = me.mQueue; // Make sure the identity of this thread is that of the local process, // and keep track of what that identity token actually is. Binder.clearCallingIdentity(); final long ident = Binder.clearCallingIdentity(); for (;;) { Message msg = queue.next(); // might block if (msg == null) { // No message indicates that the message queue is quitting. return; } // This must be in a local variable, in case a UI event sets the logger Printer logging = me.mLogging; if (logging != null) { logging.println(">>>>> Dispatching to " + msg.target + " " + msg.callback + ": " + msg.what); } msg.target.dispatchMessage(msg); if (logging != null) { logging.println("<<<<< Finished to " + msg.target + " " + msg.callback); } // Make sure that during the course of dispatching the // identity of the thread wasn't corrupted. final long newIdent = Binder.clearCallingIdentity(); if (ident != newIdent) { Log.wtf(TAG, "Thread identity changed from 0x" + Long.toHexString(ident) + " to 0x" + Long.toHexString(newIdent) + " while dispatching to " + msg.target.getClass().getName() + " " + msg.callback + " what=" + msg.what); } msg.recycle(); } }其中msg.target.dispatchMessage(msg);的target是handler类型,也就是说这行代码执行的是handler下的dispatchMessage(msg)方法,代码如下]
public void dispatchMessage(Message msg) { if (msg.callback != null) { handleCallback(msg); } else { if (mCallback != null) { if (mCallback.handleMessage(msg)) { return; } } handleMessage(msg); } }可知在该方法中调用了handlermessage()方法,这也是必须重写的原因.
阅读全文
0 0
- Handler
- Handler
- Handler
- handler
- handler
- Handler
- Handler
- Handler
- Handler
- Handler
- Handler
- handler
- Handler
- handler
- handler
- Handler
- Handler
- Handler
- 文章标题
- java 抽象类和接口
- CoordinatorLayout之初步认识
- 移动硬盘H盘损坏文件系统变成RAW如何恢复
- 大数据(二十八)HBASE【Hbase 体系架构】
- handler
- 通用Mapper和PageHelper插件 学习笔记
- 用MyEclipse连接URL解析json对象,并将数据以表格形式写入PostgreSQL数据库
- centos刚部署好就遇到Jquery file upload. Failed to resize image (original thumbnail)
- day7上
- QSGMII
- RxJava的基本使用
- 中国国内采购平台品牌排行
- 解决@responseBody返回数据乱码问题