Looper Handler MessageQueue Message 探究

时间:2023-03-09 23:38:14
Looper Handler MessageQueue Message 探究

Android消息处理的大致的原理如下:

  1.有一个消息队列,可以往队列中添加消息

  2.有一个消息循环,可以从消息队列中取出消息

Looper Handler MessageQueue Message 探究

Android系统中这些工作主要由Looper和Handler两个类来实现:

  Looper类: 有一个消息队列,封装消息循环

  Handler类: 消息的投递、消息的处理

Looper类:

  Looper的使用需先调用 Looper.prepare(),然后调用Looper.loop()开启消息循环。

     public static void prepare() {
prepare(true);
} private static void prepare(boolean quitAllowed) {
if (sThreadLocal.get() != null) {
throw new RuntimeException("Only one Looper may be created per thread");
}
sThreadLocal.set(new Looper(quitAllowed));
}     static final ThreadLocal<Looper> sThreadLocal = new ThreadLocal<Looper>();

  prepare会在调用线程的局部变量中设置一个Looper对象;

  ThreadLocal是java中线程局部变量类,有两个关键函数:

      set: 设置调用线程的局部变量

      get: 获取调用线程的局部变量

  Looper的构造函数:  

     private Looper(boolean quitAllowed) {
mQueue = new MessageQueue(quitAllowed);
mThread = Thread.currentThread();
}

  创建了一个消息队列,用于存放消息。

  Looper.loop(), myLooper()通过ThreadLocal对象获取了prepare时创建的Looper对象。loop里面是一个循环,循环从MessageQueue中取消息,然后通过Handler去处理。

  (msg.target.dispatchMessage(msg); target是一个Handler对象,后面会提到)

     public static @Nullable Looper myLooper() {
return sThreadLocal.get();
} 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.recycleUnchecked();
}
}

  Looper的作用:

  • 封装一个消息队列

  • prepare()方法把Looper对象和调用的线程绑定起来

  • 通过loop()方法处理消息队列中的消息    

Hander类:

  Handler有多个构造函数,常用的就下面几个:     

     public Handler() {
this(null, false);
} public Handler(Looper looper) {
this(looper, null, false);
} public Handler(Callback callback, boolean async) {
mLooper = Looper.myLooper();
if (mLooper == null) {
throw new RuntimeException(
"Can't create handler inside thread that has not called Looper.prepare()");
}
mQueue = mLooper.mQueue;
mCallback = callback;
mAsynchronous = async;
} public Handler(Looper looper, Callback callback, boolean async) {
mLooper = looper;
mQueue = looper.mQueue;
mCallback = callback;
mAsynchronous = async;
}

  无参构造函数,通过Looper.myLooper()获取调用线程的Looper对象; Handler提供了一个Callback的接口,参数里面的Callback在处理消息的时候会用到,如果设置了全局Callback,消息会通过这个Callback处理,如果未设置,则需重重载handlerMessage()方法来处理消息。

     public interface Callback {
public boolean handleMessage(Message msg);
}

  (1) Handler和Message ----> Handler把Message插入Looper的消息队列。

    Handler有一系列的处理消息的函数,比如:     

     public final boolean sendMessage(Message msg)
{
return sendMessageDelayed(msg, 0);
} public final boolean sendEmptyMessage(int what)
{
return sendEmptyMessageDelayed(what, 0);
} public final boolean sendEmptyMessageDelayed(int what, long delayMillis) {
Message msg = Message.obtain();
msg.what = what;
return sendMessageDelayed(msg, delayMillis);
} public final boolean sendMessageDelayed(Message msg, long delayMillis)
{
if (delayMillis < 0) {
delayMillis = 0;
}
return sendMessageAtTime(msg, SystemClock.uptimeMillis() + delayMillis);
} public boolean sendMessageAtTime(Message msg, long uptimeMillis) {
MessageQueue queue = mQueue;
if (queue == null) {
RuntimeException e = new RuntimeException(
this + " sendMessageAtTime() called with no mQueue");
Log.w("Looper", e.getMessage(), e);
return false;
}
return enqueueMessage(queue, msg, uptimeMillis);
} public final boolean sendMessageAtFrontOfQueue(Message msg) {
MessageQueue queue = mQueue;
if (queue == null) {
RuntimeException e = new RuntimeException(
this + " sendMessageAtTime() called with no mQueue");
Log.w("Looper", e.getMessage(), e);
return false;
}
return enqueueMessage(queue, msg, 0);
}

   这些都是将消息插入到Looper的消息队列,sendMessageAtFrontOfQueue()是将消息插入到消息队列的队列头,所以优先级很高。所有方法最后都是通过enqueueMessage()方法插入消息。

     private boolean enqueueMessage(MessageQueue queue, Message msg, long uptimeMillis) {
msg.target = this;
if (mAsynchronous) {
msg.setAsynchronous(true);
}
return queue.enqueueMessage(msg, uptimeMillis);
}

    msg.target = this,前面有提到,target是Handler对象,消息的处理最后都需通过这个。

  (2)Handler的消息处理

    上面的Looper.loop()方法中,不断从消息队列中提取消息,然后通过Handler的dispatchMessage()方法处理消息。

     public void dispatchMessage(Message msg) {
if (msg.callback != null) {
handleCallback(msg);
} else {
if (mCallback != null) {
if (mCallback.handleMessage(msg)) {
return;
}
}
handleMessage(msg);
}
}

     如果Message设置了callback,则通过这个callback处理,如果Message没设置callback则先通过全局callback来处理,如果都没设置,则通过handlerMessage()方法来处理。

  简单总结一下:

    Looper中有一个MessageQueue,里面存储一个个待处理的Message。

    Message中有一个Handler,这个Handler处理Message。

    转载还望注明出处:http://www.cnblogs.com/xiaojianli/p/5642380.html