Handler

Handler

  1.callBack 是一个接口,里面是handlerMessage

  2.hadlerMessage是一个空方法,子类可实现,可不实现;对于抽象方法,如果子类是非抽象类,则必须实现父类中所有抽象方法,如果是抽象类,则可不实现

  3.handler中的方法大概有这么几种,

    1.obtainMessage,其实是调用的Message的obtain函数

    2.sendMessage 和postMessage,以及在构造函数中传入callback处理消息

    3.hasMessage,hasCallback

    4.removeMessage,removerCallBack

Message

  1.Message实现了Parcelable,

  2.Message 主要就是Obtain方法,因为handler里面的obtain也是调用的这里的obtain,

  3.Max_pool_size 是50,猜测是message pool值的大小

  4.Message也是一个final类

MessageQueue 消息队列,

  1.是一个Final类,不可被继承

  2.idle静止状态,设备不充电且屏幕关闭的情况下,会逐渐进入静止状态,

Looper:

  里面有一个ThreadLocal

  Looper也是一个final类

 

流程分析:

  1.创建handler,一般是无参构造,然后重写handleMessage方法

 

  2.发送消息,以sendEmptyMessage为例,sendEmptyMessage 会调用

public final boolean sendEmptyMessage(int what)
    {
      //调用sendEmptyMessageDelayed()函数,然后延时设置为0
return sendEmptyMessageDelayed(what, 0); }

然后接着看

public final boolean sendEmptyMessageDelayed(int what, long delayMillis) {
        Message msg = Message.obtain();
        msg.what = what;
        return sendMessageDelayed(msg, delayMillis);
    }

获取一个message对象之后,sendMessageDelayed

public final boolean sendMessageDelayed(Message msg, long delayMillis)
    {
        if (delayMillis < 0) {
            delayMillis = 0;
        }
        return sendMessageAtTime(msg, SystemClock.uptimeMillis() + delayMillis);
    }

这里是是调用了,sendMessageAtTime ,SystemClock.uptimeMillis是自从开机,除了手机深度睡眠之外,一直增加的数字,

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

这里赋值了一个Messagequeue,

 public Handler(Callback callback, boolean async) {
       ...
        mLooper = Looper.myLooper();
        ....
        mQueue = mLooper.mQueue;
mCallback
= callback; mAsynchronous = async; }

在构造函数里面获取了Looper轮询器,然后根据轮询器又获取了消息队列,handler的构造方法可以分为两类,一类是使用默认创建,最终都会调用到上面这个构造方法,另一类就是下面这种了,指定looper,指定callback,指定是否异步,handler默认是同步的:

 public Handler(Looper looper, Callback callback, boolean async) {
        mLooper = looper;
        mQueue = looper.mQueue;
        mCallback = callback;
        mAsynchronous = async;
    }

接下来看Looper.myLooper(),因为是通过looper获取的messagequeue,

public static @Nullable Looper myLooper() {
        return sThreadLocal.get();
    }

sThreadLocal是一个looper的ThreadLocal,所以这里可以看到,每一个handler都有自己的looper,虽然都是looper,但之间并不影响。然后我们再看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));
    }

就是在threadlocal中加入了这样一个变量。因为mainThread已经存在一个looper,所以在mainthread中不用调用looper.prepare(),而在子线程中需要去调用looper.prepare(),而且与主线程中不同的是,子线程的looper还是可以退出的,quitAllowed,接下来,我们看

messageQueue,在handler的构造函数中看到mQueue = looper.mQeue 可以去看由此可知,每个looper带有一个消息队列,也就是handler之间的messageQueue不冲突。

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

在looper的构造函数中,new 了一个messageQueue,所以由上面的流程可以看出,一个创建一个handler的之前,需要创建了一个looper,looper创建是调用prepare方法,创建looper的时候就附带创建了消息队列。最主要的是looper的保存是通过threadlocal保证looper各个handelr之间互不影响。

上面分析知道,发送消息,最终都会调用sendMessageAtTime, time的计算有systemClock.uptime+delaytime计算而来,接下来就是enqueuMessage(),这是handler里面的

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

可以看出,调用了队列的enqueuemessage,队列的

boolean enqueueMessage(Message msg, long when) {
        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;
            if (p == null || when == 0 || when < p.when) {
                // New head, wake up the event queue if blocked.
                msg.next = p;
                mMessages = msg;
                needWake = mBlocked;
            } else {
                // Inserted within the middle of the queue.  Usually we don't have to wake
                // up the event queue unless there is a barrier at the head of the queue
                // and the message is the earliest asynchronous message in the queue.
                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;
                    }
                }
                msg.next = p; // invariant: p == prev.next
                prev.next = msg;
            }

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

 msg.when = when;
            Message p = mMessages;
            boolean needWake;
            if (p == null || when == 0 || when < p.when) {
                // New head, wake up the event queue if blocked.
                msg.next = p;
                mMessages = msg;
                needWake = mBlocked;

可知,当前没有消息或者没有延时,或者插入的消息要比当前的消息先执行,插入的消息的next指向当前的消息,下面接着看,不符合上述三个条件的插入

} else {
                // Inserted within the middle of the queue.  Usually we don't have to wake
                // up the event queue unless there is a barrier at the head of the queue
                // and the message is the earliest asynchronous message in the queue.
                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;
                    }
                }
                msg.next = p; // invariant: p == prev.next
                prev.next = msg;
            }

先声明一个prev变量,然后是一个死循环,主要看这里

 if (p == null || when < p.when) {
                        break;
                    }

如果消息队列下面没有消息了,或者,要插入的消息比当前的消息先执行,就将消息插入这个位置:

  msg.next = p; // invariant: p == prev.next
                prev.next = msg;

插入的消息next指向p,上一个消息指向插入的消息,这里注意,插入消息是一个synchornize操作。消息插入完了,剩下就是执行操作:我们所知的在主线程中创建了looper,具体来讲就是在ActivityThread。java里面实现的,以下是ActivityThread中looper的实现:

 final Looper mLooper = Looper.myLooper();

声明一个成员变量,mLooper,然后看main函数:

 public static void main(String[] args) {
        Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, "ActivityThreadMain");
        SamplingProfilerIntegration.start();

        // CloseGuard defaults to true and can be quite spammy.  We
        // disable it here, but selectively enable it later (via
        // StrictMode) on debug builds, but using DropBox, not logs.
        CloseGuard.setEnabled(false);

        Environment.initForCurrentUser();

        // Set the reporter for event logging in libcore
        EventLogger.setReporter(new EventLoggingReporter());

        // Make sure TrustedCertificateStore looks in the right place for CA certificates
        final File configDir = Environment.getUserConfigDirectory(UserHandle.myUserId());
        TrustedCertificateStore.setDefaultUserDirectory(configDir);

        Process.setArgV0("<pre-initialized>");

        Looper.prepareMainLooper();

        ActivityThread thread = new ActivityThread();
        thread.attach(false);

        if (sMainThreadHandler == null) {
            sMainThreadHandler = thread.getHandler();
        }

        if (false) {
            Looper.myLooper().setMessageLogging(new
                    LogPrinter(Log.DEBUG, "ActivityThread"));
        }

        // End of event ActivityThreadMain.
        Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);
        Looper.loop();

        throw new RuntimeException("Main thread loop unexpectedly exited");
    }

 可以找到looper.prepareMainLooper,以及looper.loop,这就解决了之前loop函数在哪里调用的问题:思考:那么在子线程是不是需要我们手动调用loop函数呢?答案是需要!

https://www.zhihu.com/question/34652589

 

最后是参考:http://mp.weixin.qq.com/s/SVSJ7imNj6lsbuTE9ix2Zg

 

还有message的消息池,大小为50;

posted @ 2018-02-01 10:23  贺长寿  阅读(356)  评论(0编辑  收藏  举报