子线程新建Handler为什么会报错?——浅谈Handler,Looper,Message之间的关系

本文探讨了在Android子线程中创建Handler导致的`Can't create handler inside thread that has not called Looper.prepare()`异常。分析了Handler、Looper和Message之间的关系,解释了Looper.prepare()和Looper.loop()的重要性,以及消息的处理流程,包括sendMessage()如何将消息放入队列,以及dispatchMessage()如何回调Handler进行消息处理。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

引言:很多人都知道不能再在子线程new一个Handler,android会报错,至于为什么会报错,并没有作深入的研究,今天一起来研究一下,顺手学习下android异步消息处理机制的问题。


在子线程中new 一个Handler为什么会出错?首先直接在子线程新建一个Handler?


new Thread(new Runnable() {
    @Override
    public void run() {

        Handler handler=new Handler(){
            @Override
            public void handleMessage(Message msg) {
                super.handleMessage(msg);

                Toast.makeText(getApplicationContext(),"handler msg",Toast.LENGTH_SHORT).show();


            }
        };

        handler.sendEmptyMessage(1);



    }
}).start();


 结果不出意外报错:java.lang.RuntimeException: Can't create handler inside thread that has not called Looper.prepare()。

Handler构造方法源码:

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

handler构造函数中,需要持有一个Looper对象,如果没有,提示这个错误。
looper的作用是与当前线程绑定,保证一个线程只有一个Looper实例,同事一个Looper实例也只有一个MessageQueue.
然后Looper的loop()方法就是不断从MessageQueue中取出消息,交给handler去发送消息,而子线程是默认没有looper的,
所以就会报错了,解决办法很简单,我们只需要调用prepare()方法,新建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));
}

可以看到方法中新建一个Looper对象放进了一个ThreadLocal的对象中,并且提前判断了ThreadLocal是否为空,这就说明了

prepare()方法不能被调用2次,也就保证一个线程只有一个Looper。

接下来看下Looper()构造方法。

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

构造函数中,新建一个MessageQueue,现在消息队列找到了,怎么从这个队列中取出消息给handler,调用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 traceTag = me.mTraceTag;
        if (traceTag != 0 && Trace.isTagEnabled(traceTag)) {
            Trace.traceBegin(traceTag, msg.target.getTraceName(msg));
        }
        try {
            msg.target.dispatchMessage(msg);
        } finally {
            if (traceTag != 0) {
                Trace.traceEnd(traceTag);
            }
        }

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


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

在myLooper方法中直接拿到了ThreadLocal中存储的Looper实例,如果为空,就报错,说明loop一定要在prepare之后调用,

然后拿到了looper中消息队列,进入无限循环,取消息,把消息赋给msg的target的dispatchMessage方法处理,这个msg.target就是

我们熟悉的handler。


在handler源码中,我们可以看到handler通过持有的looper获取了looper的messageQueue,这样就把Handler,looper,message联系在一起。

总结一下handler处理message的逻辑。

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

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

还记得上文looper.loop中会去除每个msg,然后交给target.dispathMessage(msg)去处理消息吗?

enqueueMessage中首先为msg.target赋值为this,也就是把当前的handler作为msg的target属性,最终会调用queue的enqueueMessage的

方法,也就是handler发出的消息,最终会被保存到消息队列中去。

现在已经知道了Looper会调用prepare和loop方法,在当前执行的线程中保存一个Looper实例,这个实例会保存一个MessageQueue对象,

然后当前线程进入一个无限循环中去,不断从MessageQueue中读取handler发来的消息,然后再回调创建这个消息的hanlder中的dispatchMessage

方法,下面看下这个方法的源码。

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

这里最终调用了我们创建handler中复写的handleMessage方法。
最后,整个流程基本理顺了一遍。
总结一下:
首先Looper.prepare()在本地线程中保存一个Looper实例,然后该实例保存一个MessageQueue对象,
因为Looper.prepare方法在一个线程中只能调用一次,所以MessageQueue在一个线程中只会存在一个。
Looper.loop方法会让当前线程进入一个无限循环,不断从MessageQueue的实例中读取消息,然后回调msg.target.dispathchMessage方法。

在Handler构造方法中,会首先得到当前线程中保存的Loop实例,进而与Looper实例中的MessageQueue相关联,
handler的sendMessage方法,会给msg的target赋值为handler本身,然后加入MessageQueue中,
在构造handler实例时,我们会重写handlerMessage方法,也就是msg.target.dispatchMessage(msg)最终调用的方法。

总结:
Looper负责的就是创建一个MessageQueue,然后进入一个无限循环不断从该MessageQueue中读取消息,而消息的创建者就是handler.
















评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值