Hello, everybody. We are talking about the use of Android handler in this section, before we talk about handler, let us ask a small question, is how to let the program 5 seconds to update the title.
First we look at the people who are accustomed to Java programming, how to write a program before they know how to use handler, the code is as follows:
[Java] View plain copy 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++; } } }
Android introduces handler, a special class that can be said to be a bridge between runnable and activity interactions, so we just send a message in the Run method, and in handler, we perform different tasks with different messages.
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++; } }
Let's look at the following:
Android Master Advanced Tutorial (ix)----the use of Android handler!!!