Handler系列-怎么放入MessageQueue

链表:根据when从小到大排列

1.MessageQueue

public final class MessageQueue {
    Message mMessages; //消息链表表头
}

2.Message

public final class Message implements Parcelable {
    /*package*/ long when;
    /*package*/ Message next;
}

3.sendMessageDelayed流程

  • delay加上SystemClock.uptimeMillis() 
public class Handler {
    public final boolean sendMessageDelayed(Message msg, long delayMillis){
        if (delayMillis < 0) {
            delayMillis = 0;
        }
        //delayMillis这里会加上SystemClock.uptimeMillis(),变成when
        return sendMessageAtTime(msg, SystemClock.uptimeMillis() + delayMillis);
    }


    public boolean sendMessageAtTime(Message msg, long uptimeMillis) {
        MessageQueue queue = mQueue;
        return enqueueMessage(queue, msg, uptimeMillis);
    }

    
    private boolean enqueueMessage(MessageQueue queue, Message msg, long uptimeMillis) {
        msg.target = this; //赋值Message的target
        if (mAsynchronous) {
            msg.setAsynchronous(true);
        }
        return queue.enqueueMessage(msg, uptimeMillis);
    }
}
  • 通过链表头mMessages和when,找到msg该在的位置(根据when从小到大排列)
public final class MessageQueue {
    boolean enqueueMessage(Message msg, long when) {
        synchronized (this) {
            msg.markInUse();
            msg.when = when; //赋值Message的when
            Message p = mMessages; //表头赋值给p
            boolean needWake;
            if (p == null || when == 0 || when < p.when) {
                //链表为null或者when为0或者when的值比表头的when小
                // New head, wake up the event queue if blocked.
                msg.next = p;
                mMessages = msg; //msg成为表头
                needWake = mBlocked;
            } else {
                Message prev;
                for (;;) {
                    prev = p;
                    p = p.next;
                    if (p == null || when < p.when) {//找到该放的位置了
                        break;
                    }
                }
                //插入msg:prev msg p
                msg.next = p; 
                prev.next = msg;
            }

            // We can assume mPtr != 0 because mQuitting is false.
            if (needWake) {
                nativeWake(mPtr);
            }
        }
        return true;
    }
}

你可能感兴趣的:(Android,Android,Handler)