Handler的工作原理,为什么在子线程中执行 new Handler() 会抛出异常?

Handler的工作原理

我们常说的安卓的消息机制其实就是Handler的运行机制。Hanlder的底层是由MessageQueue和looper作为支撑。

  • MessageQueue
    消息队列,但是它内部的存储并不是消息队列,而是单链表的数据结构来存储数据的。MessageQueue只是存储存储消息,而不处理消息。
  • looper
    Looper则是负责处理消息,它会以无限循环的方式去查找是否有新的消息,有消息就处理,没有消息就等待。Looper中还有一个特殊的概念是ThreadLocal。
  • ThreadLocal
    ThreadLocal不是一个线程,而是在每个线程中存储数据。它可以在不同的线程中互补干扰的获取存储数据,通过ThreadLocal可以获取每个线程的looper。

    当我们使用Handler的时候,系统内部会创建一个Looper来构造消息系统,对于我们常提高的UI线程,指的就是ActivityThread,在ActivityThread创建的时候就会初始化一个Looper,当我们使用的时候,可以直接创建一个Handler。

在平常的开发中当在子线程中直接使用Handler时会报错

 java.lang.RuntimeException: Can't create handler inside thread that has not called Looper.prepare()
                                                                                     at android.os.Handler.<init>(Handler.java:200)
                                                                                     at android.os.Handler.<init>(Handler.java:114)
                                                                                     at com.example.ljingya.myapplication.MainActivity$1$1.<init>(MainActivity.java:19)
                                                                                     at com.example.ljingya.myapplication.MainActivity$1.run(MainActivity.java:19)
                                                                                     at java.lang.Thread.run(Thread.java:841)

需要在创建Handler之前创建一个Looper

 Looper.prepare();

在该方法内部会调用ThreadLocal的set方法创建一个Looper,并保存当前线程。

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

      private Looper(boolean quitAllowed) {
      //创建一个消息队列
        mQueue = new MessageQueue(quitAllowed);
        //保存当前线程
        mThread = Thread.currentThread();
    }

当创建Handler时在时会先获取当前线程的Looper,若Looper为null则抛出异常。

  public Handler(Callback callback, boolean async) {
        mLooper = Looper.myLooper();
        //判断Looper是否为null
        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;
    }

创建Handler之后需要开启消息轮询调用

  Looper.loop();

在loop方法中主要做这样几件事情:

  • 获取当前的Looper。

  • 从Looper中拿到消息队列

  • 通过循环调用队列的next方法获取Message,当message为空时返回null,并阻塞该队列。

  • 当有消息时调用msg.target.dispatchMessage(msg)及调用Handler的dispatchMessage方法处理该消息

 public static void loop() {
         //获取当前的Looper。
        final Looper me = myLooper();
        if (me == null) {
            throw new RuntimeException("No Looper; Looper.prepare() wasn't called on this thread.");
        }
        //从Looper中拿到消息队列
        final MessageQueue queue = me.mQueue
        ....省略代码
        for (;;) {
        //通过循环调用队列的next方法获取Message,当message为空时返回null,并阻塞该队列。
            Message msg = queue.next(); // might block
            if (msg == null) {
                // No message indicates that the message queue is quitting.
                return;
            }
            ...省略代码
            //当有消息时调用msg.target.dispatchMessage(msg)及调用Handler的dispatchMessage方法处理该消息
                msg.target.dispatchMessage(msg);
              ...省略代码
        }
    }

在Handler的dispatchMessage中则最终调用消息的回调处理。

public void dispatchMessage(Message msg) {
        if (msg.callback != null) {
            handleCallback(msg);
        } else {
            if (mCallback != null) {
                if (mCallback.handleMessage(msg)) {
                    return;
                }
            }
            //消息处理的回调
            handleMessage(msg);
        }
    }

当在使用中调用Handler的sendMessage方法时,只是想消息队列中插入一条消息,当开启轮询时会不断的从队列中处理队列中的消息。

//调用sendMessage
 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);
    }
//在这个方法中最后调用队列的enqueueMessage方法将消息插入队列中。
  private boolean enqueueMessage(MessageQueue queue, Message msg, long uptimeMillis) {
        msg.target = this;
        if (mAsynchronous) {
            msg.setAsynchronous(true);
        }
        return queue.enqueueMessage(msg, uptimeMillis);
    }
执行 new Handler() 会抛出异常

在上面提到在创建Handler时会检查Looper是否为null,若没有初始化Looper对象会抛出异常。

public Handler(Callback callback, boolean async) {
        mLooper = Looper.myLooper();
        //判断Looper是否为null
        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;
    }
消息机制的流程图

这里写图片描述

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值