如何在我的应用程序中使用CountDownTimer

时间:2017-01-05 05:47:13

标签: android countdowntimer

在我的应用程序中,我想根据系统时间和时间使用CountDownTimer。如果我的时间是14:30:30,系统时间是14:00:00,那么如何在我的申请中设置30分钟计时器?

这是我尝试过的代码,

 try {
      Date1 = dateFormat.parse(curranttime);
    } catch (ParseException e) {
        e.printStackTrace();
    }
    try {
      Date2 = dateFormat.parse(mytime);
    } catch (ParseException e) {
        e.printStackTrace();
    }
    long mills = Date1.getTime() - Date2.getTime();
    int Hours = (int) (mills / (1000 * 60 * 60));
    int Mins = (int) (mills / (1000 * 60)) % 60;
    Log.e("Mins",Mins+"");

    CountDownTimer countDownTimer = new CountDownTimer(mills, 1000) {
        public void onTick(long millisUntilFinished) {
            long millis = millisUntilFinished;
            //Convert milliseconds into hour,minute and seconds
            String hms = String.format("%02d:%02d:%02d",
                    TimeUnit.MILLISECONDS.toHours(millis),
                    TimeUnit.MILLISECONDS.toMinutes(millis) - TimeUnit.HOURS.toMinutes(TimeUnit.MILLISECONDS.toHours(millis)),
                    TimeUnit.MILLISECONDS.toSeconds(millis) - TimeUnit.MINUTES.toSeconds(TimeUnit.MILLISECONDS.toMinutes(millis)));
            holder.txtTime.setText(hms);//set text
        }
        public void onFinish() {
            holder.txtTime.setText("00:00"); //On finish change timer text
        }
    }.start();

注意:我在适配器中使用CountDownTimer

1 个答案:

答案 0 :(得分:2)

try {
  Date1 = dateFormat.parse(curranttime);
} catch (ParseException e) {
    e.printStackTrace();
}
try {
  Date2 = dateFormat.parse(mytime);
} catch (ParseException e) {
    e.printStackTrace();
}
long mills = Date2.getTime() - Date1.getTime();
int Hours = (int) (mills / (1000 * 60 * 60));
int Mins = (int) (mills / (1000 * 60)) % 60;
Log.e("Mins",Mins+"");

CountDownTimer countDownTimer = new CountDownTimer(mills, 1000) {
    public void onTick(long millisUntilFinished) {
        long millis = millisUntilFinished;
        //Convert milliseconds into hour,minute and seconds
        String hms = String.format("%02d:%02d:%02d",
                TimeUnit.MILLISECONDS.toHours(millis),
                TimeUnit.MILLISECONDS.toMinutes(millis) - TimeUnit.HOURS.toMinutes(TimeUnit.MILLISECONDS.toHours(millis)),
                TimeUnit.MILLISECONDS.toSeconds(millis) - TimeUnit.MINUTES.toSeconds(TimeUnit.MILLISECONDS.toMinutes(millis)));
        holder.txtTime.setText(hms);//set text
    }
    public void onFinish() {
        holder.txtTime.setText("00:00"); //On finish change timer text
    }
}.start();

我可以减去系统时间的时间。实际上减去我的时间和工作的系统时间