EAndroidRuntime FATAL EXCEPTION OkHttp Dispatcher Process comexamplezhcs3 PID 13853 javalangRuntimeException Cant toast on a thread that has not called Looperprepare at androidwidgetToast
这个错误是因为在非主线程中调用了Toast.makeText()方法导致的。Toast只能在主线程中调用,否则会抛出这个异常。
你可以在调用Toast.makeText()之前使用Looper.prepare()方法来准备Looper,确保在该线程中可以使用Toast。同时,你还需要在使用完Toast后调用Looper.loop()方法来开始处理消息队列。
以下是一个修复这个问题的示例代码:
new Thread(new Runnable() {
@Override
public void run() {
// 在非主线程中调用Toast
Looper.prepare();
Toast.makeText(context, "Message", Toast.LENGTH_SHORT).show();
Looper.loop();
}
}).start();
注意:使用Toast.makeText()时,第一个参数需要传入一个Context对象,比如Activity或Application的实例
原文地址: http://www.cveoy.top/t/topic/ib63 著作权归作者所有。请勿转载和采集!