Hello, everybody. We are talking about the use of Android handler in this section, before we talk about handler, let's ask a small question, is how to get the program to update title for 5 seconds. First, let's take a look at the people who are accustomed to Java programming and how to write a program before they know how to use handler, as shown in the code below:
PackageCom.android.tutor; ImportJava.util.Timer; ImportJava.util.TimerTask; Importandroid.app.Activity; ImportAndroid.os.Bundle; Public classHandlerdemoextendsActivity {//The title provides a variable for the Settitle method, which I set as the int type for convenience. Private inttitle = 0; Public voidonCreate (Bundle savedinstancestate) {Super. OnCreate (savedinstancestate); Setcontentview (R.layout.main); Timer Timer=NewTimer (); Timer.scheduleatfixedrate (NewMyTask (), 1, 5000); } Private classMyTaskextendstimertask{@Override Public voidrun () {Settitle ("Welcome to Mr Wei ' s blog" +title); Title++; } } } However, when we execute the program, and do not achieve the desired effect, so Android introduced handler this special class, it can be said that it is runnable and activity interaction Bridge, so we just send a message in the Run method, and in handler To perform different tasks with different message types. So our revised code is as follows:
PackageCom.android.tutor; ImportJava.util.Timer; ImportJava.util.TimerTask; Importandroid.app.Activity; ImportAndroid.os.Bundle; ImportAndroid.os.Handler; ImportAndroid.os.Message; Public classHandlerdemoextendsActivity {//The title provides a variable for the Settitle method, which I set as the int type for convenience. Private inttitle = 0; PrivateHandler Mhandler =NewHandler () { Public voidhandlemessage (Message msg) {Switch(msg.what) { Case1: Updatetitle (); Break; } }; }; Public voidonCreate (Bundle savedinstancestate) {Super. OnCreate (savedinstancestate); Setcontentview (R.layout.main); Timer Timer=NewTimer (); Timer.scheduleatfixedrate (NewMyTask (), 1, 5000); } Private classMyTaskextendstimertask{@Override Public voidrun () {Message message=NewMessage (); Message.what= 1; Mhandler.sendmessage (message); } } Public voidUpdatetitle () {Settitle ("Welcome to Mr Wei ' s blog" +title); Title++; } }
This article originates from http://weizhulin.blog.51cto.com/1556324/323922
Use of Android handler