There are many ways to implement the timer. Here I will briefly introduce several methods
(1) handler + runnable
Handler handler = new handler (); runnable = new runnable () {@ overridepublic void run () {// What You Want To Do //...... system. out. println (thread. currentthread (). getname (); handler. postdelayed (runnable, 1000 );}};
Then call handler. post (runnable); the timer can be started. The thread name is printed every 1 S. From the printing, we can know that it is running in the UI thread instead of opening another thread, 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 becomes invalid and cannot be removed from the message queue. See the demo below.
Figure: two buttons: one is to add runnable to the message queue and the other is to remove runnable from the message queue. The runnable prints logs every 1 second.
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() {@Overridepublic void run() {System.out.println("update...");handler.postDelayed(runnable, 1000);}};@Overrideprotected 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() {@Overridepublic void onClick(View v) {handler.post(runnable);}});mButtonStop.setOnClickListener(new OnClickListener() {@Overridepublic void onClick(View v) {handler.removeCallbacks(runnable);}});}}
Result:
(1) Start-> output-> stop output
(2) Start-> output-> background-> front-> stop-> continue output
When the activity enters the background and then enters the foreground for running, removecallbacks cannot remove updatethread from message queue.
Why?
In the process of switching an activity from the foreground to the background, the thread is always running, but when the activity is transferred to the foreground, the runnable will be redefined; in other words, the runnable removed from the message queue is not the same object as the runnable added to the message queue. If the runnable is defined as static, removecallbacks will not expire. For static variables, there is only one copy in the memory (memory saving), and the JVM will only allocate the static memory once, complete the memory allocation of static variables during the loading process. We can solve the above problem by making the following changes:
static Handler handler = new Handler();static Runnable runnable = new Runnable() {@Overridepublic void run() {System.out.println("update...");handler.postDelayed(runnable, 1000);}};
(2) Timer
Timer timer = new Timer();timer.schedule(new TimerTask() {@Overridepublic void run() {System.out.println("update....");}}, 0, 1000);
The run method runs in the sub-thread and cannot update the UI directly in the preceding statement every second. Note that timer is called if the operation is canceled. cancel () to remove the task.
(3) Use the handle and thread sleep (long) Methods
1. Define a handler class for processing received messages
Handler handler = new Handler() {public void handleMessage(Message msg) {super.handleMessage(msg);System.out.println("update...");}}
2. Create a New Thread class that implements the runnable interface. Use a Boolean to control the start and end of a thread. The Boolean islive = true is as follows:
Public class mythread implements runnable {@ overridepublic void run () {While (islive) {try {thread. sleep (1000); // thread pause for 1 second, in milliseconds message = new message (); message. what = 1; handler. sendmessage (Message); // send message} catch (interruptedexception e) {e. printstacktrace ();}}}}
3. Add the following statement where the thread needs to be started
new Thread(new MyThread()).start();
4. If you cancel, set islive to false.
Today we will mainly introduce these three methods. I hope you can point out what is not well written. Thank you!