美文网首页
Handler,Looper,Message 之间的关系

Handler,Looper,Message 之间的关系

作者: 瀚海网虫 | 来源:发表于2019-03-12 22:50 被阅读0次
image.png

带着两个问题看源码:

  1. 一个线程可以有几个Looper?
  2. 一个线程可以有几个Handler?

1. Handler

/** Initialize the current thread as a looper.
     * This gives you a chance to create handlers that then reference
     * this looper, before actually starting the loop. Be sure to call
     * {@link #loop()} after calling this method, and end it by calling
     * {@link #quit()}.
     */
   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));
   }

Handler的prepare方法会把当前Thread 变成一个Looper。

成员变量

   static final ThreadLocal<Looper> sThreadLocal = new ThreadLocal<Looper>();
   private static Looper sMainLooper;  // guarded by Looper.class

   final MessageQueue mQueue;
   final Thread mThread;

sMainLooper 标识主线程Looper

   public static void prepareMainLooper() {
       prepare(false);
       synchronized (Looper.class) {
           if (sMainLooper != null) {
               throw new IllegalStateException("The main Looper has already been prepared.");
           }
           sMainLooper = myLooper();
       }
   }

该方法,会被Android 程序主入口,ActivityThread及SystemServer调用

为什么Looper 使用前要先prepare?

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

/**
    * Run the message queue in this thread. Be sure to call
    * {@link #quit()} to end the loop.
    */
   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);
               }
           }

           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完成初始化,每个Thread只能绑定一个Looper,不能重复创建。
Looper中死循环不断的处理队列中的Message。

为什么代码里,可以不用初始化Looper,直接使用 myHandler.sendMessage(message); 发送消息,然后在自定义的Handler的handleMessage(Message msg)中接收并处理呢?

这是因为这种场景下,当前线上是主线程,所以可以主线程mainThread 的mainLooper 系统已经默认初始化了。

2. Handler

当我们调用new Handler()时(无参构造子),会调用到

 public Handler(Callback callback, boolean async) {
       if (FIND_POTENTIAL_LEAKS) {
           final Class<? extends Handler> klass = getClass();
           if ((klass.isAnonymousClass() || klass.isMemberClass() || klass.isLocalClass()) &&
                   (klass.getModifiers() & Modifier.STATIC) == 0) {
               Log.w(TAG, "The following Handler class should be static or leaks might occur: " +
                   klass.getCanonicalName());
           }
       }

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

callback = null,async = false。 可以看出此时Handler 关联了一个当前线程的Looper。

handler的作用:
There are two main uses for a Handler:
(1) to schedule messages and runnables to be executed as some point in the future;
(2) to enqueue an action to be performed on a different thread than your own.

  1. 调度message ,runnable 延后执行

2.切换线程执行任务

3. Message

Looper.loop()方法中,for循环不停取出Message,然后调用msg.target.dispatchMessage(msg)方法,用来分发传递进Looper的Message。
msg 为Message,target 为Handler

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

没有特殊设计都会执行到 handleMessage(msg);即执行用户设定的分发逻辑中。
常见的用法:

int  MSG_START = 1;
private Handler mHandler = new Handler() {
       public void handleMessage(Message msg) {
           switch(msg.what){
               ......
           }
     }
}
class MyThread extends Thread {
       @Override
       public void run() {
         mHandler.sendEmptyMessage(MSG_START);
         //或者 
        Message msg = new Message();
        msg.what = MSG_DOWN_SUCCESS;
         //msg.arg1 = 111;  可以设置arg1、arg2、obj等参数
         //msg.arg2 = 222;
        // msg.obj = obj;
         mHandler.sendMessage(msg);
   }
}

Handler的实现中适及以下对象:
1、Handler本身:负责消息的发送和处理
2、Message:消息对象
3、MessageQueue:消息队列(用于存放消息对象的数据结构)是一个典型的生产者、消费者模式( enqueueMessage()入队,next()出队 )
4、Looper:消息队列的处理者(用于轮询消息队列的消息对象,取出后回调handler的dispatchMessage进行消息的分发,dispatchMessage方法会回调handleMessage方法把消息传入,由Handler的实现类来处理)

Message对象的内部实现是链表,最大长度是50,用于缓存消息对象,达到重复利用消息对象的目的,以减少消息对象的创建(享元模式),所以通常我们要使用obtainMessage方法来获取消息对象

安全:Handler的消息处理机制是线程安全的

关系:创建Handler时会创建Looper,Looper对象的创建又创建了MessageQueue

4 回答开头的两个小问题

4.1一个线程可以有几个Looper?

只能有一个,注意Looper.prepare()方法的提示“Only one Looper may be created per thread”! 这是系统源码来保障的。

4.2 一个线程可以有几个Handler

没有限制,但是他们使用的消息队列都是同一个,也就是同一个Looper。货物再多,传送带只有一条。

同一个Looper是怎么区分不同的Handler的,换句话说,不同的Handler是怎么做到处理自己发出的消息的。
源码在Handler的sendMessage(),最终调用
Handler.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;,这里就是将当前的Handler赋值给Message对象的target字段,这样在处理消息的时候通过msg.target就可以区分开不同的Handler了。
处理的方法在Looper.loop中:
依次取出Msg 过程

Looper.loop()
...
msg.target.dispatchMessage(msg);
...

在Message的obtain的各种重载方法里面也有对target的赋值

相关文章

网友评论

      本文标题:Handler,Looper,Message 之间的关系

      本文链接:https://www.haomeiwen.com/subject/fmtfpqtx.html