Messaging between the main thread of the Android and the child threads

Source: Internet
Author: User
Tags message queue

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

Package Com.zhuozhuo;
Import android.app.Activity;
Import Android.os.Bundle;
Import Android.os.Handler;
Import Android.os.Looper;
Import Android.os.Message;
Import Android.util.Log;
Import Android.view.View;
Import Android.view.View.OnClickListener;

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) {
Super.oncreate (savedinstancestate);
Setcontentview (R.layout.main);
New Customthread (). Start ();//new and start Customthread instance

Findviewbyid (R.ID.SEND_BTN). Setonclicklistener (New Onclicklistener () {

@Override
public void OnClick (View v) {///click on interface to send message
String str = "Hello";
LOG.D ("Test", "Mainthread is ready to send msg:" + str);
Mhandler.obtainmessage (Msg_hello, str). Sendtotarget ();//Send message to Customthread instance

}
});

}





Class Customthread extends Thread {
@Override
public void Run () {
Steps to establish a message loop
Looper.prepare ();//1, initializing Looper
Mhandler = new Handler () {//2, Looper object bound Handler to Customthread instance
public void Handlemessage (message msg) {//3, defining methods for handling messages
Switch (msg.what) {
Case Msg_hello:
LOG.D ("Test", "Customthread receive msg:" + (String) msg.obj);
}
}
};
Looper.loop ();//4, start message loop
}
}
}

The message is passed from a non-UI thread to the UI thread (the main thread of the interface) because the main interface is already MessageQueue, so you can get the message processing message directly. When the message is processed from the main thread to a non-UI thread, the non-UI thread needs to add the 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 Picture Successful identity
private static final int msg_failure = 1;//Get Picture failed identity

Private ImageView Mimageview;
Private Button Mbutton;

Private Thread Mthread;

Private Handler Mhandler = new Handler () {
public void Handlemessage (Message msg) {//This method runs on the UI thread
Switch (msg.what) {
Case Msg_success:
Mimageview.setimagebitmap ((Bitmap) msg.obj)//imageview show the logo obtained from the network
Toast.maketext (Getapplication (), Getapplication (). getString (r.string.get_pic_success), Toast.length_long). Show () ;
Break

Case Msg_failure:
Toast.maketext (Getapplication (), Getapplication (). getString (R.string.get_pic_failure), Toast.length_long). Show () ;
Break
}
}
};

@Override
public void OnCreate (Bundle savedinstancestate) {
Super.oncreate (savedinstancestate);
Setcontentview (R.layout.main);
mimageview= (ImageView) Findviewbyid (R.id.imageview);//Display Picture ImageView
Mbutton = (Button) Findviewbyid (R.id.button);
Mbutton.setonclicklistener (New Onclicklistener () {

@Override
public void OnClick (View v) {
if (Mthread = = null) {
Mthread = new Thread (runnable);
Mthread.start ();//thread Start
}
else {
Toast.maketext (Getapplication (), Getapplication (). getString (r.string.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 ("Http://csdnimg.cn/www/images/csdnindex_logo.gif");//Get CSDN logo
Final Bitmap BM;
try {
HttpResponse hr = Hc.execute (Hg);
BM = Bitmapfactory.decodestream (Hr.getentity (). getcontent ());
} catch (Exception e) {
Mhandler.obtainmessage (msg_failure). Sendtotarget ();//failed to get picture
Return
}
Mhandler.obtainmessage (MSG_SUCCESS,BM). Sendtotarget ();//Get picture successful, send msg_success identity and bitmap object to UI thread

Mimageview.setimagebitmap (BM); Error! UI elements cannot be manipulated on non-UI threads

Mimageview.post (New Runnable () {///Another more concise way to send messages to the UI thread.
//
@Override
The public void Run () {//run () method executes on the UI thread
Mimageview.setimagebitmap (BM);
//                }
//            });
}
};

}

Messaging between the main thread of the Android and the child threads

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.