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() 解决办法的全部內容,希望文章能夠幫你解決所遇到的問題。