Android mobile butler software usually pops up such pop-up boxes when managing the application rights of mobile phones. Such a button appears on many occasions, the system will give a certain time such as 30s prompt the user to select the operation "prohibited" or "allowed", and set the countdown, and after the countdown to zero the system will select the default behavior for the user to perform.This design is very intelligent and automated when no one is using the phone.Here are the effects of using a handler and a Runnable to implement such a button:
Android implement countdown button effect
In an extremely reprinted article entitled "Several Ways for Android to Use Threads to Update UI", we mentioned the use of Runnable and Handler.PostDelayed (Runnable, Time) to update the interface in Android.The following is a button that implements countdown effects using Runnable and Handler.PostDelayed(Runnable,Time). Assume that the action of clicking the countdown button is the running function function(), and the button variable name is forbiddenBtn. The following is the implemented code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
Handler timerHandler = new Handler(); Int autoRun = 30; / / set the countdown time 30s Second=autoRun; Runnable timerRunnable = new Runnable() { @Override Public void run() { If (second == 0) { forbiddenBtn.setText("Forbidden"); timerHandler.removeCallbacks(timerRunnable);//Clear timing Second =autoRun; Function();// performs the default operation } Else { forbiddenBtn.setText("Forbidden (" + second-- + "seconds...)"); timerHandler.postDelayed(this, 1000); } } }; |
principle
The above code implementation principle is to use the timeHander.postDelayed(context, int) function to periodically call a Runnable, here is a time delay 1000ms execute the timerRunnable.The code that calls the countdown above is:
1 |
timerHandler.postDelayed(timerRunnable, 0); |
Immediate execution of timerRunnable; When the timerRunnable is executed, since the second is initialized to 30s, the if statement executes the else part, second is displayed after the button is displayed and decremented by 1 and then through timerHandler.postDelayed(this, 1000); executed again after 1 second. timerRunnable, when second=29... and so on, when second=0, it will execute function() to perform default operation after countdown to zero.
This article has been printed on copyright and is protected by copyright laws. It must not be reproduced without permission.If you need to reprint, please contact the author or visit the copyright to obtain the authorization. If you feel that this article is useful to you, you can click the "Sponsoring Author" below to call the author!
Reprinted Note Source: Baiyuan's Blog>>https://wangbaiyuan.cn/en/android-implementation-effect-of-countdown-button-2.html
No Comment