Android-based Handler message transmission mechanism, androidhandler
Android only allows the UI thread to modify the UI components in the Activity. When the Android program is started for the first time, Android will start a Main Thread at the same time. The Main Thread is mainly responsible for processing UI-related events, such as user button events and Screen Drawing events, and distribute related events to corresponding components for processing. Therefore, the main thread is often called the UI thread. Android only allows the UI thread to modify the UI component in the Activity. This will make the newly started thread unable to dynamically change the attribute value of the interface component. However, in actual Android development, especially in game development involving animation, the attribute values of interface components must be changed periodically by the newly started thread, therefore, the Handler message transmission mechanism is required. 1. Handler class introduction Handler class has two main functions: (1) the difference between sendMessage (Message msg) and sendEmptyMessage (int what) sent in the newly started thread, please refer to the Android source code: public final boolean sendMessage (Message msg) {return sendMessageDelayed (msg, 0);} public final boolean sendEmptyMessage (int what) {return sendEmptyMessageDelayed (what, 0);} Check sendEmptyMessageDelayed (what, 0) source code: public final boolean sendEmptyMessageDelayed (int what, long delayMillis) {Mess Age 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 msg, A message of the int type is converted to msg. (2) obtain and process the public void handleMessage (Message msg) in the main thread. 2. Use the Handler and Timer classes under the instance to automatically refresh 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) ;}},) ;}}) ;}@ Overridepublic boolean onCreateOptionsMenu (Menu menu) {// Inflate the menu; this adds items to the action bar if it is present. getMenuInflater (). inflate (R. menu. main, menu); return true ;}}