SoFunction
Updated on 2025-03-11

Detailed explanation of message passing between android main thread and child thread

Send messages from the main thread to the child thread (to be precise, it should be a non-UI thread)

package ;
import ;
import ;
import ;
import ;
import ;
import ;
import ;
import ;

public class LooperThreadActivity extends Activity{
 /** Called when the activity is first created. */
 
 private final int MSG_HELLO = 0;
 private Handler mHandler;
 
 @Override
 public void onCreate(Bundle savedInstanceState) {
  (savedInstanceState);
  setContentView();
  new CustomThread().start();//Create and start CustomThread instance  
  findViewById(.send_btn).setOnClickListener(new OnClickListener() {
   
   @Override
   public void onClick(View v) {//Send a message when clicking on the interface    String str = "hello";
    ("Test", "MainThread is ready to send msg:" + str);
    (MSG_HELLO, str).sendToTarget();//Send a message to the CustomThread instance    
   }
  });
  
 }
 
 
 
 
 
 class CustomThread extends Thread {
  @Override
  public void run() {
   //Step to establish a message loop   ();//1. Initialize Looper   mHandler = new Handler(){//2. Bind handler to the Looper object of CustomThread instance    public void handleMessage (Message msg) {//3. Define the method of processing messages     switch() {
     case MSG_HELLO:
      ("Test", "CustomThread receive msg:" + (String) );
     }
    }
   };
   ();//4. Start the message loop  }
 }
}

Pass messages from non-UI threads to UI threads (interface main thread), because the main interface already has MessageQueue, you can directly obtain message processing messages. When processing messages from the main thread to a non-UI thread above, the non-UI thread needs to add a message queue first and then process the message loop.

public class ThreadHandlerActivity extends Activity {
 /** Called when the activity is first created. */
 
 private static final int MSG_SUCCESS = 0;//Get the image's successful logo private static final int MSG_FAILURE = 1;//Get the image failed to get the logo 
 private ImageView mImageView;
 private Button mButton;
 
 private Thread mThread;
 
 private Handler mHandler = new Handler() {
  public void handleMessage (Message msg) {//This method runs in the ui thread   switch() {
   case MSG_SUCCESS:
    ((Bitmap) );//imageview displays the logo obtained from the network    (getApplication(), getApplication().getString(.get_pic_success), Toast.LENGTH_LONG).show();
    break;

   case MSG_FAILURE:
    (getApplication(), getApplication().getString(.get_pic_failure), Toast.LENGTH_LONG).show();
    break;
   }
  }
 };
 
 @Override
 public void onCreate(Bundle savedInstanceState) {
  (savedInstanceState);
  setContentView();
  mImageView= (ImageView) findViewById();//ImageView showing the image  mButton = (Button) findViewById();
  (new OnClickListener() {
   
   @Override
   public void onClick(View v) {
    if(mThread == null) {
     mThread = new Thread(runnable);
     ();//Thread starts    }
    else {
     (getApplication(), getApplication().getString(.thread_started), Toast.LENGTH_LONG).show();
    }
   }
  });
 }
 
 Runnable runnable = new Runnable() {
  
  @Override
  public void run() {//run() runs in a new thread   HttpClient hc = new DefaultHttpClient();
   HttpGet hg = new HttpGet("/www/images/csdnindex_logo.gif");//Get csdn's logo   final Bitmap bm;
   try {
    HttpResponse hr = (hg);
    bm = (().getContent());
   } catch (Exception e) {
    (MSG_FAILURE).sendToTarget();//Failed to get the picture    return;
   }
   (MSG_SUCCESS,bm).sendToTarget();//Successfully obtain the image, send the MSG_SUCCESS ID and bitmap object to the ui thread
// (bm); // Error!  Cannot operate ui elements in non-ui threads
// (new Runnable() {// Another simpler method to send messages to ui threads.//    
//    @Override
// public void run() {//run() method will be executed in the ui thread//     (bm);
//    }
//   });
  }
 };

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.