欢迎访问 生活随笔!

生活随笔

当前位置: 首页 > 编程资源 > 编程问答 >内容正文

编程问答

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

发布时间:2023/12/19 编程问答 49 豆豆
生活随笔 收集整理的这篇文章主要介绍了 Can't create handler inside thread that has not called Looper.prepare() 解决办法 小编觉得挺不错的,现在分享给大家,帮大家做个参考.

在开发的过程当中,遇到了想在一个线程中弹出一个提示窗 new AlertDialog.Builder(
           context),但是就出现了一个问题。

 

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

分析了一下原因,应该是不能在线程中操作UI界面。

然后我就就在线程里面新开一个线程,再配上hangler通信 但是还是有错误,最后查看了handler才知道是没有getMainLooper()。

因为在UI主线程之外是无法对UI组件进行控制的。因为你必须在新线程任务完成之后利用各种方法先UI主线程发送消息通知任务完成从而来显示各种提示消息。

 

最后变成这样,搞掂了

new Thread() {@Overridepublic void run() {Message msg = new Message();msg.what = 0;handler.sendMessage(msg);}}.start();handler = new Handler(context.getMainLooper()) {@Overridepublic void handleMessage(Message msg) {if (0 == msg.what) {new AlertDialog.Builder(context).setTitle("提示").setIcon(R.drawable.icon).setMessage("确定要回到打乱状态吗!!").setPositiveButton("确定",new DialogInterface.OnClickListener() {public void onClick(DialogInterface arg0,int arg1) {rBlockGroup.setmap(replayStart);gamestart = GAMESTATR_REPLAY;// replayCount = 0;// repalyCurrentStep =// 0;replayState = GAMESTATR_RUN;}}).setNegativeButton("取消",new DialogInterface.OnClickListener() {@Overridepublic void onClick(DialogInterface arg0,int arg1) {}}).create().show();}}};

 

 

 

转载于:https://www.cnblogs.com/mczha/p/3655875.html

创作挑战赛新人创作奖励来咯,坚持创作打卡瓜分现金大奖

总结

以上是生活随笔为你收集整理的Can't create handler inside thread that has not called Looper.prepare() 解决办法的全部内容,希望文章能够帮你解决所遇到的问题。

如果觉得生活随笔网站内容还不错,欢迎将生活随笔推荐给好友。