Several ways to implement Android timer and removecallbacks failure issues

Source: Internet
Author: User

There are many ways to implement timers, here I simply introduce several ways

(1) How to use Handler + runnable

Newnew  Runnable () {        @Override    publicvoid  run () {         // What you're going to        do . // ......         System.out.println (Thread.CurrentThread (). GetName ());         );    }};

Then call Handler.post (runnable), you can start the timer, here is every 1s print thread name, from the printing we can know that he does not have another thread, but run in the UI thread, when you want to cancel the timer, You only need to call Handler.removecallbacks (runnable).

There is a problem in the above, sometimes you will find that removecallbacks sometimes fail, can not be removed from the message queue, see the following demo

Two buttons, one adds the runnable to the message queue, and one removes the runnable from the message queue. The runnable prints logs every 1 seconds.

 Packagecom.example.demoactivity;Importandroid.app.Activity;ImportAndroid.os.Bundle;ImportAndroid.os.Handler;ImportAndroid.view.View;ImportAndroid.view.View.OnClickListener;ImportAndroid.widget.Button; Public classTimeractivityextendsactivity{Handler Handler=NewHandler (); Runnable Runnable=NewRunnable () {@Override Public voidrun () {System.out.println ("Update ..."); Handler.postdelayed (runnable,1000);    }    }; @Overrideprotected voidonCreate (Bundle savedinstancestate) {Super. OnCreate (savedinstancestate);                Setcontentview (R.layout.timer); Button Mbuttonstart=(Button) Findviewbyid (R.id.button1); Button Mbuttonstop=(Button) Findviewbyid (R.id.button2); Mbuttonstart.setonclicklistener (NewOnclicklistener () {@Override Public voidOnClick (View v) {handler.post (runnable);                }        }); Mbuttonstop.setonclicklistener (NewOnclicklistener () {@Override Public voidOnClick (View v) {handler.removecallbacks (runnable);    }        }); }    }

Results:
(1) start–> output –> stop–> stop output
(2) start–> output –> background–> front–> stop-> Continue output

Removecallbacks cannot remove Updatethread from the message queue when the activity is running in the background and then into the foreground.
What is this for?
The thread is always running while the activity is being moved from the foreground to the background, but the runnable runnable is redefined when the activity is transferred to the foreground, that is, the runnable removed from the message queue at this time with the original message The runnable in a queue are not the same object. If runnable is defined as static, then removecallbacks does not fail, and for static variables there is only one copy in memory (memory saving), and the JVM allocates only one memory at a time, and completes the memory allocation of static variables in the process of loading the class. We can fix this problem by making the following changes.

Static New Handler (); Static New Runnable () {        @Override    publicvoid  run () {        System.out.println (" Update ... ");         );    }};

(2) How to use the timer

New Timer (); Timer.schedule (new  timertask () {                        @Override    publicvoid  Run () {        System.out.println ("Update ....");     0, 1000);

Each second above the print statement, the Run method is run on the child thread, not directly inside the UI to update the operation, it is necessary to note that the cancellation of the call Timer.cancel () will be able to remove the task

(3) The Sleep (long) method using handle and thread

1. Define a handler class to handle the received message

New Handler () {        publicvoid  handlemessage (Message msg) {            super  . Handlemessage (msg);            SYSTEM.OUT.PRINTLN ("Update ...");}    }

2. Create a new thread class that implements the Runnable interface, using a Boolean to control thread start and end Boolean islive = True as follows:

 Public classMyThreadImplementsRunnable {@Override Public voidrun () { while(islive) {Try{Thread.Sleep (1000);//thread paused for 1 seconds, per millisecondMessage message =NewMessage (); Message.what= 1; Handler.sendmessage (message);//Send Message}Catch(interruptedexception e) {e.printstacktrace (); }            }        }    }

3. Add the following statement where you want to start the thread

New Thread (new MyThread ()). Start ();

4. If you cancel, set the Islive to False.

Today the main introduction of these three methods, write a bad place to hope you point out, thank you! Transferred from: http://blog.csdn.net/xiaanming/article/details/9011193

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.