I believe that many of you will use the countdown operation in the project. The countdown function is very frequently used in our business development. For example, if the user’s operation posture is wrong, we will give a prompt, which is a dialog box with a countdown.
Indeed, we can directly use toast, but this is often not what the product wants, because they feel that there is no interaction and the experience is poor. For example, we can also remind users of the countdown box when we complete a task. The countdown operation has a wide range of requirements for Android development, so I won’t go into details here.
In Android, there are many kinds of countdown implementation, you can use the most commonly used method of Handler+Thread implementation, can also be implemented through the Timer method, of course, you can also use this chapter to introduce Google official recommended CountDownTimer to achieve, of course, there are many ways to solve the problem. It’s not just these methods, but these are just some of the many ways that the Handler implements the countdown, and there are many variations, such as the message-based method, the Runnable method, and so on. In short, it all comes down to doing time-consuming operations in the child thread, and updating in the UI thread.
Now let’s introduce each of these different ways:
1) Use Handler+Thread/Runnable
First on the code again:
So as you can see, we’re going to create a Handler in our main thread, and we’re going to update our UI using the Handler mechanism, so UI update is the countdown that we’re going to show you, and I’m just going to show you the logic and implementation of the countdown, and you can use it in a TextView, You can also pop up a dialog box as a reminder, here we ignore the carrier of the countdown, you care about the logic of the countdown and transplant it to your own case according to the situation.
We are in the main thread (that is, the UI thread) to create a handler, here we use handler message mechanism, can not understand to see this article www.jianshu.com/p/138363a97…
To control in your handler updates, here refers to the number of seconds, and then the decrement downward cycle, and then through the handler will be sent a message, is through the handler sendEmptyMessageDelayed (0, 1), the first parameter is the delay time, the second parameter is the time interval, When the second is less than zero, the countdown to complete at this time, we will have to cancel to send, through removeCallbacksAndMessages () method, memory leak or handler will cause the program to crash, so finished??? It seems like we’re pretty sure of something. Yeah, we’re processing messages in MessageQueue in the beginning in handler, but where did the first message come from? I don’t think I found it. That’s right, I’ve omitted the lead of our first message.
You can call new Thread(new MyThread()).start () to start the countdown. This is the handler that implements the countdown. Those of you familiar with the Handler mechanism should have no problem with this.
2) Directly use Handler mode
The difference between this approach and the previous one is that the handler is created in onCreate() (initView() in onCreate()). When an activity is created, it calls a lifecycle function to complete its life. In onCreate, the Hanlder is created. Then we create the Message through obtainMessage(), and finally send the Message through sendEmptyMessage(), where Message is just created but empty because we don’t need to carry the Message to the UI thread, So we send a new message to MessageQueue, and then the handler goes into a loop, and the thread Looper starts polling and keeps pulling messages out of the MwssageQueue and distributing them to the handler until all the messages are processed and the handler doesn’t send any more messages, The business level implementation of this process is also the logic in handleMessage(). We can set a timer (mLimitTime) when the handler is initialized. In onCreate (), we send an empty message to the handler to loop. Judge the duration mLimitTime every time you process a message, update the current duration on the corresponding control, don’t forget mLimitTime–, loop until we are equal to 0, else process, here I call back the dialog dismiss() method, In this method we need removeCallbacksAndMessages () cancel our handler mechanism, to prevent a memory leak, with mode 1 not much difference on the logic, mainly familiar with handler mechanism.
But this way I use Kotlin implementation, if the first contact with Kotlin may not look very comfortable, but for Java people should not be too much of a problem, you can also follow this logic in Java implementation of the countdown.
3) Timer countdown mode
Using a Timer and a TimerTask is also very simple and very fixed, so you can call it directly from the template. First we create a Timer and a TimerTask when the class is initialized. This is very similar to the Handler usage. Inside the task we are making state in the UI thread by runOnUiThread() and the loop logic is similar. When we count down long recLen equals 0 we cancel the Timer with cancel(). Handler’s Intent is similar to that of removecallbackandMessage(). OnFinishCreateView () starts the task with schedule(task,0,1000), which is the same as sendEmptyMessage() using the handler mechanism. The onFinishCreateView() method is also a business requirement method. You can put task.schedule() in the onCreate() or onResume() method, start the task and loop until the condition breaks out of the loop, updating the control each time.
Is it very simple !!!!
4) CountDownTimer Google Wall crack
Let’s take a look at how Google encapsulates the countdown
Construction method:
Zipinfuture: [s] zipinfuture,
CountDownInterval: indicates the countDownInterval
First to millisInFuture reasonable judgment, the countdown finish off directly, unreasonable mStopTimeInFuture = SystemClock. ElapsedRealtime () + mMillisInFuture countdown terminate the completion time, What does that mean? Get the current system time, and then add our countdown time, which is equivalent to the code to mark the termination time mStopTimeInFuture, and then see if there is a familiar code — sendMessage(), It turned out that CountDownTime has already packed handler mechanism inside for us. No wonder Google recommended a way to avoid the application crash caused by memory leakage caused by incorrect gesture during the development process. Then continue to look at the source code
Here is the message processing logic, first of all, Google to the application robustness and consistency of the current countdown task shackles, you see this code: final longmillisLeft=mStopTimeInFuture-SystemClock.elapsedRealtime(); When a message is removed from the queue, it calculates the millisederd time and calculates the millisederd time. ^ mdash? [s], what is the onTick(millisLeft) callback method? We call this callback method to update our control state and so on.
Yes, we send messages in a loop, and that’s all we need to do with handler. Google encapsulates our logic until the millisLeft equals 0 callback to onFinish()
Above we will be the source of a simple look, below we continue to paste code, see how to use:
The onFinish () and onTick () methods give you the freedom to execute the logic as required,
It’s easier to just create a new CountDownTimer () and start the timer, and then do the UI update inside the callback instead of defining a TimeCount.
Handler handler handler handler handler handler handler handler handler handler handler handler handler handler handler handler handler handler