首页 > 其他 > 详细

Looper&Handler

时间:2019-12-18 23:34:11      阅读:101      评论:0      收藏:0      [点我收藏+]

Looper类:封装消息循环,并有一个消息队列(关键)

Handler类:封装了消息投递,消息处理等接口

Looper.perpare()

  1.    sThreadLocal.set(new Looper)会在调用线程得局部变量中设置一个Looper(1.构造一个消息队列2.获得当前线程)

  new Looper() {

  mQueue = new MessageQueue();

  mThread = Thread.currentThread();

}

Looper.looper() 

  1.取出prepare中保存得looper中得mQueue

  2.while循环从mQueue中取出消息

  3.消息中有个target。类型是Handler,调用handler得dispatchMessage,处理消息

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
final Printer logging = me.mLogging;
if (logging != null) {
logging.println(">>>>> Dispatching to " + msg.target + " " +
msg.callback + ": " + msg.what);
}

final long traceTag = me.mTraceTag;
if (traceTag != 0 && Trace.isTagEnabled(traceTag)) {
Trace.traceBegin(traceTag, msg.target.getTraceName(msg));
}
try {
msg.target.dispatchMessage(msg);
} finally {
if (traceTag != 0) {
Trace.traceEnd(traceTag);
}
}

 

Handler:

  有一个消息队列

  有一个looper(可以直接获取当前线程得looper,也可以由外部传入)

  有一个callback

有四个构造函数

sengMeassage,将Message得target设置成handler自己

dispatchMessage(msg)(设置消息处理得优先级,先Meassage自己得callback,后设置得callback,最后交给子类,handMeassage())

Looper&Handler

原文:https://www.cnblogs.com/jobs1/p/12063503.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!