How do you display a Toast from a background thread on Android?

后端 未结 11 1857
难免孤独
难免孤独 2020-11-22 05:03

How can I display Toast messages from a thread?

11条回答
  •  囚心锁ツ
    2020-11-22 05:50

    I encountered the same problem:

    E/AndroidRuntime: FATAL EXCEPTION: Thread-4
                  Process: com.example.languoguang.welcomeapp, PID: 4724
                  java.lang.RuntimeException: Can't toast on a thread that has not called Looper.prepare()
                      at android.widget.Toast$TN.(Toast.java:393)
                      at android.widget.Toast.(Toast.java:117)
                      at android.widget.Toast.makeText(Toast.java:280)
                      at android.widget.Toast.makeText(Toast.java:270)
                      at com.example.languoguang.welcomeapp.MainActivity$1.run(MainActivity.java:51)
                      at java.lang.Thread.run(Thread.java:764)
    I/Process: Sending signal. PID: 4724 SIG: 9
    Application terminated.
    

    Before: onCreate function

    Thread thread = new Thread(new Runnable() {
        @Override
        public void run() {
            Toast.makeText(getBaseContext(), "Thread", Toast.LENGTH_LONG).show();
        }
    });
    thread.start();
    

    After: onCreate function

    runOnUiThread(new Runnable() {
        @Override
        public void run() {
            Toast.makeText(getBaseContext(), "Thread", Toast.LENGTH_LONG).show();
        }
    });
    

    it worked.

提交回复
热议问题