Android进阶(十六)子线程调用Toast报Can't create handler inside thread that has not called Looper.prepare() 错误
原子线程调用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() 错误的更多相关文章
- 关于子线程使用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 ...
 - 在子线程中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 ...
 - 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 ...
 - 【转】在子线程中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 ...
 - 转 在子线程中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 ...
 - 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消息传递机制 ...
 - 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 ...
 - Android handler 报错处理Can't create handler inside thread that has not called Looper.prepare()
		
问题: 写了一个sdk给其他人用,提供一个回调函数,函数使用了handler处理消息 // handler监听网络请求,完成后操作回调函数 final Handler trigerGfHandler ...
 - 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 ...
 
随机推荐
- 检测linux vps是xen openvz还是kvm的方法
			
很多时候不知道自己买的vps是那种虚拟化技术,怕给商家忽悠了,下面给大家介绍下怎么简单的判断自己vps的虚拟化技术. 1.通过系统上的相关目录或文件判断 ll /proc/ ps: /proc目录 ...
 - Go 语言数据类型
			
在 Go 编程语言中,数据类型用于声明函数和变量. 数据类型的出现是为了把数据分成所需内存大小不同的数据,编程的时候需要用大数据的时候才需要申请大内存,就可以充分利用内存. Go 语言按类别有以下几种 ...
 - ELK 6安装配置 nginx日志收集 kabana汉化
			
#ELK 6安装配置 nginx日志收集 kabana汉化 #环境 centos 7.4 ,ELK 6 ,单节点 #服务端 Logstash 收集,过滤 Elasticsearch 存储,索引日志 K ...
 - 计算机网络之动态主机配置协议DHCP
			
为了将软件协议做成通用的和便于移植,协议软件的编写者不会把所有细节都固定在源代码中,而是把协议软件参数化,这就使得在很多台计算机上使用同一个经过编译的二进制代码成为可能. 一台计算机和另一台计算机的区 ...
 - Dynamics CRM2016 关于修改部署管理员账号权限引发的问题
			
最近在用2016做项目,一个同事的一个操作给我带来了一个头疼的问题,他把部署管理员的CRM账号的管理员权限给移除了,导致整个系统的所有账号进CRM都是下图这样 即使系统中还存在其他的拥有管理员权限的账 ...
 - Dynamics CRM2016 Web API之创建记录
			
前篇介绍了通过primary key来查询记录,那query的知识点里面还有很多需要学习的,这个有待后面挖掘,本篇来简单介绍下用web api的创建记录. 直接上代码,这里的entity的属性我列了几 ...
 - JQuery 网页选项卡制作
			
网页选项卡可以较好的利用有限的页面来展示更多的元素,而使用JQuery来制作网页选项卡也是一件非常简单的事情.今天就来分享一个网页选项卡的制作小技巧. 引入所需库 选项卡原理 业务核心 完整小例子 引 ...
 - [ExtJS5学习笔记]第二十九节 sencha ext js 5.1.0中动态更换皮肤主题
			
本文地址:http://blog.csdn.net/sushengmiyan/article/details/42016107 本文作者:sushengmiyan ------------------ ...
 - 剑指offer面试题3 二维数组中的查找 (java)
			
注:java主要可以利用字符串的length方法求出长度解决这个问题带来方便 public class FindNum { public static void main(String[] args) ...
 - 【Unity Shaders】ShadowGun系列之二——雾和体积光
			
写在前面 体积光,这个名称是God Rays的中文翻译,感觉不是很形象.God Rays其实是Crepuscular rays在图形学中的说法,而Crepuscular rays的意思是云隙光.曙光. ...