Hello everyone, this section describes how to use Android handler. before talking about handler, let's raise a small question: how to make Program Update the title in five seconds. First, let's take a look at the programs that are used to Java programming before we know how to write handler, Code As follows:
Package COM. android. tutor; import Java. util. timer; import Java. util. timertask; import android. app. activity; import android. OS. bundle; public class handlerdemo extends activity {// Title provides variables for the settitle method. For convenience, I have set the int type private int title = 0; Public void oncreate (bundle savedinstancestate) {super. oncreate (savedinstancestate); setcontentview (R. layout. main); timer = new timer (); timer. scheduleatfixedrate (New mytask (), 1, 5000);} private class mytask extends timertask {@ override public void run () {settitle ("welcome to Mr Wei's blog" + title); Title ++ ;}}}
However, when we execute a program, we cannot achieve the expected results. Therefore, Android introduces the special class handler, which can be said to be a bridge between runnable and activity, therefore, we only need to send a message in the run method, and execute different tasks through different messages in handler. The modified code is as follows:
Package COM. android. tutor; import Java. util. timer; import Java. util. timertask; import android. app. activity; import android. OS. bundle; import android. OS. handler; import android. OS. message; public class handlerdemo extends activity {// Title provides variables for the settitle method. For convenience, I have set the int type private int title = 0; private handler mhandler = new handler () {public void handlemessage (Message MSG) {Switch (MSG. what) {Case 1: updatetitle (); break ;};}; public void oncreate (bundle savedinstancestate) {super. oncreate (savedinstancestate); setcontentview (R. layout. main); timer = new timer (); timer. scheduleatfixedrate (New mytask (), 1, 5000);} private class mytask extends timertask {@ override public void run () {message = new message (); message. what = 1; mhandler. sendmessage (Message) ;}} public void updatetitle () {settitle ("welcome to Mr Wei's blog" + title); Title ++ ;}}
This article is from Http://weizhulin.blog.51cto.com/1556324/323922