The use of Android handler, before speaking handler, we first mention a small problem, is how to let the program 5 seconds update title.
First of all, let's take a look at the people who are used to Java programming and how to write the program before they know handler usage, as shown in the following code:
Copy Code 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 a variable for the Settitle method, which I set to the int type for convenience
private int title = 0;
public void OnCreate (Bundle savedinstancestate) {
Super.oncreate (savedinstancestate);
Setcontentview (R.layout.main);
Timer 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 the program and do not achieve the desired effect, Android introduces the special class of handler, which can be said to be a bridge between runnable and activity.
, so we just send the message in the Run method, and in handler, we perform different tasks through different messages.
So our revised code is as follows:
Copy Code code 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 a variable for the Settitle method, which I set to the int type for convenience
private int title = 0;
Private Handler Mhandler = new Handler () {
public void Handlemessage (msg) {
Switch (msg.what) {
Case 1:
Updatetitle ();
Break
}
};
};
public void OnCreate (Bundle savedinstancestate) {
Super.oncreate (savedinstancestate);
Setcontentview (R.layout.main);
Timer timer = new timer ();
Timer.scheduleatfixedrate (New MyTask (), 1, 5000);
}
Private class MyTask extends timertask{
@Override
public void Run () {
Message message = new Message ();
Message.what = 1;
Mhandler.sendmessage (message);
}
}
public void Updatetitle () {
Settitle ("Welcome to Mr Wei ' s blog" + title);
Title + +;
}
}
Let's take a look at the effect chart: