Android basic timer and delay usage, summed up the more concise mode, convenient and easy to call directly in the program.
First, the timing cycle
1. handler.postDelayed+Runnable
- Start by creating a Handler object
Handler handler=new Handler();
Copy the code
- Then create a Runnable object
Runnable runnable=new Runnable(){
@Override
public void run(a) {
// TODO Auto-generated method stub
// Call the Runnable object again to implement the timer operation every two seconds
handler.postDelayed(this.2000);
}};
Copy the code
- Called in the main thread, using the PostDelayed method, and calling the Runnable object two seconds later
handler.postDelayed(runnable, 2000);
Copy the code
- ★ Turn off this timer, you can operate like this
handler.removeCallbacks(runnable);
Copy the code
2. handler+timer+timeTask
- Start by creating a Handler object
Handler handler = new Handler() {
@Override
public void handleMessage(Message msg) {
if (msg.what == 1) {//do something
}
super.handleMessage(msg); }};Copy the code
- Then create a Timer object
Timer timer = new Timer();
TimerTask timerTask = new TimerTask() {
@Override
public void run(a) {
Message message = new Message();
message.what = 1; handler.sendMessage(message); }};Copy the code
- Called in the main thread, using the schedule method
// Delay for 1s, execute the run method every 500 milliseconds
timer.schedule(timerTask,1000.500);
Copy the code
3. Thread+handler
- Start by creating a Handler object
Handler handler = new Handler() {
@Override
public void handleMessage(Message msg) {
if (msg.what == 1) {//do something
}
super.handleMessage(msg); }};Copy the code
- Then create a Timer object
class ScheduleThread extends Thread {// The Runnable interface is also available
@Override
public void run(a) {
while (true) {try {
// The command is executed every 1s
Thread.sleep(1000);
Message msg = new Message();
msg.what = 1;
handler.sendMessage(msg);
} catch(InterruptedException e) { e.printStackTrace(); }}}}Copy the code
- Called in the main thread
new Thread(new ScheduleThread ()).start();
Copy the code
Second, the time delay
1. Handler’s postDelayed method:
new Handler().postDelayed(new Runnable() {
@Override
public void run(a) {
//do something}},1000); // The execution delay is 1s
Copy the code
2. Timer + TimerTask
timer = new Timer();
timer.schedule(new TimerTask() {
@Override
public void run(a) {
//do something}},1000);// The execution delay is 1s
Copy the code
3. Thread method:
new Thread(new Runnable() {
@Override
public void run(a) {
try {
Thread.sleep(1000);/ / delay 1 s
//do something
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}).start();
new Thread(new MyThread()).start();
Copy the code