Handler

  • Handler:Android SDK 提供给开发者方便进行异步消息处理的类(面试都会问原理)
    image.png
  • messageQueue 消息队列: 先进先出。管理Message对象,需要注意的是 messageQueue消息队列的数据结构并不是队列,它是由单链表来构成的

整个流程: 首先为主线程创建一个looper对象,每一个线程只能有一个looper。而在创建looper对象的时候它内部构造方法中又会创建一个messageQueue对象。而创建handler的时候我们会取出当前线程的looper,然后通过looper去轮询messageQueue中的messagehandler每发送一条消息,相当于在messageQueue中添加一条消息。最后通过looper当中的消息循环取得消息队列中的message交给handler去进行处理。

image.png

通过源码可以发现,创建handler的时候。会调用一个Looper.myLooper()方法,如果looper没走looper.prepare,则会报异常。

image.png

image.png

我们可以看到 looper通过sThreadLocal这个容器来存放。如果创建了就会提示一个looper只能创建一次。否则则将这个looper对象放到sThreadLoacl中,sThreadLoacl我们也叫作线程本地变量。它能为每个变量在每个线程都创建一个副本,这样就能保证每个线程都能访问自己的变量。所以说handler必须得有一个指定的looper对象。而创建完looper之后,looper会创建消息队列,之后赋值给handlermQueue。三者做一个捆绑。而在looper构造方法中,我们也看到了他new 了一个 messageQueue对象。

现在我们来看看Looper.myLooper()方法

image.png

通过上面所说的,sThreadLoacl是线程所持有的容器。所以通过他的get方法就能获得looper对象

再看sendEmptyMessage还是sendEmptyMessageDelayed 最终都会走到一个enqueueMessage方法。这个方法的就是将我们的message添加到消息队列当中。

image.png

接下来我们再看looper这个类

  /**
 * 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 slowDispatchThresholdMs = me.mSlowDispatchThresholdMs;

        final long traceTag = me.mTraceTag;
        if (traceTag != 0 && Trace.isTagEnabled(traceTag)) {
            Trace.traceBegin(traceTag, msg.target.getTraceName(msg));
        }
        final long start = (slowDispatchThresholdMs == 0) ? 0 : SystemClock.uptimeMillis();
        final long end;
        try {
            msg.target.dispatchMessage(msg);
            end = (slowDispatchThresholdMs == 0) ? 0 : SystemClock.uptimeMillis();
        } finally {
            if (traceTag != 0) {
                Trace.traceEnd(traceTag);
            }
        }
        if (slowDispatchThresholdMs > 0) {
            final long time = end - start;
            if (time > slowDispatchThresholdMs) {
                Slog.w(TAG, "Dispatch took " + time + "ms on "
                        + Thread.currentThread().getName() + ", h=" +
                        msg.target + " cb=" + msg.callback + " msg=" + msg.what);
            }
        }

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

for (;;)是个死循环,意思是looper轮询器会不断的去轮询消息。如果消息不为空,他就会执行 msg.target.dispatchMessage(msg);来处理消息 其中msg.target可以看上面一张图 enqueueMessage的方法。我们可以知道,这个就是我们的handler对象

我们回到handler类看这个方法:

/**
 * Handle system messages here.
 */
public void dispatchMessage(Message msg) {
    if (msg.callback != null) {
        handleCallback(msg);
    } else {
        if (mCallback != null) {
            if (mCallback.handleMessage(msg)) {
                return;
            }
        }
        handleMessage(msg);
    }
}

他会先判断msgcallback是不是为空,如果不为空他就会执行 handleCallback(msg);那么这个 callback 是什么呢?其实他就是我们的runnable。所以说不管handler最终post了什么。最终他传递的都是一个runnable参数,我们可以点进去看下他的方法如下:

private static void handleCallback(Message message) {
    message.callback.run();
}

就是调用了runnablerun方法

接着我们继续看如果msgcallback为空的情况下,他会用mCallback.handleMessage(msg)来处理消息。那么这个mCallback又是什么呢?

/**
 * Callback interface you can use when instantiating a Handler to avoid
 * having to implement your own subclass of Handler.
 *
 * @param msg A {@link android.os.Message Message} object
 * @return True if no further handling is desired
 */
public interface Callback {
    public boolean handleMessage(Message msg);
}

我们在源码中发现他是一个接口,而他的接口中呢只有一个我们特别熟悉的方法handleMessage。用来处理消息。

主线程的死循环一直运行是不是特别消耗CPU资源呢? 其实不然,这里就涉及到Linux pipe/e****poll机制,简单说就是在主线程的MessageQueue没有消息时,便阻塞在loop的queue.next()中的nativePollOnce()方法里,详情见Android消息机制1-Handler(Java层),此时主线程会释放CPU资源进入休眠状态,直到下个消息到达或者有事务发生,通过往pipe管道写端写入数据来唤醒主线程工作。这里采用的epoll机制,是一种IO多路复用机制,可以同时监控多个描述符,当某个描述符就绪(读或写就绪),则立刻通知相应程序进行读或写操作,本质同步I/O,即读写是阻塞的。 所以说,主线程大多数时候都是处于休眠状态,并不会消耗大量CPU资源。

下面总结几点

  • 1.Lopper 类主要是为每个线程开启的单独的消息循环。默认情况下Android新诞生的线程是没有开启消息循环的,所以说要在线程中使用Handler,你必须先调用Looper.prepare()方法。但是主线程除外,因为主线程中系统已为我们创建了Looper对象**
  • 2.handler 我们可以看作是Looper的一个接口,用来像Looper指定的messageQueue 发送消息
  • 3.在非主线程中直接new Handler()是不可以的。原理:Handler他需要发送消息到MessageQueue,而你所在的线程中没有MessageQueue,而MessageQueueLooper管理,你想创建Handler,你必须先创建好Looper
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容