Several ways to implement Android timer and removecallbacks failure issues

Source: Internet
Author: User
Tags message queue

There are many ways to implement timers, here I briefly introduce several ways (1) Use Handler +runnable the way [Java] View plain copy on code to view the snippet derivation to my Code slice Handler Handler=NewHandler (); Runnable Runnable=NewRunnable () {@Override Public voidrun () {//What you're going to do .//......  System. out. println (Thread.CurrentThread (). GetName ()); Handler.postdelayed (runnable, +);  }      }; 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

Figure: 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. [Java] View plain copy on code to see a snippet derived from my Code slice<span style="font-family:courier New;">Package com.example.demoactivity;      Import android.app.Activity;      Import Android.os.Bundle;      Import Android.os.Handler;      Import Android.view.View;      Import Android.view.View.OnClickListener;            Import Android.widget.Button;  Public classtimeractivity extends activity{Handler Handler=NewHandler (); Runnable Runnable=NewRunnable () {@Override Public voidrun () {System. out. println ("update ..."); Handler.postdelayed (runnable, +);                }          }; @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);          }              }); }                }</span><span style="Font-family:georgia, ' Times New Roman ', Times, San-serif;"> </span>Results: (1) start–> output –> stop–>Stop Output (2) start–> output –> background–> front–> stop->continue output when the activity is running in the background and then into the foreground, removecallbacks cannot remove the Updatethread from the message queue. 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 .
    StaticHandler Handler =NewHandler (); StaticRunnable Runnable =NewRunnable () {@Override Public voidrun () {System. out. println ("update ..."); Handler.postdelayed (runnable, +);  }      }; (2the way the timer is used [Java] view plain copy on code to view the chip derivation to my Code slice timer timer=NewTimer (); Timer.schedule (NewTimerTask () {@Override Public voidrun () {System. out. println ("update ...."); }      }, 0, +); 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 important to note that the cancellation of the call Timer.cancel () will be able to remove the task (3) using handle with the thread of sleep (Long) Method1. Define a Handler class to handle the accepted Message[java] view plain copy on code to view the snippet derivation to my Code slice Handler Handler=NewHandler () { Public voidhandlemessage (Message msg) {super.handlemessage (msg); System. out. println ("update ..."); }          }  2Create a new thread class that implements the Runnable interface, using a Boolean to control thread start and end Boolean islive =true is as follows: [Java] View plain copy on code to see a snippet derived from my Code slice Public classMyThread implements Runnable {@Override Public voidrun () { while(islive) {Try{Thread.Sleep ( +);//thread paused for 1 seconds, per millisecondMessage message =NewMessage (); Message.what=1; Handler.sendmessage (message);//Send Message}Catch(interruptedexception e) {e.printstacktrace (); }                  }              }          }  3Add the following statement where you need to start the thread [Java] View plain copy on code to view the snippet derivation to my Code sliceNewThread (NewMyThread ()). Start (); 4. If you cancel, set Islive to false. Today mainly introduce these three methods, write bad place hope everybody point out, thank you! 

Several ways to implement Android timer and removecallbacks failure issues

Related Article

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.