The code is as follows:
1 PackageCom.wyl.handler_mars;2 3 Importandroid.app.Activity;4 ImportAndroid.os.Bundle;5 ImportAndroid.os.Handler;6 ImportAndroid.os.Looper;7 ImportAndroid.os.Message;8 ImportAndroid.util.Log;9 ImportAndroid.view.View;Ten ImportAndroid.view.View.OnClickListener; One ImportAndroid.widget.Button; A ImportAndroid.widget.TextView; - ImportAndroid.widget.Toast; - /** the * The main thread sends the message, the worker thread receives the message - * @authorWyl - * - */ + Public classSecondactivityextendsActivityImplementsonclicklistener{ - Button Btn_fasong; + Handler hand; A Message msg; at TextView TV; - @Override - protected voidonCreate (Bundle savedinstancestate) { - //TODO auto-generated Method Stub - Super. OnCreate (savedinstancestate); - Setcontentview (r.layout.main2); inBtn_fasong =(Button) Findviewbyid (r.id.btn_send); -TV =(TextView) Findviewbyid (r.id.tv_01); toBtn_fasong.setonclicklistener ( This); +Thread T =NewMyThread (); - T.start (); the } * @Override $ Public voidOnClick (View v) {Panax Notoginseng //hand = new Handler ();//This line is especially important, if not commented out, then the following thread will not be able to receive the message, because this line of code to regenerate a handler object, also corresponds to a different looper, so there is no -Message msg =hand.obtainmessage (); theMsg.obj = "No words anymore ... "; +System.out.println ("OnClick () ... Send: "+" no words anymore ... "); AHand.sendmessage (msg);//The main thread sends a message the } + - $ classMyThreadextendsthread{ $ - @Override - Public voidrun () { theLooper.prepare ();//gets a Looper object -System.out.println ("===========");WuyiHand =NewHandler () { the - @Override Wu Public voidhandlemessage (Message msg) { - //TODO auto-generated Method Stub AboutSystem.out.println ("Mythread.run () received the message" + ", the thread:" +Thread.CurrentThread (). GetName ()); $ } - }; - Looper.loop (); - } A + } the}
Handler a reason why the data in the message queue cannot be removed