java.lang.RuntimeException: Can't create handler inside thread that has not
在子线程中 调用了这句:
Toast.makeText(UiUtils.getContext(), "正在下载"+name, Toast.LENGTH_SHORT).show();
报出了下面的错误
08-15 14:52:50.368 3517-3560/com.ldw.marketm E/AndroidRuntime: FATAL EXCEPTION: pool-2-thread-5Process: com.ldw.marketm, PID: 3517java.lang.RuntimeException: Can't create handler inside thread that has not called Looper.prepare()at android.os.Handler.<init>(Handler.java:200)at android.os.Handler.<init>(Handler.java:114)at android.widget.Toast$TN.<init>(Toast.java:327)at android.widget.Toast.<init>(Toast.java:92)at android.widget.Toast.makeText(Toast.java:241)at com.ldw.marketm.holder.DetailBottomHolder$2.run(DetailBottomHolder.java:78)at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)at java.lang.Thread.run(Thread.java:841)
分析:跟踪源码
查看makeText方法,可以看到 new了一个Toast实例
public static Toast makeText(Context context, CharSequence text,@Duration int duration) {Toast result = new Toast(context);LayoutInflater inflate = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);View v = inflate.inflate(com.android.internal.R.layout.transient_notification, null);TextView tv = (TextView) v.findViewById(com.android.internal.R.id.message);tv.setText(text);result.mNextView = v;result.mDuration = duration;return result;
}
Toast构造函数中又实例化了一个 TN对象
public Toast(Context context) {mContext = context;mTN = new TN();mTN.mY = context.getResources().getDimensionPixelSize(com.android.internal.R.dimen.toast_y_offset);mTN.mGravity = context.getResources().getInteger(com.android.internal.R.integer.config_toastDefaultGravity);
}
在静态类TN中,可以读到这一句:
final Handler mHandler = new Handler();
创建了一个Handler对象
private static class TN extends ITransientNotification.Stub {final Runnable mShow = new Runnable() {@Overridepublic void run() {handleShow();}};final Runnable mHide = new Runnable() {@Overridepublic void run() {handleHide();// Don't do this in handleHide() because it is also invoked by handleShow()mNextView = null;}};private final WindowManager.LayoutParams mParams = new WindowManager.LayoutParams();final Handler mHandler = new Handler();
读 Handler构造函数:
/*** * Default constructor associates this handler with the {@link Looper} for* the * current thread. * * If this thread does not have a looper, this* handler won't be able to receive messages * so an exception is thrown.*/
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;
}
主线程中创建handler后会默认创建一个looper对象。但是子线程不会,需要手动创建。其ThreadLoacl中没有设置过Looper,mLooper==null ,所以会抛出异常。
解决方法
方法一:增加Looper.prepare();
ThreadManager.getInstance().createLongPool().execute(new Runnable(){@Overridepublic void run() {//SystemClock.sleep(3000);Looper.prepare();Toast.makeText(UiUtils.getContext(), "正在下载"+name, Toast.LENGTH_SHORT).show();Looper.loop();// 进入loop中的循环,查看消息队列/*getActivity().runOnUiThread(new Runnable() {@Overridepublic void run() {}});*/}});
方法二:post 给主线程去处理
// if current thread is background thread
// post show-toast-runnable to main handler
// if current thread is background thread
// post show-toast-runnable to main handlermainHandler.post(new Runnable() {@Overridepublic void run() {if (toast == null) {toast = Toast.makeText(context, "", Toast.LENGTH_SHORT);}toast.setText(msg);toast.setDuration(Toast.LENGTH_SHORT);toast.show();}
});
java.lang.RuntimeException: Can't create handler inside thread that has not相关推荐
- java.lang.RuntimeException: Can't create handler inside thread that has not called Looper.prepare()
java.lang.RuntimeException: Can't create handler inside thread that has not called Looper.prepare() ...
- Android --- java.lang.RuntimeException: Can‘t create handler inside thread that has not called Loop
报错信息如下: java.lang.RuntimeException: Can't create handler inside thread that has not called Looper.pr ...
- Can't create handler inside thread that has not called Looper.prepare() 解决办法
在开发的过程当中,遇到了想在一个线程中弹出一个提示窗 new AlertDialog.Builder( context),但是就出现了一个问题. java.lang.Runtim ...
- Can't create handler inside thread that has not called Looper.prepare()
问题: Can't create handler inside thread that has not called Looper.prepare() 1,在报错的方法前加Looper.prepare ...
- MQ java.lang.OutOfMemoryError: unable to create new native thread
文章目录 1. 问题现象 2. 分析定位 3. 解决方案 4. 结果验证 5. 总结 1. 问题现象 java.lang.OutOfMemoryError: unable to create new ...
- 解决java.lang.OutOfMemoryError: unable to create new native thread问题
解决java.lang.OutOfMemoryError: unable to create new native thread问题 参考文章: (1)解决java.lang.OutOfMemoryE ...
- spark大批量读取Hbase时出现java.lang.OutOfMemoryError: unable to create new native thread
这个问题我去网上搜索了一下,发现了很多的解决方案都是增加的nproc数量,即用户最大线程数的数量,但我修改了并没有解决问题,最终是通过修改hadoop集群的最大线程数解决问题的. 并且网络上的回答多数 ...
- Can't create handler inside thread Thread that has not called Looper.prepare()
今天在子线程里面写了一个Toast 运行程序直接崩溃了 看了下log 如下 最后忽然想到了子线程里面不能直接使用Toast 然后 就添加了 Looper.prepare(); 和 Looper.loo ...
- Caused by: java.lang.RuntimeException: Font asset not found fonts/SYFZLTKHJW.TTF
/*** 通过反射方法设置app全局字体*/public void setTypeface() {typeFace = Typeface.createFromAsset(getAssets(), &q ...
最新文章
- CUDA5.5入门文章:VS10设置
- (93)多人投票器(N人投票器)
- 4-8 :button表单按钮选择器
- UnicodeDecodeError: 'ascii' codec can't decode byte 0xe4 in position 31: ordinal not in range(128)
- 双变量空间自相关_【数据分析】变量探索分析
- 什么是网络通信协议?(七层功能介绍)
- c语言日历程序 带农历,一个完整的日历程序(含有农历)
- IDEA 修改全文搜索快捷键
- spire.doc 让java操作word文档更简单优雅
- Java 基础 第3阶段:高级应用——尚硅谷学习笔记(含面试题) 2023年
- 八大处理器最强手机盘点 手机CPU混战(组图)
- 模型prun quantization related paper
- 点亮科技树——锂离子电池
- 2020年软件评测师真题精选
- 两个链表的第一个公共节点
- 供应链平台物流、售后管理功能详解:SCM系统软件撬动新能源汽车企业发展空间
- OSCAR 云计算开源产业大会 之 ServiceComb 雄关漫道 PPT 大放送
- 通过OPC网关快速实现采集PLC数据到OPC Server服务器
- python极客学院爬虫_基于requests实现极客学院课程爬虫
- 考研上浙大计算机了...