Can't toast on a thread that has not called Looper.prepare()

前言

最近一段时间在忙着开发一款自己的APP,将自己常用的功能需求都加入进入,同时在GitHub上跟着大牛们学习新的技术,提升自己的技能,在开发的过程中不断的发现问题和解决问题。
在开发过程遇到了这样一个问题:Can't toast on a thread that has not called Looper.prepare(),如果在一个线程中没有调用Looper.prepare(),就不能在该线程中创建Toast。这个问题是因为在子线程中弹出Toast导致的。
Android是不能直接在子线程中弹出Toast的,可是如果我们非要这么做,那该怎么办呢?下面就为大家讲解如何在子线程中弹出Toast,以及一些其他类似的子线程中操作的错误。

本博客同步发布于XueLong的博客

在子线程中调用Toast

在子线程中弹出Toast,会报错:java.lang.RuntimeException: Can't toast on a thread that has not called Looper.prepare()。

解决方式:先调用Looper.prepare();再调用Toast.makeText().show();最后再调用Looper.loop();

public class ToastUtils {
    static Toast toast = null;
    public static void show(Context context, String text) {
        try {
            if(toast!=null){
                toast.setText(text);
            }else{
                toast= Toast.makeText(context, text, Toast.LENGTH_SHORT);
            }
            toast.show();
        } catch (Exception e) {
            //解决在子线程中调用Toast的异常情况处理
            Looper.prepare();
            Toast.makeText(context, text, Toast.LENGTH_SHORT).show();
            Looper.loop();
        }
    }
}

在子线程中更新UI

在子线程中更新UI,会报错:android.view.ViewRootImpl$CalledFromWrongThreadException: Only the original thread that created a view hierarchy can touch its views.

解决方式:在子线程中更新UI,一般使用Handler或者runOnUiThread()或者AsyncTask。

在子线程中创建Handler

在子线程中创建Handler,会报错:java.lang.RuntimeException: Can't create handler inside thread that has not called Looper.prepare()。

解决方式:

new Thread() {
  public void run() {
    Looper.prepare();
    new Handler().post(runnable);//在子线程中直接去new 一个handler
    Looper.loop();    //这种情况下,Runnable对象是运行在子线程中的,可以进行联网操作,但是不能更新UI
  }
}.start();

写在最后

以上就是在子线程中更新UI、弹出Toast、创建Handler时会遇到的问题,及解决方式。

  • 2
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值