Looper&Handler

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);
}
}

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

Handler:

  有一个消息队列

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

  有一个callback

有四个构造函数

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

posted @ 2019-12-18 20:31  无解的不等式  阅读(362)  评论(0编辑  收藏  举报