toast 线程问题

在开发过程遇到了这样一个问题: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

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。