Android中使用Java语言编写倒计时计时器比较常见,同时还需使用后台服务来实现倒计时的持续性。可以按照以下步骤进行实现:
public class CountDownService extends Service {
@Override
public IBinder onBind(Intent intent) {
return null;
}
}
public class CountDownService extends Service { private static final long COUNTDOWN_TIME = 60000; //倒计时时间 60秒毫秒 private CountDownTimer countDownTimer; //倒计时 private long timeLeft = COUNTDOWN_TIME;
@Override
public IBinder onBind(Intent intent) {
return null;
}
//执行倒计时的方法
private void startCountDown() {
countDownTimer = new CountDownTimer(timeLeft, 1000) {
@Override
public void onTick(long millisUntilFinished) {
timeLeft = millisUntilFinished;
}
@Override
public void onFinish() {
//定时器结束,再次启动
startCountDown();
}
};
countDownTimer.start(); //开始计时
}
}
public class CountDownService extends Service {
private static final long COUNTDOWN_TIME = 60000; //倒计时时间 60秒毫秒
private CountDownTimer countDownTimer; //倒计时
private long timeLeft = COUNTDOWN_TIME;
@Override
public void onCreate() {
super.onCreate();
startCountDown(); //启动倒计时计时器
}
@Override
public int onStartCommand