public class ToastUtil {
private static Toast toast = null;
public static void showToast(Context context,String content){
if (toast != null){
toast.cancel();
}
Looper.prepare();
toast = Toast.makeText(context,content,Toast.LENGTH_SHORT);
toast.show();
Looper.loop();
}
public static void showToast(Context context,int resid){
showToast(context,context.getString(resid));
}
}
这是我封装的Toast的代码,其实也就是在网上下载的,我是定义了一个接口,接口里面会用到这个方法,然后接口的方法会在Asynctask中使用,有的时候就会报错toast Can't create handler inside thread that has not called Looper.prepare(),然后在网上搜索,网上的说在 toast = Toast.makeText(context,content,Toast.LENGTH_SHORT);
toast.show();前面加上Looper.prepare();后面加上 Looper.loop();(刚开始我是没有加的),然后就会报错Only one Looper may be created per thread。。。
这是为什么啊?
asynctask的实现机制在不同API版本里是有区别的,你使用的是哪个版本的?而且你是在asynctask的哪个回调方法里showtoast的?
你百度一下,用Android的handler,在要弹toast的地方sendemptymessage,在handler的处理消息函数里用toast
口的回调放在doinbackground里面,处理在子线程中了
showToast属于ui操作,你在非UI线程调用怎么能不报错,还有doInbackgroud是子线程处理耗时的,你试着放到postXX下看看,还有这个封装有必要么?