ConutDownTimer
需求描述:
引导页右上角进行倒计时,结束后跳转
演示:
代码演示
activity_launcher.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@drawable/kun"
tools:context=".MainActivity">
<TextView
android:id="@+id/tv_countDownTimer"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentEnd="true"
android:layout_marginTop="20dp"
android:layout_marginEnd="20dp"
android:text="跳过"
android:textColor="@color/black"
android:textSize="20sp" />
</RelativeLayout>
LauncherActivity
public class LauncherActivity extends AppCompatActivity {
private ActivityLauncherBinding binding;
private CountDownTimer timer;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
binding = ActivityLauncherBinding.inflate(getLayoutInflater());
setContentView(binding.getRoot());
initCountDownTimer();
}
private void initCountDownTimer() {
/**
* 参数 - millisInFuture:设置倒计时的总时间(毫秒)
* 参数 - countDownInterval:设置每次减去的时间(毫秒)
*/
timer = new CountDownTimer(1000 * 5, 1000) {
@Override
public void onTick(long millisUntilFinished) {
// 判断当前Activity是否isFinishing(),
// 避免在finish,所有对象都为null的状态下执行CountDown造成内存泄漏
if (!isFinishing()) {
int time = (int) millisUntilFinished;
binding.tvCountDownTimer.setText(time / 1000 + "跳过");
binding.tvCountDownTimer.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
checkToJump();
}
});
}
}
@Override
public void onFinish() {
checkToJump();
}
}.start();
}
private void checkToJump() {
startActivity(new Intent(getApplicationContext(), MainActivity.class));
//回收内存
destroyTimer();
finish();
}
private void destroyTimer() {
// 避免内存泄露
if (timer != null) {
timer.cancel();
timer = null;
}
}
}
ConutDownTimer方法描述
1、CountDownTimer 直接 new 出来使用,其构造函数
public CountDownTimer(long millisInFuture, long countDownInterval) {
mMillisInFuture = millisInFuture;
mCountdownInterval = countDownInterval;
}
参数 - millisInFuture:设置倒计时的总时间(毫秒)
参数 - countDownInterval:设置每次减去的时间(毫秒)
2、方法
public final void cancel ()
public abstract void onFinish ()
public abstract void onTick (long millisUntilFinished)
public final CountDownTimer start ()
- cancel() 取消当前任务
- onFinish() 当前任务完成的时候调用
- onTick(long millisUntilFinished) 当前任务每完成一次倒计时间隔时间时回调
- start() 开始当前的任务