"Turn" Android timer implementation of several ways and removecallbacks failure problem--good

Source: Internet
Author: User

Original URL: http://blog.csdn.net/xiaanming/article/details/9011193

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

(1) How to use Handler + runnable

[Java]View Plaincopy
  1. Handler Handler = new Handler ();
  2. Runnable Runnable = new Runnable () {
  3. @Override
  4. public Void Run () {
  5. //What you have to do
  6. //......  
  7. System.out.println (Thread.CurrentThread (). GetName ());
  8. Handler.postdelayed (runnable, 1000);
  9. }
  10. };

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 Plaincopy
  1. <span style="Font-family:courier New;"  > Packagecom.example.demoactivity;
  2. Import android.app.Activity;
  3. Import Android.os.Bundle;
  4. Import Android.os.Handler;
  5. Import Android.view.View;
  6. Import Android.view.View.OnClickListener;
  7. Import Android.widget.Button;
  8. Public class Timeractivity extends activity{
  9. Handler Handler = new Handler ();
  10. Runnable Runnable = new Runnable () {
  11. @Override
  12. public Void Run () {
  13. SYSTEM.OUT.PRINTLN ("Update ...");
  14. Handler.postdelayed (runnable, 1000);
  15. }
  16. };
  17. @Override
  18. protected void OnCreate (Bundle savedinstancestate) {
  19. super.oncreate (savedinstancestate);
  20. Setcontentview (R.layout.timer);
  21. Button Mbuttonstart = (button) Findviewbyid (R.id.button1);
  22. Button Mbuttonstop = (button) Findviewbyid (R.id.button2);
  23. Mbuttonstart.setonclicklistener (new Onclicklistener () {
  24. @Override
  25. public void OnClick (View v) {
  26. Handler.post (runnable);
  27. }
  28. });
  29. Mbuttonstop.setonclicklistener (new Onclicklistener () {
  30. @Override
  31. public void OnClick (View v) {
  32. Handler.removecallbacks (runnable);
  33. }
  34. });
  35. }
  36. }</span><span style="Font-family:georgia, ' Times New Roman ', Times, San-serif;" >
  37. </span>

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.

"Threads are always running while the activity is being moved from the foreground to the background, but when the activity goes to the foreground, the runnable runnable" should not be redefined runnable runnable.

[Java]View Plaincopy
  1. static Handler Handler = new Handler ();
  2. static Runnable Runnable = new Runnable () {
  3. @Override
  4. public Void Run () {
  5. SYSTEM.OUT.PRINTLN ("Update ...");
  6. Handler.postdelayed (runnable, 1000);
  7. }
  8. };

(2) How to use the timer

[Java]View Plaincopy
    1. timer timer = new timer () ;   
    2. timer.schedule (new timertask ()  {  
    3.                        
    4.      @Override   
    5.     public void run ( )  {  
    6.         system.out.println (
    7.     }   
    8. }, 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

[Java]View Plaincopy
    1. Handler Handler = new Handler () {
    2. public void Handlemessage (Message msg) {
    3. super.handlemessage (msg);
    4. SYSTEM.OUT.PRINTLN ("Update ...");
    5. }
    6. }

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:

[Java]View Plaincopy
  1. Public class MyThread implements Runnable {
  2. @Override
  3. public Void Run () {
  4. While (islive) {
  5. try {
  6. Thread.Sleep (+); Thread paused for 1 seconds, per millisecond
  7. Message message = new Message ();
  8. Message.what = 1;
  9. Handler.sendmessage (message); //Send Message
  10. } catch (Interruptedexception e) {
  11. E.printstacktrace ();
  12. }
  13. }
  14. }
  15. }

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

[Java]View Plaincopy
    1. 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!

"Turn" Android timer implementation of several ways and removecallbacks failure problem--good

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.