下面的异常是什么意思;我该怎么解决呢?

这是代码:

Toast toast = Toast.makeText(mContext, "Something", Toast.LENGTH_SHORT);

这是例外:

java.lang.RuntimeException: Can't create handler inside thread that has not called Looper.prepare()
     at android.os.Handler.<init>(Handler.java:121)
     at android.widget.Toast.<init>(Toast.java:68)
     at android.widget.Toast.makeText(Toast.java:231)

当前回答

这通常发生在从任何后台线程调用主线程上的某些内容时。让我们看一个例子。

private class MyTask extends AsyncTask<Void, Void, Void> {


@Override
protected Void doInBackground(Void... voids) {
        textView.setText("Any Text");
        return null;
    }
}

在上面的例子中,我们通过doInBackground()方法在主UI线程中的textview上设置文本,该方法只在工作线程上操作。

其他回答

你需要在UI线程上创建吐司。请看下面的例子。

runOnUiThread(new Runnable() {
  public void run() {
    Toast.makeText(activity, "YOUR_MESSAGE", Toast.LENGTH_SHORT).show();
  }
});

要显示Toast消息,请参考这篇文章

Java 8

new Handler(Looper.getMainLooper()).post(() -> {
    // Work in the UI thread

}); 

科特林

Handler(Looper.getMainLooper()).post{
    // Work in the UI thread
}

GL

Rxjava和RxAndroid用户:

public static void shortToast(String msg) {
    Observable.just(msg)
            .observeOn(AndroidSchedulers.mainThread())
            .subscribe(message -> {
                Toast.makeText(App.getInstance(), message, Toast.LENGTH_SHORT).show();
            });
}

协同程序会很好地做到这一点

CoroutineScope(Job() + Dispatchers.Main).launch {
                        Toast.makeText(context, "yourmessage",Toast.LENGTH_LONG).show()}

我就是这么做的。

new Handler(Looper.getMainLooper()).post(new Runnable() {
    @Override
    public void run() {
        Toast(...);
    }
});

可视组件“锁定”于来自外部线程的更改。 因此,由于toast在主屏幕上显示由主线程管理的内容,您需要在主线程上运行这段代码。 希望这对你有所帮助。