美文网首页
toast 线程问题

toast 线程问题

作者: Robin丶丨 | 来源:发表于2019-11-28 12:33 被阅读0次

在开发过程遇到了这样一个问题:Can't toast on a thread that has not called Looper.prepare(),如果在一个线程中没有调用Looper.prepare(),就不能在该线程中创建Toast。这个问题是因为在子线程中弹出Toast导致的。

Android是不能直接在子线程中弹出Toast的,可是如果我们非要这么做,那该怎么办呢?下面就为大家讲解如何在子线程中弹出Toast,以及一些其他类似的子线程中操作的错误。

在子线程中调用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 static void show(Context context, String message) {

if (TextUtils.isEmpty(message)) {

return;

    }

try {

if (toast !=null) {

toast.setText(message);

        }else {

toast = Toast.makeText(context, message, Toast.LENGTH_SHORT);

        }

toast.show();

    }catch (Exception e) {

//解决在子线程中调用Toast的异常情况处理

        Looper.prepare();

        Toast.makeText(context, message, 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()。

解决方式:

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

转载:链接:https://www.jianshu.com/p/4551734b3c21

相关文章

网友评论

      本文标题:toast 线程问题

      本文链接:https://www.haomeiwen.com/subject/yetbwctx.html