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

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

How can I display Toast messages from a thread?

11条回答
  •  我寻月下人不归
    2020-11-22 05:56

    You can use Looper to send Toast message. Go through this link for more details.

    public void showToastInThread(final Context context,final String str){
        Looper.prepare();
        MessageQueue queue = Looper.myQueue();
        queue.addIdleHandler(new IdleHandler() {
             int mReqCount = 0;
    
             @Override
             public boolean queueIdle() {
                 if (++mReqCount == 2) {
                      Looper.myLooper().quit();
                      return false;
                 } else
                      return true;
             }
        });
        Toast.makeText(context, str,Toast.LENGTH_LONG).show();      
        Looper.loop();
    }
    

    and it is called in your thread. Context may be Activity.getContext() getting from the Activity you have to show the toast.

提交回复
热议问题