我在TextView中显示可视倒计时,我想知道是否有更有效的方法来实现倒计时逻辑。我觉得在每个刻度上进行计算(即使计算很简单)可能会随着时间的推移消耗电池。
long now = Calendar.getInstance().getTimeInMillis();
Calendar midnight = new GregorianCalendar();
midnight.set(Calendar.HOUR_OF_DAY, 0);
midnight.set(Calendar.MINUTE, 0);
midnight.set(Calendar.SECOND, 0);
midnight.set(Calendar.MILLISECOND, 0);
midnight.add(Calendar.DAY_OF_MONTH, 1);
long deadline = midnight.getTimeInMillis();
long diff = deadline - now;
new CountDownTimer(diff, 1000) {
public void onTick(long millisUntilFinished) {
long days = TimeUnit.MILLISECONDS.toDays(millisUntilFinished);
long hours = TimeUnit.MILLISECONDS.toHours(millisUntilFinished) - (days * 24);
long minutes = TimeUnit.MILLISECONDS.toMinutes(millisUntilFinished) - (days * 24 * 60) - (hours * 60);
long seconds = TimeUnit.MILLISECONDS.toSeconds(millisUntilFinished) - (days * 24 * 60 * 60) - (hours * 60 * 60) - (minutes * 60);
String fDays = String.format(Locale.FRANCE, "%d", days) + "J";
String fHours = String.format(Locale.FRANCE, "%d", hours) + "h";
String fMinutes = String.format(Locale.FRANCE, "%d", minutes) + "min";
String fSeconds = String.format(Locale.FRANCE, "%d", seconds) + "s";
fMinutes = (minutes < 10) ? "0" + fMinutes : fMinutes;
fSeconds = (seconds < 10) ? "0" + fSeconds : fSeconds;
String countDown = days > 0 ? fDays : "";
countDown += (!countDown.isEmpty() || hours > 0) ? fHours : null;
countDown += (!countDown.isEmpty() || minutes > 0) ? fMinutes : null;
countDown += (!countDown.isEmpty() || seconds > 0) ? fSeconds : null;
mTextView.setText(countDown);
}
public void onFinish() {
mTextView.setText("done!");
}
}.start();