Can't toast on a thread that has not called Looper.prepare()

前端 未结 2 1692
死守一世寂寞
死守一世寂寞 2020-12-16 10:28

I try to run a test for my android app but I get this trace. What does it mean?

java.lang.RuntimeException: Can\'t toast on a thread that has not called Loop         


        
相关标签:
2条回答
  • 2020-12-16 11:11

    You CANNOT show a Toast on non-UI thread. You need to call Toast.makeText() (and most other functions dealing with the UI) from within the main thread.


    You could use Activity#runOnUiThread():

    runOnUiThread(new Runnable() {
          public void run() {
             final Toast toast = Toast.makeText(context, "GAME OVER!\nScore: " + score, duration);
             toast.show();
          }
     });
    

    If you want execute a instrumentation test on main thread, add @UiThreadTest annotation:

    @Test
    @UiThreadTest
    public void useAppContext() {
        // ...
    }
    

    P.s: There are also many other ways with explain (using Handler, Looper, Observable..) in these posts: Android: Toast in a thread and Can't create handler inside thread that has not called Looper.prepare()

    0 讨论(0)
  • 2020-12-16 11:12

    In kotlin put your code inside this:

    runOnUiThread { 
        Log.i(TAG, "runOnUiThread")
        Toast.makeText(MainActivity.this, "Play", Toast.LENGTH_SHORT).show()
    }
    
    0 讨论(0)
提交回复
热议问题