There are many ways to implement timers, and here I'm simply introducing several ways
(1) using the handler + Runnable method
Copy Code code as follows:
Handler Handler = new Handler ();
Runnable Runnable = new Runnable () {
@Override
public void Run () {
What you're going to do.
//......
System.out.println (Thread.CurrentThread (). GetName ());
Handler.postdelayed (runnable, 1000);
}
};
Then call Handler.post (runnable), you can start the timer, here is every 1s print thread name, from the print we can know that he does not have another thread, but run in the UI thread, when you want to cancel the timer, Only need to call Handler.removecallbacks (runnable) on it.
There is a problem in the above, sometimes you will find that removecallbacks sometimes ineffective, can not be removed from the message queue, see the following demo
Figure: Two buttons, one to add runnable to the message queue, and one to remove the runnable from the message queue. The runnable prints a log every 1 seconds.
Copy Code code as follows:
<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 class Timeractivity extends activity{
Handler Handler = new Handler ();
Runnable Runnable = new Runnable () {
@Override
public void Run () {
SYSTEM.OUT.PRINTLN ("Update ...");
Handler.postdelayed (runnable, 1000);
}
};
@Override
protected void OnCreate (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 (New Onclicklistener () {
@Override
public void OnClick (View v) {
Handler.post (runnable);
}
});
Mbuttonstop.setonclicklistener (New Onclicklistener () {
@Override
public void OnClick (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
Removecallbacks cannot remove Updatethread from the message queue when the activity enters the background and then runs to the foreground.
What is this for?
Threads are always running while the activity is in the foreground, but the runnable runnable is redefined when the activity is transferred to the foreground, i.e. the runnable removed from the message queue and the original message The runnable in the queue is not the same object. If the runnable is defined as static, then the removecallbacks will not fail, for static variables in memory only one copy (save memory), the JVM only for static allocation of memory, in the process of loading the class to complete the memory allocation of static variables, We can solve this problem by making the following changes
Copy Code code as follows:
static Handler Handler = new Handler ();
static Runnable Runnable = new Runnable () {
@Override
public void Run () {
SYSTEM.OUT.PRINTLN ("Update ...");
Handler.postdelayed (runnable, 1000);
}
};
(2) How to use timer
Copy Code code as follows:
Timer timer = new timer ();
Timer.schedule (New TimerTask () {
@Override
public void Run () {
SYSTEM.OUT.PRINTLN ("Update ...");
}
}, 0, 1000);
Each second of the above print statement, the Run method is run in the child thread, not directly in the inside update UI operations, here need to note that the cancellation call Timer.cancel () can remove the task
(3) A sleep (long) method using handle and thread
1. Define a handler class for handling the received message
Copy Code code as follows:
Handler Handler = new Handler () {
public void Handlemessage (msg) {
Super.handlemessage (msg);
SYSTEM.OUT.PRINTLN ("Update ...");
}
}
2. Create a new thread class that implements the Runnable interface, using a Boolean to control the start and end of the thread Boolean islive = True as follows:
Copy Code code as follows:
public class Mythread implements Runnable {
@Override
public void Run () {
while (islive) {
try {
Thread.Sleep (1000),//thread paused for 1 seconds, per millisecond
Message message = new Message ();
Message.what = 1;
Handler.sendmessage (message);//Send messages
catch (Interruptedexception e) {
E.printstacktrace ();
}
}
}
}
3. Add the following statement where you want to start the thread
Copy Code code as follows:
New Thread (New Mythread ()). Start ();
4. The cancellation of the islive set to false on the line
Today, the main introduction of these three methods, write the bad place I hope everyone points out, thank you!