我有一个倒数计时器,它取出我的时间选择器的值,并在我设置时间选择器时开始倒计时,但发生的事情是它没有倒计时到你设置时间选择器的当前时间。我的问题是如何让我的倒数计时器倒计时到现在。
这是我的代码......
TimePickerDialog.OnTimeSetListener onTimeSetListener = new TimePickerDialog.OnTimeSetListener() {
@Override
public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
timer = new CounterClass((minute * 60 * 1000) + (hourOfDay * 60 * 60 * 1000), 1000);
long millis = (minute * 60 *1000) + (hourOfDay * 60 * 60 *1000);
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)));
System.out.println(hms);
textViewTime.setText(hms);
timer.start();
}
};
public class CounterClass extends CountDownTimer {
/**
* @param millisInFuture The number of millis in the future from the call
* to {@link #start()} until the countdown is done and {@link #onFinish()}
* is called.
* @param countDownInterval The interval along the way to receive
* {@link #onTick(long)} callbacks.
*/
public CounterClass(long millisInFuture, long countDownInterval) {
super(millisInFuture, countDownInterval);
}
@TargetApi(Build.VERSION_CODES.GINGERBREAD)
@Override
public void onTick(long millisUntilFinished) {
long millis = millisUntilFinished;
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)));
System.out.println(hms);
textViewTime.setText(hms);
Bundle b = new Bundle();
b.putString(hms, hms);
Intent mainActivity = new Intent("android.intent.action.MAIN");
mainActivity.putExtras(b);
}
@Override
public void onFinish() {
}
}
感谢:)
答案 0 :(得分:0)
您需要获取当前时间和所选时间之间的差异,您可以使用以下内容来实现:
public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
Calendar c = Calendar.getInstance();
int totalMinutesSelected = (hourOfDay * 60) + minute;
int totalMinutesNow =(c.get(Calendar.HOUR_OF_DAY) * 60) + c.get(Calendar.MINUTE);
int seconds = (totalMinutesSelected - totalMinutesNow) * 60;
timer = new CounterClass(seconds, 1000);
...
}
在CounterClass
课程中,你必须做这样的事情;
public class CounterClass extends CountDownTimer {
Calendar c = Calendar.getInstance();
...
public void onTick(long millisUntilFinished) {
c.setTimeInMillis(System.currentTimeMillis() + millisUntilFinished);
String hms = String.format("%02d:%02d:%02d", c.get(Calendar.HOUR_OF_DAY), c.get(Calendar.MINUTE), c.get(Calendar.SECOND));
...
}
}