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

这是代码:

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)

当前回答

Toast.makeText()只能从Main/UI线程调用。loop . getmainlooper()帮助你实现它:

JAVA

new Handler(Looper.getMainLooper()).post(new Runnable() {
    @Override
    public void run() {
        // write your code here
    }
});

科特林

Handler(Looper.getMainLooper()).post {
        // write your code here
}

这种方法的优点是您可以在没有活动或上下文的情况下运行UI代码。

其他回答

我得到了同样的问题,这段代码为我工作很好。 作为一个例子,这是我的代码做一个任务在后台和UI线程。 观察如何使用套筒:

new Thread(new Runnable() {
    @Override
    public void run() {
    Looper.prepare();
                                
    // your Background Task here

    runOnUiThread(new Runnable() {
        @Override
        public void run() {

        // update your UI here      
                                
        Looper.loop();
        }
    });
    }
}).start();

错误原因:

工作线程是用来做后台任务的,你不能在工作线程的UI上显示任何东西,除非你调用像runOnUiThread这样的方法。如果你试图在UI线程上显示任何东西而不调用runOnUiThread,将会有一个java.lang.RuntimeException。

所以,如果你在一个活动中,但从工作线程调用Toast.makeText(),这样做:

runOnUiThread(new Runnable() 
{
   public void run() 
   {
      Toast toast = Toast.makeText(getApplicationContext(), "Something", Toast.LENGTH_SHORT).show();    
   }
}); 

上面的代码确保您在UI线程中显示Toast消息,因为您是在runOnUiThread方法中调用它。所以不再有java.lang.RuntimeException。

尝试这个,当你看到runtimeException由于循环程序没有准备之前的处理程序。

Handler handler = new Handler(Looper.getMainLooper()); 

handler.postDelayed(new Runnable() {
  @Override
  public void run() {
  // Run your task here
  }
}, 1000 );

下面是Kotlin使用Coroutine的解决方案:

通过MainScope()使用CoroutineScope扩展类:

class BootstrapActivity :  CoroutineScope by MainScope() {}

然后简单地这样做:

launch {
        // whatever you want to do in the main thread
    }

不要忘记添加协程的依赖项:

org.jetbrains.kotlinx:kotlinx-coroutines-core:${Versions.kotlinCoroutines}
org.jetbrains.kotlinx:kotlinx-coroutines-android:${Versions.kotlinCoroutines}

首先调用loop .prepare(),然后调用Toast.makeText().show()最后调用loop .loop():

Looper.prepare() // to be able to make toast
Toast.makeText(context, "not connected", Toast.LENGTH_LONG).show()
Looper.loop()