Can't create handler inside thread that has not called Looper.prepare() 解决办法
生活随笔
收集整理的这篇文章主要介绍了
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() 解决办法的全部内容,希望文章能够帮你解决所遇到的问题。
- 上一篇: JVM内存结构图解
- 下一篇: f-measure[转]