SoFunction
Updated on 2025-04-08

Android updates UI using Handler and Message

In Android, it is not safe to update UI controls in non-main threads. The app will directly Crash when running. So when we need to update UI controls in non-main threads, we need to use Handler and Message to implement it.
In the demo, use a button and a TextView. After clicking the button, change the content of the TextView. When the button is clicked, create a new process and modify the UI controls in the process.

public class MainActivity extends Activity implements OnClickListener {
  private static final int UPDATE_TEXT = 1;
  private Button send;
  private TextView tv;
  
  private Handler hd = new MyHandler();

  @Override
  protected void onCreate(Bundle savedInstanceState) {
    (savedInstanceState);
    setContentView(.activity_main);
    send = (Button) findViewById(.bt_sendMessage);
    tv = (TextView) findViewById(.tv_text);
    (this);
  }

  @Override
  public void onClick(View v) {
    switch (()) {
    case .bt_sendMessage:
      new Thread(new Runnable() {
        @Override
        public void run() { // Create a new thread and create a new Message object. Use the Handler object to send this Message          Message msg = new Message();
           = UPDATE_TEXT; // A user-defined value used to identify different types of messages          (msg); // Send a message        }
      }).start();
      break;

    default:
      break;
    }
  }
  
  // Define an internal class inherited from Handler and override the handleMessage method to handle messages transmitted by child threads  class MyHandler extends Handler{
    @Override
    public void handleMessage(Message msg) {
      (msg);
      switch () {
      case UPDATE_TEXT: // After receiving the message, modify the UI control        ("The modification was successful!");
        break;

      default:
        break;
      }
    }
  }
}

understand:First, define an inner class in the main activity, inherit it from the Handler, and overwrite the handleMessage method in the Handler. This method is an empty method in the Handler, which makes it easier for us to customize the content of the message. Then in the onCreate method, get the Button and add a click event, add a thread to the event. In the thread, use the Message class to encapsulate a message, and then send the message with the Handler object. The handleMessage method of the Handler object will be called to achieve the effect of changing the content of the TextView.

The above is all the content of this article. I hope it will be helpful to everyone's study and I hope everyone will support me more.