倒计时的实现其实有很多方法,概括来说有两种,一种是调用线程,一种是调用android自带的方法。经过对比我发现,调用线程的倒计时如果熄屏过后不久就会被销毁,而且就算调用函数一直获得cpu,最终也会被销毁,(这应该是android自己的保护机制,我没有深究),但是调用Android自带的方法就不会。事件准确性对比,调用线程的时间精准度比调用系统方法高一点,但是都存在一定的误差。综合以上的考虑,我还是最终选择了android自带的方法。
这个方法就是CountDownTimera(),它的实现比较简单,直接上代码:
timer = new CountDownTimer(TotalTime*1000, 1000) { //时间倒计时
@SuppressLint("SetTextI18n")
@Override
public void onTick(long totalTime) {
long hour=totalTime/3600/1000;
min=(totalTime-3600*hour*1000)/60/1000;
long sec=totalTime/1000%60;
textView.setText(hour+" : "+min+" : "+sec);
}
@Override
public void onFinish() { //结束后执行
textView.setText("");
}
}.start();
这样,这个倒计时就算是完成了。
可是仅仅只是这样未免显得单调,怎样做的炫酷一点?对了,我们前面提到过动画效果的实现 点击这里
这里同样也可以用法。然后可以在倒计时之前设置一个gif动画,我用的是三秒的倒计时,结束后就开始正式的倒计时。最后当倒计时结束我们应该有一个触发机制,我实现的是手机的震动,提醒用户倒计时结束了。
所以总的代码修改如下:
timer = new CountDownTimer(5*1000, 1000) { //炫酷倒计时(准备)
@SuppressLint("SetTextI18n")
@Override
public void onTick(long totalTime) {
}
@Override
public void onFinish() {
GifImageView gifImageView=(GifImageView)findViewById(R.id.gif);
gifImageView.setBackgroundResource(R.drawable.gif_7);
timer = new CountDownTimer(TotalTime*1000, 1000) { //时间倒计时
@SuppressLint("SetTextI18n")
@Override
public void onTick(long totalTime) {
long hour=totalTime/3600/1000;
min=(totalTime-3600*hour*1000)/60/1000;
long sec=totalTime/1000%60;
textView.setText(hour+" : "+min+" : "+sec);
Animation animation= AnimationUtils.loadAnimation(ForceActivity.this,R.anim.my_animation); //特效2
textView.startAnimation(animation);
}
@Override
public void onFinish() {
button.setEnabled(true);
button3.setEnabled(true);
textView.setText("");
Vibrator vibrator = (Vibrator)ForceActivity.this.getSystemService(ForceActivity.this.VIBRATOR_SERVICE); //结束后震动提示结束
vibrator.vibrate(3000); //震动时间为三秒
}
}.start();
}
}.start();
}
关于gif动画的潜入,需要导入一个gif包,这个包android本身提供了,只需要在build-gradle中添加 implementation 'pl.droidsonroids.gif:android-gif-drawable:1.1.+'如下:
dependencies {
implementation fileTree(include: ['*.jar'], dir: 'libs')
implementation 'com.android.support:recyclerview-v7:26.1.0'
implementation 'com.android.support:appcompat-v7:26.1.0'
implementation 'pl.droidsonroids.gif:android-gif-drawable:1.1.+'
implementation 'com.android.support.constraint:constraint-layout:1.1.2'
testImplementation 'junit:junit:4.12'
androidTestImplementation 'com.android.support.test:runner:1.0.2'
androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.2'
}
好了,关于倒计时就说到这里了,更多炫酷的倒计时需要绘制,这里就暂时不深究了