This was in response to the question: “Would you provide me any insight as to how you made that timer continuously show the countdown time?” referring to an app I made:
Here’s a snippet that handles this timer, using CountDownTimer, in case anyone is having trouble creating their own:
mScheduledDate.setText(DateFormatter.formatDateTime(mDate));
mScheduledDuration.setText(DurationFormatter.format(mDuration));
long timeLeft = mDate.getTimeInMillis() - Calendar.getInstance().getTimeInMillis();
if(timeLeft < 0){
timeLeft = 0;
}
mScheduledTimeLeft.setText(DurationFormatter.format_countdown(timeLeft/1000));
if(timeLeft == 0) {
mScheduledTimeLeft.setTextColor(getResources().getColor(R.color.important));
return;
}
mScheduledTimeLeft.setTextColor(getResources().getColor(R.color.success));
mScheduledCountdown = new CountDownTimer(timeLeft, 1000){
@Override
public void onTick(long l) {
mScheduledTimeLeft.setText(DurationFormatter.format_countdown(l/1000));
if(l <= WARNING_THRESHOLD){
if(l <= IMPORTANT_THRESHOLD){
mScheduledTimeLeft.setTextColor(getResources().getColor(R.color.important));
}else
mScheduledTimeLeft.setTextColor(getResources().getColor(R.color.warning));
}
}
@Override
public void onFinish() {
mTimerEndListener.onScheduledTimerEnd();
}
}.start();
I also have a countdown in the status bar:
And the code for that using the setUsesChronometer for NotifcationCompat.builder:
mBuilder = new NotificationCompat.Builder(getApplicationContext());
mBuilder.setContentTitle(getResources().getString(R.string.notif_title_active))
.setContentText(getResources().getString(R.string.notif_text_active) + " " + DurationFormatter.format_countdown(timeLeft/1000))
.setWhen(mBucket.time_last_started.getTime())
.setUsesChronometer(true)
.setLargeIcon(mLogo)
.setSmallIcon(R.drawable.ic_action_time);
mBuilder.setContentIntent(mResultPendingIntent);
mNotifyManager.notify(NOTIF_ID_COUNTDOWN, mBuilder.build());
Hope this helps.