I have a class that has a CountDownTimer, which will be use throughout my project and I want to call different methods upon the Countdown onFinish() from different activities.
Here's my CountDownTimer class;
public class CountDownTimer {
private static final long START_TIME_IN_MILLIS = 10000;
private long timeLeftInMillis = START_TIME_IN_MILLIS;
private final TextView textViewCountDown;
private CountDownTimer countDownTimer;
private boolean timerRunning;
public CountDownTimer(TextView textView) {
this.textViewCountDown = textView;
startTimer();
}
public void startTimer() {
countDownTimer = new android.os.CountDownTimer(timeLeftInMillis, 1000) {
@Override
public void onTick(long millisUntilFinished) {
timeLeftInMillis = millisUntilFinished;
updateCountDownText();
}
@Override
public void onFinish() {
timerRunning = false;
}
}.start();
timerRunning = true;
}
public void resetTimer() {
timeLeftInMillis = START_TIME_IN_MILLIS;
updateCountDownText();
}
public void pauseTimer() {
countDownTimer.cancel();
timerRunning = false;
}
}
Example Scenario - Once a specific activity prompted, countdown will start and user has 10s to do whatever he wants otherwise it will automatically collect data and validate. So, once the 10s is over validating and data collecting methods should call from the activity.
I am a newbie to Android Dev and Thanks in advance!
There is multiple ways to achive this, each of them with different preferences. For your usecase i guess you could look into Broadcasts. Have all Activities that need to perform an action after the countdown implement a BroadcastReceiver which reacts to the Broadcast sent by your CountDownTimer.
Another option would be to implement some way of eventhandling. Android doesn't provide a event API, but you could look into the EventBus lib. Alternatively you could also just write your own event framework. For a simple case like yours it shouldn't be to complex.