Android has a rule that allows the UI thread to modify only the UI components in the activity. The main thread is also often called the UI thread.
In this case, it is not possible for the newly-started thread to dynamically change the property values of the interface components. So there is the handler message processing mechanism.
Handler class:
There are two main functions:
1. Sending messages in a newly-started thread
2. Get and process messages in the main thread.
Main methods:
void Handlemessage (Message msg): Methods for handling messages
Final Boolean hasmessage (int): Checks whether the message queue contains the value of the What property
Final Boolean hasmessage (int what,object Object): Checks whether the message queue contains the value of the What property and the Object property
Sendemptymessage (int): Send an empty message
Final Boolean sendMessage (Message msg): Send Message now
Final Boolean sendmessagedelayed (Message Msg,long delaymillis): Specifies the number of milliseconds after which a message is sent
Auto-Play Animations:
Mainactivity.java:
Import Java.util.timer;import java.util.timertask;import Android.app.activity;import Android.os.Bundle;import Android.os.handler;import Android.os.message;import Android.view.menu;import Android.view.menuitem;import Android.widget.imageview;public class Mainactivity extends Activity {int images[] = new int[] {r.drawable.yy01, r.drawabl E.yy02,r.drawable.yy03, r.drawable.yy04, r.drawable.yy05, R.drawable.yy06,r.drawable.yy07, R.DRAWABLE.YY08, R.drawable.yy09, R.drawable.yy10,r.drawable.yy11, R.drawable.yy12, r.drawable.yy13,};int currentImage = 0;private ImageView ImageView; @Overrideprotected void OnCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate) ; Setcontentview (r.layout.activity_main); ImageView = (ImageView) Findviewbyid (r.id.imageshow); final Handler Mhandler = new Handler () {@Overridepublic void Handlemessage (Message msg) {//TODO auto-generated method Stubsuper.handlemessage (M SG);//If the message is issued by this program if (msg.what = = 0x1233) {//Modify the picture to be displayed Imageview.setimageresource (images[currentimage++% images.length]);}}};/ /define a timer to have the timer perform the specified task periodically//the Timer object can dispatch the TimerTask object through periodic execution of the specified task, and the essence of the TimerTask object is to start a new thread, the newly timer (). Schedule ( New TimerTask () {@Overridepublic void Run () {//TODO auto-generated method stub//send an empty message mhandler.sendemptymessage (0x1233) ;}}, 0, 2000);}}
There is only one imageview in the layout file.
Android------handler message passing mechanism