View. post(Runnable Runnable)

Using the View object, the post method is called to execute the code in the main thread, and the same effect can be achieved with postDelayed execution. Such as:

textView.post(new Runnable() {
     @Override
     public void run(a) {
         textView.setText("Update textView"); }});Copy the code

RunOnUiThread (Runnable Runnable)

Call runOnUiThread directly in Acitivity or pass the Activity’s context object into a child thread. Such as:

runOnUiThread(new Runnable() {
    public void run(a) {
        textView.setText("Update textView"); }}Copy the code

Handler. Post (Runnable Runnable)

If the thread is in the main thread, you can simply new a Handler object, and if the child thread needs to fetch the main thread’s Looper and Queue

/ / main thread
Handler handler = new Handler();
/ / the child thread
Handler handler = new Handler(Looper.getMainLooper());

Copy the code

Then call the POST method, or postAtTime or postAtDelayed. Such as:

handler.post(new Runnable() {
      @Override
      public void run(a) {
           textView.setText("Update textView"); }});Copy the code

Handler. SendMessage (Message Message)

This is a common way to send a message via sendMessage and process it in handleMessage. Such as:

Handler handler = new Handler() {
      @Override
      public void handleMessage(Message msg) {
          super.handleMessage(msg);
          // Process the message
          textView.setText("Update textView" + msg);
          switch(msg.what) {
                case 0:
                      // Process the specified message
                      break; }}}; handler.sendEmptyMessage(0);

Copy the code

Method 5: Use AsynTask

 AsyncTask asyncTask = new AsyncTask() {
      @Override
      protected Object doInBackground(Object[] objects) {
          return null;
      }

      @Override
      protected void onPostExecute(Object o) {
          super.onPostExecute(o); }};Copy the code

The doInBackground method is executed in the child thread, and the result is passed to the onPostExecute method, which runs on the main thread.

These are a few common methods to switch to the main thread execution, I hope to help you.