美文网首页
handler-发送消息

handler-发送消息

作者: lvcs | 来源:发表于2019-08-23 16:37 被阅读0次

    1.客户端使用

    示例:(注意:匿名内部类将持有外部引用,下面代码不可做实际使用)

    //MainActivity
    private Handler mHandler = new Handler(){
        @Override
        public void handleMessage(Message msg){
            mTextView.setText(msg.arg1+"");
        };
    };
    new Thread(){
        @Override
        public void run() {
           Message message = new Message();
           message.arg1 = 1;
           mHandler.sendMessage(message);
        }
    }.start();
    

    2.创建Handler

    public class Handler {
        //回调
        public interface Callback {
        public boolean handleMessage(Message msg);
    }  
      
    public Handler() {
        this(null, false);
    } 
    
    //async如果为true则为异步消息(默认同步)
    public Handler(Callback callback, boolean async) {
        if (FIND_POTENTIAL_LEAKS) {
            final Class<? extends Handler> klass = getClass();
            //Handler类应该是静态的,否则可能会发生泄漏
            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());
            }
        }
        //绑定当前线程的Looper
        mLooper = Looper.myLooper();
    ......
        //绑定该Looper的消息队列
        mQueue = mLooper.mQueue;
        //绑定回调
        mCallback = callback;
        //是否为异步消息
        mAsynchronous = async;
      }
    
      //在Looper.loop()中调用此方法回调  
      public void dispatchMessage(Message msg) {
        //handler处理三种消息的顺序msg.callback,handler.mCallback ,handleMessage
        //在调用post系列方法时,封装成的Message的callback属性就是post传入的Runnable对象
        if (msg.callback != null) {
            handleCallback(msg);
        } else {
            // mCallback是Handler内部定义的Callback接口类型,在Handler构造方法时可以当作参数传入
            if (mCallback != null) {
                if (mCallback.handleMessage(msg)) {
                    return;
                }
            }
             //通过Handler自己的handleMessage()方法处理消息
            handleMessage(msg);
        }
      }    
    
      //发送延时消息
      public final boolean postDelayed(Runnable r, long delayMillis)
      {
            return sendMessageDelayed(getPostMessage(r), delayMillis);
      }
      //发送普通消息
      public final boolean sendMessage(Message msg)
      {
            return sendMessageDelayed(msg, 0);
      }
    
      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);
      }
      
      private boolean enqueueMessage(MessageQueue queue, Message msg, long uptimeMillis) {
            //将target 设置为自己
            msg.target = this;
            //是否为异步消息(同步障碍消息)
            if (mAsynchronous) {
                msg.setAsynchronous(true);
            }
            //消息入队
            return queue.enqueueMessage(msg, uptimeMillis);
       }
    }
    

    3.创建Message

    //Message 
    public final class Message implements Parcelable {
      public int what;
      public int arg1;
      public int arg2;
      public Object obj;
      public Messenger replyTo;
      //Bundle 数据类型
      Bundle data;
      Handler target;
      Runnable callback;
      //单链表结构
      Message next;
      //链表的当前长度
      private static int sPoolSize = 0;
      //在队列中的Message最大数量
      private static final int MAX_POOL_SIZE = 50;
      public Message() {
      }
      //获取Message对象
      //如果为空就新new一个对象,如果不为空就返回sPool并把sPool指向链表的下一个元素,同时sPoolSize-1
      public static Message obtain() {
        synchronized (sPoolSync) {
            if (sPool != null) {
                Message m = sPool;
                sPool = m.next;
                m.next = null;
                m.flags = 0; 
                sPoolSize--;
                return m;
            }
        }
        return new Message();
    }
    //Looper.loop() 最后会调用此方法
    void recycleUnchecked() {
        //重置信息
        flags = FLAG_IN_USE;
        what = 0;
        arg1 = 0;
        arg2 = 0;
        obj = null;
        replyTo = null;
        sendingUid = -1;
        when = 0;
        target = null;
        callback = null;
        data = null;
    
        synchronized (sPoolSync) {
            //当前pool中的Message还没有超过MAX_POOL_SIZE时
            //将消息添加到链表中,这里实现了pool添加Message的操作
            if (sPoolSize < MAX_POOL_SIZE) {
                next = sPool;
                sPool = this;
                sPoolSize++;
            }
        }
     }
    }
    

    4.Handler.enqueueMessage()

    public final boolean sendMessage(Message msg)
    {
        return sendMessageDelayed(msg, 0);
    }
    
    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);
    }
    
    private boolean enqueueMessage(MessageQueue queue, Message msg, long uptimeMillis) {
        //通过Handler向MessageQueue发送的Message都将其target成员指向了Handler自己,也
        //就意味着该消息后续的处理将由Handler自己来接管
        msg.target = this;
        if (mAsynchronous) {
            msg.setAsynchronous(true);
        }
        return queue.enqueueMessage(msg, uptimeMillis);
    }
    

    5.MessageQueue.enqueueMessage()

    //MessageQueue
    boolean enqueueMessage(Message msg, long when) {
    
        //我们通过Handler发送的普通消息的target是不可能为null的。所以消息队列中如果存在target为null的消息,
        //只能是通过postSyncBarrier插入的同步障碍消息
        if (msg.target == null) {
            throw new IllegalArgumentException("Message must have a target.");
        }
        if (msg.isInUse()) {
            throw new IllegalStateException(msg + " This message is already in use.");
        }
    
        synchronized (this) {
             //如果当前消息循环已经结束,直接退出
            if (mQuitting) {
                IllegalStateException e = new IllegalStateException(
                        msg.target + " sending message to a Handler on a dead thread");
                Log.w(TAG, e.getMessage(), e);
                msg.recycle();
                return false;
            }
    
            msg.markInUse();
            //消息建立的时间(如果为延时消息则需加上延时时间)
            msg.when = when;
            Message p = mMessages;//队列的头部消息
            boolean needWake;
            //如果该消息队列目前为空,或者通过sendMessageAtFrontOfQueue接口调用传进来的,
            //或者msg的处理时间点在消息队列队头的消息的处理时间点之前,则将msg插入队头*
            if (p == null || when == 0 || when < p.when) {
                //放入队列头部
                //如果队列中没有消息,或者当前进入的消息比消息队列中的消息等待时间短
                msg.next = p;
                mMessages = msg;
                needWake = mBlocked;
            } else {
                //插入队列中
                //判断唤醒条件,只有当前消息队列队头的消息为障碍消息(判断条件中正是通过target==null来断定消息是否是障碍消息)
                //且当前插入的消息为异步消息,并且msg是消息队列中的最早的异步消息时,才需要唤醒消息队列
                needWake = mBlocked && p.target == null && msg.isAsynchronous();
                Message prev;
                //循环遍历消息队列,把当前进入的消息放入合适的位置(比较等待时间)
                for (;;) {
                    prev = p;
                    p = p.next;
                   //遍历消息队列并按消息执行时间先后顺序查找新消息合适的插入位置
                   //注意延时消息如果未到时间继续等待入队
                    if (p == null || when < p.when) {
                        break;
                    }
                    if (needWake && p.isAsynchronous()) {
                        needWake = false;
                    }
                }
                //新消息插入消息队列中,可以看到就是改变Message中next成员的指向,将新消息接入到消息队列链表中。
                msg.next = p; 
                prev.next = msg;
            }
    
             //调用nativeWake,以触发nativePollOnce函数结束等待
            if (needWake) {
                //如果需要唤醒,则调用该方法在Native层唤醒
                nativeWake(mPtr);
            }
        }
        return true;
    }
    

    相关文章

      网友评论

          本文标题:handler-发送消息

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