原子线程调用Toast报Can't create handler inside thread that has not called Looper.prepare() 错误

今天用子线程调Toast报了一个Can't create handler inside thread that has not calledLooper.prepare()错误。

因为toast的实现需要在activity的主线程才能正常工作,所以传统的非主线程不能使toast显示在actvity上,通过Handler可以使自定义线程运行于Ui主线程。

前几次碰到这个问题,确实郁闷了很久... log -- java.lang.RuntimeException: Can't create handler inside thread that has not calledLooper.prepare()

解决办法很简单:

Looper.prepare();

Toast.makeText(getApplicationContext(), "test", Toast.LENGTH_LONG).show();

Looper.loop();

为什么要加这两句,看了源码就了解了

Toast

public void show() {

...

service.enqueueToast(pkg, tn, mDuration);   //把这个toast插入到一个队列里面

...

}

Looper

public static final void prepare() {

if (sThreadLocal.get() != null) {

throw new RuntimeException("Only one Looper may be created per thread");

}

sThreadLocal.set(new Looper());  //在当前线程中创建一个Looper

}

private Looper() {

mQueue = new MessageQueue();  //关键在这,创建Looper都干了什么。 其实是创建了消息队列

mRun = true;

mThread = Thread.currentThread();

}

一般如果不是在主线程中又开启了新线程的话,一般都会碰到这个问题。

原因是在创建新线程的时候默认情况下不会去创建新的MessageQueue。

总结下:Toast 显示的必要条件:

1:Toast 显示需要出现在一个线程的消息队列中.... 很隐蔽

Android中HandlerThread类的解释

Android应用中的消息循环由Looper和Handler配合完成,Looper类用于封装消息循环,类中有个MessageQueue消息队列;Handler类封装了消息投递和消息处理等功能。

系统默认情况下只有主线程(即UI线程)绑定Looper对象,因此在主线程中可以直接创建Handler的实例,但是在子线程中就不能直接new出Handler的实例了,因为子线程默认并没有Looper对象,此时会抛出RuntimeException异常:

浏览下Handler的默认构造函数就一目了然了:

·如果需要在子线程中使用Handler类,首先需要创建Looper类实例,这时可以通过Looper.prepare()和Looper.loop()函数来实现的。阅读Framework层源码发现,Android为我们提供了一个HandlerThread类,该类继承Thread类,并使用上面两个函数创建Looper对象,而且使用wait/notifyAll解决了多线程中子线程1获取子线程2的Looper对象为空的问题。

Toast创建时需要创建一个Handler,但是这个Handler需要获得Looper的实例,而在子线程中是没有这个实例的,需要手动创建。

附Toast部分源码:

public Toast(Context context) {

mContext = context;

mTN = new TN();

mTN.mY = context.getResources().getDimensionPixelSize(

com.android.internal.R.dimen.toast_y_offset);

}

private static class TN extends ITransientNotification.Stub {

……

final Handler mHandler = new Handler();

……

}

Handler源码:

/**

* Default constructor associates this handler with the queue for the

* current thread.

*

* If there isn't one, this handler won't be able to receive messages.

*/

public Handler() {

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 = null;

}

Android进阶(十六)子线程调用Toast报Can't create handler inside thread that has not called Looper.prepare() 错误的更多相关文章

  1. 关于子线程使用Toast报错Can't create handler inside thread that has not called Looper.prepare()的解决办法

    形同如下代码,在Thread中调用Toast显示错误信息: new Thread(new Runnable(){ @Override public void run() { try{ weatherD ...

  2. 在子线程中new Handler报错--Can't create handler inside thread that has not called Looper.prepare()

    在子线程中new一个Handler为什么会报以下错误? java.lang.RuntimeException:  Can't create handler inside thread that has ...

  3. Android 线程更新UI报错 : Can't create handler inside thread that has not called Looper.prepare()

    MainActivity中有一个按钮,绑定了save方法 public void save(View view) { String title = titleText.getText().toStri ...

  4. 【转】在子线程中new Handler报错--Can't create handler inside thread that has not called Looper.prepare()

    在子线程中new一个Handler为什么会报以下错误? java.lang.RuntimeException:  Can't create handler inside thread that has ...

  5. 转 在子线程中new Handler报错--Can't create handler inside thread that has not called Looper.prepare()

    在子线程中new一个Handler为什么会报以下错误? java.lang.RuntimeException:  Can't create handler inside thread that has ...

  6. Android进阶(八)Can't create handler inside thread that has not called Looper.prepare()

    Error:Can't create handler inside thread that has not called Looper.prepare() 原代码: //利用Handler消息传递机制 ...

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

    10-12 17:02:55.500: E/AndroidRuntime(28343): FATAL EXCEPTION: Timer-2 10-12 17:02:55.500: E/AndroidR ...

  8. Android handler 报错处理Can't create handler inside thread that has not called Looper.prepare()

    问题: 写了一个sdk给其他人用,提供一个回调函数,函数使用了handler处理消息 // handler监听网络请求,完成后操作回调函数 final Handler trigerGfHandler ...

  9. Android 错误提示: Can't create handler inside thread that has not called Looper.prepare()

    Can't create handler inside thread that has not called Looper.prepare() 将 Handler handler = new Hand ...

随机推荐

  1. 01_自动化构建工具之Maven

    目前技术中存在问题(为什么使用Maven): 一个项目就是一个工程: 缺陷:如果项目太过庞大,就不适合使用package来划分层次,最好是一个模块就是一个工程,利于分工协作. 解决:Maven可以将一 ...

  2. PHP MySQL Where 子句

    WHERE 子句 WHERE 子句用于提取满足指定标准的的记录. 语法 SELECT column_name(s) FROM table_name WHERE column_name operator ...

  3. Appium移动自动化测试(三)--安装Android模拟器(建议直接连手机,跳过此步)

    转自虫师,亲测有效,留备后用. 本文中如果直接安装时不出现错误,则可以忽略(一.二.三.四.五),我安装的是5.1.1,直接成功,就是有点慢,要有耐心. 如果到最后一步,启动不起来,报错: emula ...

  4. EBS业务学习之库存管理

    库存管理业务流程 企业结构 库存结构 库存结构定义 指定每个子库存的特性: •子库存的数量跟踪 •资产类子库存 •保留子库存 •净值子库存 •包含在有效承诺中Include in ATP •子库存级库 ...

  5. com.fasterxml.jackson.databind.exc.UnrecognizedPropertyException: Unrecognized field 异常

    分享牛原创(尊重原创 转载对的时候第一行请注明,转载出处来自分享牛http://blog.csdn.net/qq_30739519) 1.1.1. 前言 近期在使用ObjectMapper对象将jso ...

  6. javascript之内置函数

    1.常规函数 (1)alert函数:显示一个警告对话框,包括一个OK按钮. (2)confirm函数:显示一个确认对话框,包括OK.Cancel按钮. (3)escape函数:将字符转换成Unicod ...

  7. Swift中声明协议中的class关键字的作用

    大熊猫猪·侯佩原创或翻译作品.欢迎转载,转载请注明出处. 如果觉得写的不好请多提意见,如果觉得不错请多多支持点赞.谢谢! hopy ;) 最近在Cocos2D编程for Swift中看到以下一个代码片 ...

  8. 简单搭建iOS开发项目框架

    今天我们来谈谈如何搭建框架,框架需要做一些什么. 第一步:找到我们的目标我们的目标是让其他开发人员拿到手后即可写页面,不再需要考虑其他的问题. 第二步:我们需要做哪些东西各位跟着我一步一步来进行. 假 ...

  9. javascript中的XML

    IE下创建DOM并载入XML var xmldoc = new ActiveXObject("Microsoft.XMLDOM"); xmldoc.load(url); //载入X ...

  10. 基于OpenCV 的美颜相机推送直播流

    程序流程: 1.图像采集 先从opencv(2.4.10版本)采集回来摄像头的图像,是一帧一帧的 每一帧图像是一个矩阵,opencv中的mat 数据结构. 2.人脸的美化 人脸美化,我们用的皮肤检测, ...