java.lang.RuntimeException: Can't create handler inside thread that has not

【报错提示】java.lang.RuntimeException: Can‘t create handler inside thread 遇到一个报错: java.lang.RuntimeException: Can't create handler inside thread Thread[OkHttp https://a.fxltsbl.com/...] that has not called Looper.prepare() 1. 这个报错提示是在一个没有调用 Looper.prepare() 的线程中尝试创建一个 Handler 对象。 阅读详情

以前没遇到过现在遇到就找到收集一下

在Android中不允许Activity里新启动的线程访问该Activity里的UI组件,这样会导致新启动的线程无法改变UI组件的属性值。


出现java.lang.RuntimeException: Can't create handler inside thread that has not called Looper.prepare()异常


然而,我们实际需要,在很多时候都需要异步获取数据刷新UI控件,这时候采取的方法就是Handler消息机制和AsyncTask异步任务两种解决方法。


首先是引起异常的例子:

<span style="color:#ff9966;">new Thread(new Runnable() {
			
			@Override
			public void run() {
				// TODO Auto-generated method stub
				
				try {
					Thread.sleep(1000);
					Toast.makeText(getApplicationContext(), "ABCDEFGHIJKLMNOPQRSTUVWXYZ", 0).show();
				} catch (InterruptedException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				
			}
		}).start();</span>

上面例子在线程里面休眠1秒后吐司消息,然后出现 java.lang.RuntimeException: Can't create handler inside thread that has not called Looper.prepare()异常。

正确的方法应该是:

new Thread(new Runnable() {
			
			@Override
			public void run() {
				// TODO Auto-generated method stub
				
				try {
					Thread.sleep(1000);
					handler.sendEmptyMessage(0);
				} catch (InterruptedException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				
			}
		}).start();
private Handler handler = new Handler() {

		@Override
		public void handleMessage(Message msg) {
			// TODO Auto-generated method stub
			
			Toast.makeText(getApplicationContext(), "ABCDEFGHIJKLMNOPQRSTUVWXYZ", 0).show();
			
		}
		
	};

重写Handler对象中的handlerMessage方法进行你需要的处理。


当然不是只有这一种方法可以实现我们的需要,


runOnUiThread(Runnable action) Activity中带有的方法,运行指定的action在UI线程中,如果当前线程是UI线程,那么action立即执行。如果当前线程不是UI线程,那么action将发送事件到UI的消息队列中。


View post(Runnable aciton);


View postDelayed(Runnable action, long delayMillis);


这两个方法也是同样的道理。


下面是异步任务的处理:

private class MyTask extends AsyncTask<Void, Void, Void> {

		@Override
		protected Void doInBackground(Void... params) {
			// TODO Auto-generated method stub
			publishProgress();
			return null;
		}
		
		@Override
		protected void onProgressUpdate(Void... values) {
			// TODO Auto-generated method stub
			super.onProgressUpdate(values);
			try {
				Thread.sleep(1000);
				Toast.makeText(getApplicationContext(), "doInBackground", 0).show();
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		
		@Override
		protected void onPostExecute(Void result) {
			// TODO Auto-generated method stub
			Toast.makeText(getApplicationContext(), "onPostExecute", 0).show();
			super.onPostExecute(result);
		}
		
	}

onProgressUpdate方法的执行在收到publishProgress方法调用后,运行于UI线程中,对UI控件进行处理,例如,我们做的下载,需要显示下载到了百分之多少时,可以不停的publishProgress(Value value),然后在进度条中更新。


onPostExecute()方法,在doInBackground()方法结束后运行在UI线程,对result进行处理



doInBackground()方法中,就是在后台线程中处理我们的异步任务,不能做类似Toast的操作,同样会出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 - 爱程序网
http://www.aichengxu.com/view/8850


Figma汉化教程 阅读详情

相关推荐

通俗易懂的图解二叉搜索树、AVL树和红黑树

搜索是一种很常见的需求,当数据较多时,如何找到目标对象时,即需要搜索查找。 那么如何快速找到目标呢,最朴素的思想就是暴力查找,一个一个对比。 显然,当数据量增大时,我们需要优化查找方法获取更快的查找速度,我们可以通过维护一个有序数组,从而实现二分查找,查找速度从O(n)降为O(longn)。 但是数组并不便于插入和删除,链表便成为了最好的选择。 既然是采用二分查找,那么不如直接按照查找的步骤维护一种数据结构,于是二叉搜索树出现了。 二叉搜索树的性质为: 若左子树不为空,则左子树上所有节点值都小于根结点值;

暗色光的博客 758

java.lang.RuntimeException: Can‘t create handler inside thread that has not called Looper.prepare()

今天记录一下写安卓的时候遇到的些问题吧,都是比较常见实用的1、错误:java.lang.RuntimeException: Can't create handler inside thread that has not called Looper.prepare()2、简单的okhttp的Get请求。Json转数组总结: 博主并不是专业的安卓开发,所以遇到的一些问题也可能比较低级,解决方案也并非...

Mr_Van的博客 3579

从ISCXTor2016到CICIDS2017:手把手教你下载和使用UNB的网络安全数据集

本文详细介绍了UNB大学发布的ISCXTor2016和CICIDS2017等网络安全数据集的下载与使用方法,特别适合加密流量识别和网络行为分析研究。文章提供了多种高效获取路径、文件结构解析及实战分析示例,帮助研究者快速上手这些真实场景捕获的精细标注数据集。

weixin_42524945的博客 641

如何解决java.lang.RuntimeException: Can't create handler inside thread that has not called Looper.prepar

如何解决java.lang.RuntimeException: Can’t create handler inside thread that has not called Looper.prepare(). 在很多时候,我们需要去实现一个自己的Handler对象,然后去异步有序地处理一些逻辑。如下所示: private class MyHandler extends Handler { ...

勤奋的果子的博客 3592

零样本缺陷检测新体验:用AnomalyGPT大模型快速搭建智能质检系统(附Win10适配指南)

本文详细介绍了如何利用AnomalyGPT大模型在Windows 10系统上快速搭建零样本工业缺陷检测系统。通过实战指南,涵盖从环境部署、模型准备到工程化落地的全过程,包括将模型封装为API服务、接入工业相机以及开发可视化监控看板,为制造业智能质检提供了一套高效、低门槛的本地部署解决方案。

weixin_29094775的博客 312

dToF直方图之美_deadtime死区时间

IMX459的死区时间可以在6ns,这个时间是什么级别,车载激光雷达激光器的光脉宽一般都在4ns以上,也就是这个时间贴近去SPAD的死区时间,这就导致了pile up会非常弱,不会有太多数量的光子计数堆积,加上某些SPAD设计,对TDC有一些更深入的考量,所以不需要去校正pile up算法。Sensor层面决定了pile up的复杂程度,如果一个dToF的SPAD一致性非常好,那么pile up校正可以简单到极致,也就是一句代码的事,比如IMX611,优秀到不需要后端去考虑校正pile up。

致力于lidar应用开发 2152

Toast和Looper。Handler消息循环机制。

(1) Looper类别用来为一个线程开启一个消息循环。默认情况下Android中新诞生的线程是没有开启消息循环的。(主线程除外,主线程系统会自动为其创建Looper对象,开启消息循环) Looper对象通过MessageQueue来存放消息和事件。一个线程只能有一个Looper,对应一个MessageQueue。 (2) 通常是通过Handler对象来与Looper交互的。Han...

JoyChiang的专栏 475

提示词驱动的智能合同生成与审核

第1章:核心概念与背景 1.1.1 问题背景 1.1.1.1 合同生成与审核的需求 合同作为商业和法律领域中的基本工具,其生成和审核过程至关重要。传统的合同生成往往依赖于法律专业人士的手工撰写,这不仅耗时耗力,而且容易出现错误。此外,合

AI天才研究院 1003

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

在Android中不允许Activity里新启动的线程访问该Activity里的UI组件,这样会导致新启动的线程无法改变UI组件的属性值。 出现java.lang.RuntimeException: Can't create handler inside thread that has not called Looper.prepare()异常 然而,我们实际需要,在很多时候都需要异步获取数据

wsyjx22的专栏 3528

Linux ARM平台开发系列讲解(LED) 2.1.1 如何点亮一个LED之添加设备树信息

1. 设备树添加设备信息 我拿到的开发板上有两颗LED供用户编程使用,分别是GPIO5_IO8和GPIO5_IO9,设备信息如下,不同板子的设备定义不同,根据自己的实际情况进行添加。 2. 编译设备树 根据自己拿到的SDK,执行编译命令,我这里拿到的SDK编译脚本为: ./build.sh kernel 3. 使用uuu工具烧录新编译好的内核 因为imx8 SDK设备树和内核是统一编译成一个镜像,所以只需要烧录内核,设备树文件也会烧录。 sudo uuu -b emmc imx-kernel.bin

DSMGUOGUO的博客 920

搞定ESD(七):静电放电问题典型案例分析(二)

静电放电噪声耦合的方式主要是:传导耦合与辐射耦合,辐射耦合主要以磁场耦合、 电场耦合为主要形式。电场耦合发生的主要条件是:静电放电高频在参考地平面寄生电感中产生电平波动,平行于参考地平面上的较长信号布线就很容易通过分布电容发生电场耦合。根据高速信号回流路径的特性可知,其回流路径是贴近信号布线下方,或者信号两侧,若信号回流路径跨分割后,环路面积会随之增大;信号环路面积大从EMI角度看其空间辐射更强,从EMS角度看则更容易耦合外部噪声干扰(雷击浪涌、EFT、ESD、RS)。

记得诚 2804

java.lang.RuntimeException: Can't create handler inside thread that has not call

java.lang.RuntimeException: Can't create handler inside thread that has not called Looper.prepare() 这时今天遇到的第二个错误。 原因是非主线程中没有创建Looper对象,需要先调用Looper.prepare()启用Looper。 解决办法是在线程的开始跟结束间调用Looper.prepa...

hei5207的博客 468

C#上位机实战:工业产线数据采集与监控系统开发(附源码思路)

模块化设计:四层架构清晰,各模块独立可替换,便于后期维护与扩展;稳定性强:支持断线重连、异常重试、并发采集,满足工业7×24小时运行需求;实用性高:覆盖产线监控核心功能,可视化组件适配工业场景,操作简单;源码可复用:通信类、采集服务、报警管理器等可直接复制到其他上位机项目。

这里只有干货:从 Modbus 通信到 MES 对接,从 YOLO 训练到工控机部署,带你搞定工业软件开发全流程。 1656

java.lang.RuntimeException: Can't create handler inside thread that has not cal

http://hi.baidu.com/donghaozheng/item/dc843d149968bf6e70d5e8e4 (1) Looper类别用来为一个线程开启一个消息循环。默认情况下Android中新诞生的线程是没有开启消息循环的。(主线程除外,主线程系统会自动为其创建Looper对象,开启消息循环) Looper对象通过MessageQueue来存放消息和事件。一个线程只能有...

shikun520的专栏 425

IDEA的使用指南

IDEA基于java的使用手册,可以最快速的上手,在使用中不断的丰富自己的使用技巧.

深度学习工具包 DeepLearningToolbox

深度学习工具包Deprecation notice.-----This toolbox is outdated and no longer maintained.There are much better tools available for deep learning than this toolbox, e.g. [Theano](http://deeplearning.net/software/theano/), [torch](http://torch.ch/) or [tensorflow](http://www.tensorflow.org/)I would suggest you use one of the tools mentioned above rather than use this toolbox.Best, Rasmus.DeepLearnToolbox================A Matlab toolbox for Deep Learning.Deep Learning is a new subfield of machine learning that focuses on learning deep hierarchical models of data.It is inspired by the human brain's apparent deep (layered, hierarchical) architecture.A good overview of the theory of Deep Learning theory is[Learning Deep Architectures for AI](http://www.iro.umontreal.ca/~bengioy/papers/ftml_book.pdf)For a more informal introduction, see the following videos by Geoffrey Hinton and Andrew Ng.* [The Next Generation of Neural Networks](http://www.youtube.com/watch?v=AyzOUbkUf3M) (Hinton, 2007)* [Recent Developments in Deep Learning](http://www.youtube.com/watch?v=VdIURAu1-aU) (Hinton, 2010)* [Unsupervised Feature Learning and Deep Learning](http://www.youtube.com/watch?v=ZmNOAtZIgIk) (Ng, 2011)If you use this toolbox in your research please cite [Prediction as a candidate for learning deep hierarchical models of data](http://www2.imm.dtu.dk/pubdb/views/publication_details.php?id=6284)```@MASTERSTHESIS\{IMM2012-06284, author = "R. B. Palm", title = "Prediction as a candidate for learning deep hierarchical models of data", year = "2012",}```Contact: rasmusbergpalm at gmail dot comDirectories included in the toolbox-----------------------------------`NN/` - A library for Feedforward Backpropagation Neural Networks`CNN/` - A library for Convolutional Neural Networks`DBN/` - A library for Deep Belief Networks`SAE/` - A library for Stacked Auto-Encoders`CAE/` - A library for Convolutional Auto-Encoders`util/` - Utility functions used by the libraries`data/` - Data used by the examples`tests/` - unit tests to verify toolbox is workingFor references on each library check REFS.mdSetup-----1. Download.2. addpath(genpath('DeepLearnToolbox'));Example: Deep Belief Network---------------------```matlabfunction test_example_DBNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit RBM and visualize its weightsrand('state',0)dbn.sizes = [100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);figure; visualize(dbn.rbm{1}.W'); % Visualize the RBM weights%% ex2 train a 100-100 hidden unit DBN and use its weights to initialize a NNrand('state',0)%train dbndbn.sizes = [100 100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);%unfold dbn to nnnn = dbnunfoldtonn(dbn, 10);nn.activation_function = 'sigm';%train nnopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.10, 'Too big error');```Example: Stacked Auto-Encoders---------------------```matlabfunction test_example_SAEload mnist_uint8;train_x = double(train_x)/255;test_x = double(test_x)/255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit SDAE and use it to initialize a FFNN% Setup and train a stacked denoising autoencoder (SDAE)rand('state',0)sae = saesetup([784 100]);sae.ae{1}.activation_function = 'sigm';sae.ae{1}.learningRate = 1;sae.ae{1}.inputZeroMaskedFraction = 0.5;opts.numepochs = 1;opts.batchsize = 100;sae = saetrain(sae, train_x, opts);visualize(sae.ae{1}.W{1}(:,2:end)')% Use the SDAE to initialize a FFNNnn = nnsetup([784 100 10]);nn.activation_function = 'sigm';nn.learningRate = 1;nn.W{1} = sae.ae{1}.W{1};% Train the FFNNopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.16, 'Too big error');```Example: Convolutional Neural Nets---------------------```matlabfunction test_example_CNNload mnist_uint8;train_x = double(reshape(train_x',28,28,60000))/255;test_x = double(reshape(test_x',28,28,10000))/255;train_y = double(train_y');test_y = double(test_y');%% ex1 Train a 6c-2s-12c-2s Convolutional neural network %will run 1 epoch in about 200 second and get around 11% error. %With 100 epochs you'll get around 1.2% errorrand('state',0)cnn.layers = { struct('type', 'i') %input layer struct('type', 'c', 'outputmaps', 6, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %sub sampling layer struct('type', 'c', 'outputmaps', 12, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %subsampling layer};cnn = cnnsetup(cnn, train_x, train_y);opts.alpha = 1;opts.batchsize = 50;opts.numepochs = 1;cnn = cnntrain(cnn, train_x, train_y, opts);[er, bad] = cnntest(cnn, test_x, test_y);%plot mean squared errorfigure; plot(cnn.rL);assert(er<0.12, 'Too big error');```Example: Neural Networks---------------------```matlabfunction test_example_NNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);% normalize[train_x, mu, sigma] = zscore(train_x);test_x = normalize(test_x, mu, sigma);%% ex1 vanilla neural netrand('state',0)nn = nnsetup([784 100 10]);opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samples[nn, L] = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.08, 'Too big error');%% ex2 neural net with L2 weight decayrand('state',0)nn = nnsetup([784 100 10]);nn.weightPenaltyL2 = 1e-4; % L2 weight decayopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex3 neural net with dropoutrand('state',0)nn = nnsetup([784 100 10]);nn.dropoutFraction = 0.5; % Dropout fraction opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex4 neural net with sigmoid activation functionrand('state',0)nn = nnsetup([784 100 10]);nn.activation_function = 'sigm'; % Sigmoid activation functionnn.learningRate = 1; % Sigm require a lower learning rateopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex5 plotting functionalityrand('state',0)nn = nnsetup([784 20 10]);opts.numepochs = 5; % Number of full sweeps through datann.output = 'softmax'; % use softmax outputopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex6 neural net with sigmoid activation and plotting of validation and training error% split training data into training and validation datavx = train_x(1:10000,:);tx = train_x(10001:end,:);vy = train_y(1:10000,:);ty = train_y(10001:end,:);rand('state',0)nn = nnsetup([784 20 10]); nn.output = 'softmax'; % use softmax outputopts.numepochs = 5; % Number of full sweeps through dataopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, tx, ty, opts, vx, vy); % nntrain takes validation set as last two arguments (optionally)[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');```[![Bitdeli Badge](https://d2weczhvl823v0.cloudfront.net/rasmusbergpalm/deeplearntoolbox/trend.png)](https://bitdeli.com/free "Bitdeli Badge")

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 Toast提示异常:java.lang.RuntimeException: Can't create handler inside thread tha...

weixin_30603633的博客 169

Outlook Express 6 (OE6) for Win7/Win8/Win10

英文版 Outlook Express6.0, 兼容Win7/Win10/WinXP,解压就可用。

android Toast提示异常:java.lang.RuntimeException: Can't create handler inside thread that has not called

android Toast提示异常:java.lang.RuntimeException: Can't create handler inside thread that has not called 仔细检查了代码,不应该异常啊??  没有 handler相关代码啊?                原来是在子线程弹Toast了, 切记,Toast只能在UI线程弹出,如果一定要在子线程弹,那么

tihi的博客 1万+

STM32F407中文手册

STM32f407中文手册 本参考手册面向应用开发人员,提供有关使用 STM32F405xx/07xx、STM32F415xx/17xx、 STM32F42xxx 和 STM32F43xxx 微控制器存储器与外设的完整信息。STM32F405xx/07xx、STM32F415xx/17xx、STM32F42xxx 和 STM32F43xxx 构成一个微 控制器系列,各产品具有不同的存储器大小、封装和外设。有关订购信息以及器件的机械与电气特性,请参见数据手册。有关 ARM Cortex™-M4F 内核的信息,请参见《Cortex™-M4F 技术参考手册》。

android java.lang.RuntimeException: Can't create handler inside thread that has not called Looper.pr

今天在华为的手机上出现java.lang.RuntimeException: Can't create handler inside thread that has not called Looper.prepare()异常,这个异常就是说不能再子线程中创建handler,但是我看了好一会代码,这段子程序并没有创建handler,于是就逐步调试,发送在调用自定义的AsyncTask的时候,程序直接

htyxz8802的专栏 1606

Android java.lang.RuntimeException: Can't create handler inside thread that has not called

在Android 5.1开发中遇到问题: 调用android.net.ethernet.EthernetManager出现问题,打印日志如下 升级代码中  FHUbootReceiver 中126行 EthManagerUtils 中接口方法如下 ./vendor/amlogic/frameworks/core/java/android/provider/fhagent/E

u010473556的博客 9351
上一篇: SwipeRefreshLayout嵌套ScrollView包裹复杂头布局和RecyclerView
下一篇: 选择头像文件操作
Dear月
博客等级 码龄10年 0粉丝 2原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

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

抵扣说明:

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

余额充值