In the main UI thread, the system has initialized a Looper object, so the program creates handler directly, then posts handler to send messages and process messages.
The program ape itself initiates the child thread, the program ape must create itself a Looper object, and start it, create the Looper object to call his prepare () method. The method
Ensure that each thread has a maximum of one Lopper object
Calling Looper's Prepare () method creates a Looper object for the current thread, and when the Looper object is created, his constructor creates a matching MessageQueue
Call Looper's Loop () method to start Lopper.
The following is an example of calculating prime numbers with new threads
public class Mainactivity extends Activity {
Private EditText et;
Private Button BT;
Private TextView TV;
Static final String Upper_num = "UPPER";
Calthread Calthread;
Class Calthread extends Thread {
Public Handler Mhandler;
@Override
public void Run () {
Looper.prepare ();
Mhandler = new Handler () {
@Override
public void Handlemessage (Message msg) {
if (msg.what = = 0x123) {
int upper = Msg.getdata (). GetInt (Upper_num);
list<integer> nums = new arraylist<integer> ();
outer:for (int i = 2; i <= upper; i++) {
for (int j = 2; J <= Math.sqrt (i); j + +) {
if (i! = 2 && I% J = = 0) {
Continue outer;
}
}
Nums.add (i);
}
Toast.maketext (Mainactivity.this, nums.tostring (),
Toast.length_short). Show ();
}
}
};
Looper.loop ();
}
}
@Override
protected void OnCreate (Bundle savedinstancestate) {
Super.oncreate (savedinstancestate);
Setcontentview (R.layout.activity_main);
ET = (EditText) Findviewbyid (R.ID.EDITTEXT1);
BT = (Button) Findviewbyid (R.id.button1);
TV = (TextView) Findviewbyid (R.ID.TEXTVIEW1);
Calthread = new Calthread ();
Calthread.start ();
Bt.setonclicklistener (New Onclicklistener () {
@Override
public void OnClick (View arg0) {
Message ms = new Message ();
Ms.what = 0x123;
Bundle bundle = new bundle ();
Bundle.putint (Upper_num, Integer.parseint (Et.gettext (). toString ()));
Ms.setdata (bundle);
Calthread.mhandler.sendMessage (MS);
}
});
}
}
Android Handler Thread Looper combined usage