如果在子线程中直接显示Toast:
Toast.makeText(context, "测试", Toast.LENGTH_SHORT).show();
运行时就会出现如下异常:
java.lang.RuntimeException: Can't toast on a thread that has not called Looper.prepare()
原因是Android中不允许在子线程中处理UI。如果要在子线程中处理UI那就要动态转到主线程中执行,所以常用的3个解决方法如下:
1.使用Looper。
Looper.prepare();
Toast.makeText(context, "测试", Toast.LENGTH_SHORT).show();
Looper.loop();
2.如果代码是在Activity中,可以使用runOnUiThread。
runOnUiThread(new Runnable() {
@Override
public void run() {
Toast.makeText(context, "测试", Toast.LENGTH_SHORT).show();
}
});
3.使用rxjava。
Observable.just(1L)
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(a -> {
Toast.makeText(context, "测试", Toast.LENGTH_SHORT).show();
}, throwable -> {
throwable.printStackTrace();
});