Adapting the response of @tinoper so that the counter stops when the foreground
of the Activity
is lost and the countdown is renewed when it returns to the foreground
Global variables
private MiContador timer;
private long lastCountDown = 30000; //Milliseconds for view ad
private Boolean isCountDown = false;
in onResume ()
@Override
protected void onResume() {
super.onResume();
Log.i(TAG, "onResume: ");
timer = new MiContador(lastCountDown, 1000);
timer.start();
}
on onPause ()
@Override
protected void onPause() {
timer.cancel();
Log.i(TAG, "onPause: ");
super.onPause();
}
MyCounter class extended from CountDownTimer
public class MiContador extends CountDownTimer {
private final String TAG = MiContador.class.getSimpleName();
public MiContador(long millisInFuture, long countDownInterval) {
super(millisInFuture, countDownInterval);
isCountDown = true;
}
@Override
public void onFinish() {
Log.i(TAG, "onFinish: ");
isCountDown = false;
}
@Override
public void onTick(long millisUntilFinished) {
Log.d(TAG, "onTick: " + String.valueOf(millisUntilFinished/1000));
lastCountDown = millisUntilFinished;
//countdownText.setText((millisUntilFinished / 1000 + ""));
}
}