3
    thread = new Thread() {
        public void run() {
            super.run();
            System.out.println("run:" + Thread.currentThread().getName());
            Looper.prepare();
            handler = new Handler();
            Looper.loop();
        };
    };
    thread.start();

And then

    handler.post(new Runnable() {
        @Override
        public void run() {
            Toast.makeText(MActivity.this,Thread.currentThread().getName(),0).show();
        }
    });

the code run correct.

but the toast shows :"Thread-217"

that means the toast shows from a non-uithread.

why?


I am so sorry. I know answer. Toast is a special UI element. It can be showed from any thread. But the other UI elements ,such as Button TextView must only be touched in the UI-thread. So,my code runs correct,but when you change the toast to Button ,is crashed.

Tony
  • 520
  • 4
  • 13

2 Answers2

1

You are trying to show toast in a UI thread using runnable thats why its going wrong

  Thread background = new Thread(new Runnable() {   
        public void run() {
                         // Send message to handler
                            handler.sendMessage(msgObj);
                        }
      };




      private final Handler handler = new Handler() {
               public void handleMessage(Message msg) {
                  //Catch the response and show the toast
                  String aResponse = msg.getData().getString("message");

                  Toast.makeText(getBaseContext(),"Not Got Response From Server.",
                         Toast.LENGTH_SHORT).show();
                                }
          };
Sreedev
  • 6,563
  • 5
  • 43
  • 66
  • I means the toast.show() should run on a separate thread.because the handler is created in that non-uithread. but the code run correct. so we can touch UI on non-uithread? – Tony Jul 15 '14 at 10:22
  • You are not suppose to show toast on non UI thread it will crash for sure....Toast should always be in UI thread. – Sreedev Jul 15 '14 at 10:48
1

You must create the Handler in UiThread. The handler send the message to thread where it was created.

handler = new Handler();

thread = new Thread() {
        public void run() {
            super.run();
            System.out.println("run:" + Thread.currentThread().getName());
            Looper.prepare();
            Looper.loop();
        };
    };
    thread.start();
MiguelAngel_LV
  • 1,200
  • 5
  • 16