Android only allows the UI thread to modify the UI components in the activity. When the Android program starts for the first time, Android initiates a primary thread (main thread), which is primarily responsible for handling UI-related events, such as user keystroke events, screen drawing events, and distributing related events to the corresponding component for processing. SoThe main thread is also often referred to as the UI thread。 Android only allows the UI thread to modify the UI component in the activity, which causes the newly-started thread to not dynamically change the property values of the interface components. However, in the actual development of Android program, especially in the game development involving animation, it is necessary to let the newly-started thread change the property value of the interface component periodically, which requires the help ofmessage passing mechanism of handlerTo achieve it. 1 Handler class Introduction The main role of the handler class is two: (1) Send a message in a newly started thread SendMessage (message msg) or sendemptymessage (int what) The difference between the two, see Android source code: Public Final Boolean sendMessage (Message msg) {return sendmessagedelayed ( MSG, 0);} Public Final Boolean sendemptymessage (int.) {return sendemptymessagedelayed (what, 0);} See sendemptymessagedelayed (What, 0) source code: Public Final Boolean sendemptymessagedelayed (int what, long Delaymillis) { Message msg = Message.obtain (); msg.what = What;return sendmessagedelayed (msg, delaymillis);} In fact, SendMessage (message msg) and Sendemptymessage (int what) are actually the same, A message type of MSG, a type of what is an int, what to preach, and eventually turn to MSG. (2) Get and process messages in the main thread public void Handlemessage (message msg) 2 Use the handler and the timer class to implement the automatic refresh of the time
public class Mainactivity extends Activity {@Overrideprotected void onCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate); Setcontentview (R.layout.activity_main); final TextView txt= (TextView) Findviewbyid ( R.id.showtime), Final Handler myhandler=new Handler () {@Overridepublic void Handlemessage (Message msg) {if (msg.what== 0x12) {Txt.settext ("Current time:" +new java.util.Date ());}}; Button btn= (button) Findviewbyid (R.ID.BTN) Btn.setonclicklistener (new Onclicklistener () {@Overridepublic void OnClick (View arg0) {//TODO auto-generated method Stubnew Timer (). Schedule (new TimerTask () {@Overridepublic void Run () {// TODO auto-generated Method Stubmyhandler.sendemptymessage (0x12),}, 0,1000);}}); @Overridepublic boolean Oncreateoptionsmenu (Menu menu) {//Inflate the menu; This adds items to the action bar if it is PR Esent.getmenuinflater (). Inflate (R.menu.main, menu); return true;}}
Android Learning handler message delivery mechanism