首页 > 编程知识 正文

handle的通信机制,handler机制原理

时间:2023-05-04 18:32:56 阅读:178736 作者:2548

Handler的作用是将消息对象发送到消息队列,同时将自己的引用分配给消息# target。

Looper的作用是从消息队列中检索消息对象并将其传递给handler # dispatch消息(消息)方法。 这里,主要需要调用handle message (handle message )方法,而不是调用handler # handle message (handle消息)

排序条件是消息# when字段,表示由消息队列#枚举消息(消息,长消息)方法设置的相对时间。

Looper包含ThreadLocal类型的sThreadLocal静态字段,Looper通过其get和set方法赋值和取值。

在子线程中创建的Handler对象直接导致程序崩溃,提示的错误竟然是can’tcreatehandlerinsidethreadthasnotcalledlooper.prepare ()

如何在子线程上获取当前线程的Looper

Looper.myLooper (

在任意线程上获取主线程的Looper时

Looper.getMainLooper (

必须首先通过调用Looper.prepare ()启用Looper。

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

解析源代码:

publicbooleansendmessageattime (消息msg,长更新时间millis ) {

消息队列=队列;

if (queue==空值) {

runtimeexceptione=newruntimeexception (

this ' sendMessageAtTime () called with no mQueue );

log.w(「looper”,e.getMessage ),e );

返回假;

}

returnenqueuemessage(queue,msg,uptimeMillis );

}

privatebooleanenqueuemessage (消息队列、消息msg、长更新时间millis ) {

msg.target=this;

机器(if ) {

MSG.setasynchronous(true;

}

returnqueue.enqueuemessage(msg,uptimeMillis;

}

publicfinalclassmessageimplementsparcelable {

//…

汉德勒目标;

}

分选机的结构

公共硬件(callback callback,boolean async ) {

mLooper = Looper.myLooper();

if (m looper==空) {

throw new RuntimeException (

“can’tcreatehandlerinsidethreadthasnotcalledlooper.prepare (

}

mQueue = mLooper.mQueue;

mCallback=callback;

mAsynchronous=async;

}

Looper到底是什么样的对手,有这样的身份,在Handler的机制中发挥着这样的作用呢? 让我们看看myLooper ()方法:

公共静态@ nullableloopermylooper {

return sThreadLocal.get (;

}

myLooper ) )方法直接从sThreadLocal对象检索Looper。 sThreadLocal是ThreadLocal类的对象,ThreadLocal类简单地说,他存储的对象是线程专用的。

ThreadLocal类说白了就是通过他存储的对象是线程私有的

Looper对象已用ActivityThread的Main方法初始化。

链表存储消息

publicfinalclassactivitythread {

//…

publicstaticvoidmain (string [ ] args ) {

Looper.prepareMainLooper (;

}

//…

}

版权声明:该文观点仅代表作者本人。处理文章:请发送邮件至 三1五14八八95#扣扣.com 举报,一经查实,本站将立刻删除。