Make a note of the timer that is commonly used in Android to update the UI data regularly.
1.Handler + runnable Timer
Private Handler Mhandler;
Private Runnable mrunnable;
Mhandler = new Handler ();
mrunnable = new Runnable () {
Public void run () {
Ways to update data
Update ();
}
};
Timed start thread (thread executed, milliseconds)
Mhandler. postdelayed (mrunnable, 4000);
To remove a thread from a handler
Mhandler. Removecallbacks (mrunnable);
==================================================
2. Timer+timertask Timer
Timertimer = new Timer ();
Timer.schedule (new timertask () {
@Override
Public void run () {
// method of execution
Sendmsg ();
}
}, 4000); Time of execution milliseconds
3.// Sending message messages
void Sendmsg () {
//handler Message message
Message message = new message ();
Message. what = MSG;
Mhandler. SendMessage (message);
}
------Handler receive the message mechanism ------
class MyHandlerextends Handler {
@Override
Public void handlemessage (Message msg) {
// TODO auto-generated Method Stub
Super. Handlemessage (msg);
if (Msg. what =msg) {
Ways to update data
Update ();
}
}
};
4. timers executed at intervals
private timer timer;
Private Handler Mshowhandler = new Handler ();
Start timer
if (timer = = null) {
Timer = new timer ();
Timer.scheduleatfixedrate (New Refreshtask (), 0, 800); Executes every 800 milliseconds
}
Timer
Class Refreshtask extends TimerTask {
@Override
public void Run () {
You can add a judgment here to determine what situation to perform the update
if (i=0) {
Mshowhandler.post (New Runnable () {
@Override
public void Run () {
Update Data methods
Update ();
}
}
// }
});
Stop Timer
if (timer! = null) {
Timer.cancel ();
timer = null;
}
---------------------------------------------------------------------------------------------------