Can't create handler inside thread that has not called Looper.prepare()

不长记性,总是犯这个错误——在一个新建的线程中进行了Toast的操作

默认情况下Android中新诞生的线程是没有开启消息循环的。(主线程除外,主线程系统会自动为其创建Looper对象,开启消息循环)。座椅如果在主线程中开启一个handler,用message传递消息来在主线程handler中进行Toast是可行的,也是我一般的作法,现在来探寻下如果不用主线程的话应该怎么解决。


首先确定问题的产生原因是什么,

Toast或者Dialog中都有一个Handler的成员变量,在初始化时都会跟着初始化,而Toast或者Dialog中的Handler都需要一个Looper,所以需要在包含该Toast或者Dialog的线程中(如下面的Timer线程)初始化Looper。Looper.prepare();

Handler可看做是Looper的一个接口,用来向指定的Looper发送消息及定义处理方法。

以下转自 http://jeff-pluto-1874.iteye.com/blog/869710

寻找 Toast、Looper 和 Handler 三者之间的联系,也许谜底就能解开了。欲揭谜底,从源码入手是一条捷径。

Toast.java 的第231行的代码是创建一个新的Toast实例,而实例化的过程中,就需要执行第68行,也就是声明并创建Handler(成员变量)的实例。那么来看Handler.java的第121行到底做了什么,如下所示:

Java代码   收藏代码
  1. 119        mLooper = Looper.myLooper();  
  2. 120        if (mLooper == null) {  
  3. 121            throw new RuntimeException(  
  4. 122            "Can't create handler inside thread that has not called Looper.prepare()");}  

 到此,距离真相的解开近了一大步,既然抛出了 RuntimeException,那么 mLooper 肯定是 null,但是为什么 Looper.myLooper() 会返回 null?继续进入到 Looper.java 中寻根究底。

 

Java代码   收藏代码
  1. /** 
  2.  * Return the Looper object associated with the current thread.  Returns 
  3.  * null if the calling thread is not associated with a Looper. 
  4.  */  
  5. public static final Looper myLooper() {  
  6.     return (Looper)sThreadLocal.get();  
  7. }  

 以上就是 myLooper() 方法的真实面貌,通过注释可以看出问题的真正原因在于当前线程并没有绑定 Looper,返回为 null 是正确但非正常的结果。

那么正确的调用方法应该是什么呢

class LooperThread extends Thread {
    public Handler mHandler;
 
    public void run() {
        Looper.prepare();
        mHandler = new Handler() {
            public void handleMessage(Message msg) {
                // process incoming messages here
            }
        };
        Looper.loop();
    }
}

总而言之,Toast-->初始化Handler-->Handler实例化的过程中调用 mLooper = Looper.myLooper();-->当前线程并没有绑定 Looper,返回为 null -->Handler抛出异常Can't create handler inside thread that has not called Looper.prepare()

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值