What is handler?
Handler is a set of mechanisms that Android gives us to update the UI, as well as a set of message handling mechanisms that we can send messages to, or that can be handled by him.
Why do you use handler?
Android in the design, it encapsulates a set of message creation, delivery, processing mechanism, if you do not follow such a mechanism, there is no way to update the UI message, will throw an exception message.
Handler usage (i)
code example:
public class Mainactivity extends Activity {
Private TextView TV;
@Override
protected void OnCreate (Bundle savedinstancestate) {
Super.oncreate (savedinstancestate);
Setcontentview (R.layout.activity_main);
TV = (TextView) Findviewbyid (R.ID.TV1);
New Thread () {
public void Run () {
try {
Thread.Sleep (1000);
Update text information
Tv.settext ("Update Thread");
} catch (Interruptedexception e) {
TODO auto-generated Catch block
E.printstacktrace ();
}
};
}.start ();
}
}
Exception reason: UI can only be updated in the original thread
Using handler to update the UI, you can perform a successful
public class Mainactivity extends Activity {
Private TextView TV;
Private Handler Handler = new Handler ();
@Override
protected void OnCreate (Bundle savedinstancestate) {
Super.oncreate (savedinstancestate);
Setcontentview (R.layout.activity_main);
TV = (TextView) Findviewbyid (R.ID.TV1);
New Thread () {
public void Run () {
try {
Thread.Sleep (1000);
Handler.post (New Runnable () {
@Override
public void Run () {
TODO auto-generated Method Stub
Update text information
Tv.settext ("Update Thread");
}
});
} catch (Interruptedexception e) {
TODO auto-generated Catch block
E.printstacktrace ();
}
};
}.start ();
}
}
Example of using Handrle to do a picture poll:
public class Mainactivity extends Activity {
Private TextView TV;
Private ImageView img;
Private Handler Handler = new Handler ();
private int images[] = {R.drawable.one,r.drawable.two,r.drawable.three};
private int index;
Private myrunnable myrunnable= new myrunnable ();
Class Myrunnable implements runnable{
/**
* TODO simply describes the implementation functionality of the overridden method (optional).
* @author Administrator 2014-12-25
* @see Java.lang.runnable#run ()
*/
@Override
public void Run () {
TODO auto-generated Method Stub
Index + +;
index = index%3;
Img.setimageresource (Images[index]);
Handler.postdelayed (myrunnable, 1000);
}
}
@Override
protected void OnCreate (Bundle savedinstancestate) {
Super.oncreate (savedinstancestate);
Setcontentview (R.layout.activity_main);
TV = (TextView) Findviewbyid (R.ID.TV1);
img = (ImageView) Findviewbyid (R.ID.IMAGEVIEW1);
Handler.postdelayed (myrunnable, 1000);
}
}
Android's Handler detailed