Android Timer, update data

Source: Internet
Author: User

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;
}

---------------------------------------------------------------------------------------------------

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.