Create countdown N seconds while viewing an Activity on Android

1

I want to implement a countdown of N seconds, which starts when the Activity is displayed, the counter stops when the user decides to change the app and resumes when the focus is re-focused.

Events must be detected in order to launch procedures when

  • each second change
  • when it reaches 0

and a function to know if the counter is running.

My idea is to implement a full screen advertising visualization system, which is required to visualize it N seconds.

    
asked by Webserveis 09.10.2016 в 13:58
source

2 answers

2

It's probably old (I used it in an app a couple of years ago) and you have something better but if it serves as a base this has worked for me.

About the class that extends CountDownTimer you must implement two methods only. Then from the activity where you call it with something similar to

final MiContador timer = new MiContador(30000,1000);
timer.start();


public class MiContador extends CountDownTimer{

    public MiContador(long millisInFuture, long countDownInterval) {
        super(millisInFuture, countDownInterval);
    }

    @Override
    public void onFinish() {
    //Lo que quieras hacer al finalizar

    }

    @Override
    public void onTick(long millisUntilFinished) {          
        //texto a mostrar en cuenta regresiva en un textview
        countdownText.setText((millisUntilFinished/1000+""));

    }
}

I hope you serve, greetings.

    
answered by 09.10.2016 / 14:20
source
1

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 + ""));

    }
}
    
answered by 09.10.2016 в 15:30