Android Countdown Artifact of CountDownTimer

  • 2021-11-14 07:12:24
  • OfStack

Android countdown artifact-CountDownTimer, for your reference, the specific contents are as follows

What is CountDownTimer? In fact, in fact, the

CountDownTimer is a countdown tool packaged by Google under Andorid. os package. We, usually in the development process like a number of verification code, countdown functions, if their own encapsulation of a countdown tool will be slightly troublesome. Google is a very convenient tool to use.

Source code


package android.os;

public abstract class CountDownTimer {
 public CountDownTimer(long millisInFuture, long countDownInterval) {
 throw new RuntimeException("Stub!");
 }

 public final synchronized void cancel() {
 throw new RuntimeException("Stub!");
 }

 public final synchronized CountDownTimer start() {
 throw new RuntimeException("Stub!");
 }

 public abstract void onTick(long var1);

 public abstract void onFinish();
}

Constructor:

Two parameters, the first is the total countdown time and the second is the countdown interval. For example, if you jump once in one second, the parameter will be 1000, and the unit of both parameters is milliseconds.

start ():

Call this method to start the timer.

cancel ():

Call this method to release the timer.

Important! 1 Be sure to use the cancel () timer in callbacks such as onDestory, or a null pointer error will occur because the page is reclaimed and the timer is still running!

Callback method:

onTick ():

Each time interval will be called back once. For example, if the interval of 1000ms is set, this method will be called back once every 1000ms.

onFinish():

Callback after the entire timer ends.

1 pits in use

The problem of inaccurate timing

Although this tool does deal with delays, for a number of other reasons, it is very likely that CountDownTimer will not start timing from the total time you set. For example, if you set millsInFuture to 30000 (30s), CountDownTimer actually starts timing from 29xxx, which will cause UI of some Text to display one second faster. The solution is to pass in a number 1 larger than 30000 at construction time, such as 30300.

Memory leak/null pointer problem

In fact, CDT has a package for Handler, so it is necessary to call cnacel () method of Timer when recycling, otherwise it is easy to have null pointer error.


Related articles: