In this example, we will pause/resume the CountDownTimer based off of the Activity lifecycle.
private static final long TIMER_DURATION = 60000L;
private static final long TIMER_INTERVAL = 1000L;
private CountDownTimer mCountDownTimer;
private TextView textView;
private long mTimeRemaining;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textView = (TextView)findViewById(R.id.text_view); // Define in xml layout.
mCountDownTimer = new CountDownTimer(TIMER_DURATION, TIMER_INTERVAL) {
@Override
public void onTick(long millisUntilFinished) {
textView.setText(String.format(Locale.getDefault(), "%d sec.", millisUntilFinished / 1000L));
mTimeRemaining = millisUntilFinished; // Saving timeRemaining in Activity for pause/resume of CountDownTimer.
}
@Override
public void onFinish() {
textView.setText("Done.");
}
}.start();
}
@Override
protected void onResume() {
super.onResume();
if (mCountDownTimer == null) { // Timer was paused, re-create with saved time.
mCountDownTimer = new CountDownTimer(timeRemaining, INTERVAL) {
@Override
public void onTick(long millisUntilFinished) {
textView.setText(String.format(Locale.getDefault(), "%d sec.", millisUntilFinished / 1000L));
timeRemaining = millisUntilFinished;
}
@Override
public void onFinish() {
textView.setText("Done.");
}
}.start();
}
}
@Override
protected void onPause() {
super.onPause();
mCountDownTimer.cancel();
mCountDownTimer = null;
}