2020-07-25为什么在子线程中创建Handler会抛异常?

  1. Handler,Looper 和 MessageQueue 的关系
    这部分只是简单介绍一下。

Handler 主要用来发送和接收消息;
Looper 主要用来轮询消息;
MessageQueue 主要用来存储消息。

2. Handler 的工作原理

2.1 引入

先看一段代码,这也是使用 Handler 的常见方式:

public class MyActivity extends Activity {
    private static final String TAG = MyActivity.class.getSimpleName();
    private static final int MSG_CODE = 1;
    private static Handler sHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case MSG_CODE:
                    Log.d(TAG, "接收到的消息是: " + msg.obj);
                    break;
                default:
            }
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Message msg = new Message();
        msg.what = MSG_CODE;
        msg.obj = "这是发送的消息";
        Log.d(TAG, "发送消息为" + msg.obj);
        sHandler.sendMessage(msg);
    }
}

运行一下,查看日志:

D/MyActivity: 发送消息为这是发送的消息
D/MyActivity: 接收到的消息是: 这是发送的消息

2.2 发送过程

从发送的地方看起:

   public final boolean sendMessage(Message msg)
 {
     return sendMessageDelayed(msg, 0);
 }

这个方法的作用是把 Message 发送到 MessageQueue 的尾部。接收消息的是在 handleMessage() 方法中,是在和 Handler 相关联的线程中。
若是成功地把消息放置到 MessageQueue 的尾部,那么这个方法就会返回 true;失败的话,就返回 false。失败通常是因为处理 Message 的 Looper 正在退出。

接着看 sendMessageDelayed() 方法:

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

在这个方法中,先获取成员变量 mQueue 的引用,然后判断 MessageQueue queue 的值是否为 null,最后会调用 enqueueMessage(queue, msg, uptimeMillis) 方法。重要的就是 mQueue 的获取和判断。mQueue 是在哪里被赋值的呢?是在构造 Handler 对象的过程中赋值的,具体看 public Handler(Callback callback, boolean async) 方法的 mQueue = mLooper.mQueue; 这行代码。而因为我们是在主线程构造的 Handler 对象,所以我们获取到的 mQueue 是主线程对应 Looper 对象的 mQueue,它是不为 null 的。

接着看:

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

在这个方法中,首先把 this 赋值给 Message 对象的 target 属性。this 代表就是这里的 Handler 对象。下面的 if 语句,默认不会成立,最后是调用 MessageQueue 的 enqueueMessage(Message msg, long when) 方法。这个方法的重点是让 Message 对象持有当前 Handler 对象的引用。

到这里,消息已经发送到了 MessageQueue 中了
在这个方法中,首先把 this 赋值给 Message 对象的 target 属性。this 代表就是这里的 Handler 对象。下面的 if 语句,默认不会成立,最后是调用 MessageQueue 的 enqueueMessage(Message msg, long when) 方法。这个方法的重点是让 Message 对象持有当前 Handler 对象的引用。

到这里,消息已经发送到了 MessageQueue 中了。

2.3 接收过程
上面我们已经看到,消息通过 Handler 的 sendMessage(Message msg) 方法最终发送到了 MessageQueue 里。那么如何再接收到发送的消息呢?

需要介绍一个从 MessageQueue 里取消息的角色:Looper。Looper 会通过 Looper.loop() 方法轮询消息。

     /**
     * 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
            Printer logging = me.mLogging;
            if (logging != null) {
                logging.println(">>>>> Dispatching to " + msg.target + " " +
                        msg.callback + ": " + msg.what);
            }

            msg.target.dispatchMessage(msg);

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

在这个方法里,先获取到当前线程的 Looper 对象,就是主线程的 Looper 对象。接着就进入了 for 的无限循环,这个无限循环是这个方法的重点。
在无限循环中,先从 MessageQueue 中取出下一个 Message 对象;判断 Message 对象为 null 的话,就结束无限循环,当然 loop() 方法也随之结束。

Note:

这个地方曾经被面试问到过:
面试官:Looper 的 loop() 方法什么时候结束呢?
我:当 MessageQueue 的 next() 方法返回 null 的时候,loop() 方法就会结束。
面试官:那么,MessageQueue 的 next() 方法什么时候返回 null ?
我:这个…..

接着看 msg.target.dispatchMessage(msg); 这行代码,这里的 msg.target 就是 当前的 Handler 对象。在发送过程的分析中,刚刚提过这一点。

进入Handler 的 dispatchMessage(Message msg) 方法:

    /**
     * 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);
        }
    }
``` j
在这个方法中,依照实例代码,会调用最后一行的 handleMessage(msg),在这个方法中会接收到发送的消息。

3. 为什么在子线程中执行 new Handler() 会抛出异常?
在子线程中 new Handler():

``` java
public class MyActivity2 extends Activity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        new Thread("Thread1"){
            @Override
            public void run() {
                super.run();
                Handler handler = new Handler();
            }
        }.start();
    }
}

运行一下,查看日志:

E/AndroidRuntime: FATAL EXCEPTION: Thread1
    Process: com.wzc.chapter_10, PID: 5263
    java.lang.RuntimeException: Can't create handler inside thread that has not called Looper.prepare()
        at android.os.Handler.<init>(Handler.java:208)
        at android.os.Handler.<init>(Handler.java:122)
        at com.wzc.chapter_10.MyActivity2$1.run(MyActivity2.java:20)

从日志里,可以知道:不能在还没有调用 Looper.prepare() 方法的线程中创建 Handler。
那我们就在线程中调用一次 Looper.prepare() 方法,再次运行果然不报错了。

Looper.prepare();
Handler handler = new Handler();

但是具体原因是什么?

从 Hander 的构造方法入手:

public Handler() {
        this(null, false);
}

public Handler(Callback callback, boolean async) {
        if (FIND_POTENTIAL_LEAKS) {
            final Class<? extends Handler> klass = getClass();
            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());
            }
        }

        mLooper = Looper.myLooper();
        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;
 }

在带参的构造函数中,我们发现了抛出异常的地方,在 mLooper 对象为 null 的时候, 会抛出异常。说明这里的 Looper.myLooper(); 的返回值是 null。
看一下 Looper.myLooper() 方法:

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

是从 Looper 类 的 sThreadLocal 这个静态成员变量中取出 Looper 对象。
需要查看一下,sThreadLocal.set() 方法的调用:

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

可以看到只有调用了 Looper.prepare() 方法,才会构造一个 Looper 对象并在 ThreadLocal 存储当前线程的 Looper 对象。
这样在调用 Looper.myLooper() 时,获取的结果就不会为 null。

©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 194,088评论 5 459
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 81,715评论 2 371
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 141,361评论 0 319
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 52,099评论 1 263
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 60,987评论 4 355
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 46,063评论 1 272
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 36,486评论 3 381
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 35,175评论 0 253
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 39,440评论 1 290
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 34,518评论 2 309
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 36,305评论 1 326
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 32,190评论 3 312
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 37,550评论 3 298
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 28,880评论 0 17
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 30,152评论 1 250
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 41,451评论 2 341
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 40,637评论 2 335