How to pause and resume countdown timer? - java

I have a countdown timer in my game activity and I need it paused when I get incoming call or something that lose the focus from my activity. I tried like this but it does not work (the onPause method works, it stops the timer, but it wont resume it):
private long total = 180000;
MyCount brojacVremena = new MyCount(total, 1000);
public class MyCount extends CountDownTimer {
public MyCount(long millisInFuture, long countDownInterval) {
super(millisInFuture, countDownInterval);
}
#Override
public void onFinish() {
#Override
public void onTick(long millisUntilFinished) {
total = millisUntilFinished;
vreme.setText("" + millisUntilFinished / 1000);
}
}
#Override
protected void onResume() {
// TODO Auto-generated method stub
super.onResume();
MyCount brojacVremena = new MyCount(total, 1000);
brojacVremena.start();
}
#Override
protected void onPause() {
// TODO Auto-generated method stub
super.onPause();
brojacVremena.cancel();
}
I tried even this in my onPause:
#Override
protected void onPause() {
// TODO Auto-generated method stub
super.onPause();
MyCount brojacVremenaNew = new MyCount(total, 1000);
brojacVremenaNew.cancel();
}

I do not think that you need to extend it, unless really necessary. I second what codeMagic said - store time time left in a variable in onPause() and DO NOT forget to save it in onSaveInstanceState() or to SharedPreference.
When your activity resumes, either due to config change or whatever, you can recreate your timer:
new CountDownTimer(millisUntilFinished, tickTime) {
public void onTick(long millisUntilFinished) {
millisUntilFinished -= tickTime;
// do you wanna know for whom the bell tolls?
}
public void onFinish() {
// it tolls for thee
millisUntilFinished = 0;
}
}.start();
In onPause(), cancel this timer and in onResume() create a new instance of the timer based on how much time is left :)
EDIT:
Something like this:
#Override
public void onResume(){
super.onResume();
millisUntilFinished = getMillisFromSharedPreference(KEY);
if(millisUntilFinished != 0){
new CountDownTimer(millisUntilFinished, tickTime) {
public void onTick(long millisUntilFinished) {
millisUntilFinished -= tickTime;
// do you wanna know for whom the bell tolls?
}
public void onFinish() {
// it tolls for thee
millisUntilFinished = 0;
}
}.start();
}
}
#Override
public void onPause(){
super.onPause();
saveMillisToSharedPreference(KEY,millisUntilFinished);
}

Related

countDownTimer Don't show 00:00

I'm Making a countdown timer app but the problem when the countdown finish it doesn't show me 00:00
I'm using seek bar the set the timer when I use 100 in countDown interval it works but I want it to be 1000 in the interval and I'm following a tutorial I write the same code shown in the tutorial it works for him and not for me please help me guys
public void buttonClicked(View view)
{
CountDownTimer countDown = new CountDownTimer(timerSeek.getProgress() * 1000 + 100, 1000) {
#Override
public void onTick(long millisUntilFinished) {
timerUpdate((int) millisUntilFinished / 1000);
}
#Override
public void onFinish() {
Toast.makeText(MainActivity.this, "finish", Toast.LENGTH_SHORT).show();
}
}.start();
}
/* ========================================================= */
/* ========================================================= */
public void timerUpdate(int secondsLeft)
{
int minutes = secondsLeft / 60;
int seconds = secondsLeft - (minutes * 60);
String secondsStr = Integer.toString(seconds);
if (seconds <= 9)
secondsStr = "0" + secondsStr;
timerText.setText(Integer.toString(minutes) + " : " + secondsStr);
}
/* ============================================================ */
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
timerSeek = (SeekBar) findViewById(R.id.timerSeek);
timerText = (TextView) findViewById(R.id.timerText);
timerSeek.setMax(600);
timerSeek.setProgress(30);
timerSeek.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
#Override
public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
timerUpdate(progress);
}
#Override
public void onStartTrackingTouch(SeekBar seekBar) {
}
#Override
public void onStopTrackingTouch(SeekBar seekBar) {
}
});
}
This is because onTick() method is not called when the countdown is finished. Rather, onFinish() is called. An easy solution that appears to me is that you can explicitly show 00:00 inside onFinish(), since this method is called when the countdown is finished.

Get variable from countdown and set it to TextView

I need your help to get a variable from the countdown and set that value to text view. Suppose if countdown stopped at 0:40 sec and I want to put that number to text view.
So I'm using Seekbar to update the time with progress and a textview. And suppose I stopped at a certain number, next time I start again, let the number start from when it stopped. I have uploaded the image of output. Thanks
I learned to create this app from udemy online tutorial. Its called Complete android developer course- Build 23 Apps!!. Its lesson 38- App Egg timer.
This is my MainActivity.java file
public class MainActivity extends AppCompatActivity {
TextView timerTv;
SeekBar timerSeekBar;
Button startBtn;
CountDownTimer countDownTimer;
boolean counterisActive = false;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
timerTv = (TextView) findViewById(R.id.countdowntimertextview);
timerSeekBar = (SeekBar) findViewById(R.id.timerSeekBar);
startBtn = (Button) findViewById(R.id.startBtn);
timerSeekBar.setMax(300);
timerSeekBar.setProgress(20);
timerSeekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
#Override
public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
updateTimer(progress);
Log.i("Seekbar changes", String.valueOf(progress), null);
}
#Override
public void onStartTrackingTouch(SeekBar seekBar) {
}
#Override
public void onStopTrackingTouch(SeekBar seekBar) {
}
});
}
public void resetTimer(){
//This is where I want to set the text.
timerTv.setText("Trying to get text from countdown!!");
startBtn.setText("START!");
timerSeekBar.setEnabled(true);
countDownTimer.cancel();
timerSeekBar.setProgress(20);
counterisActive = false;
}
public void buttonClicked(View view){
if(counterisActive){
resetTimer();
}else {
counterisActive = true;
timerSeekBar.setEnabled(false);
startBtn.setText("STOP!");
Log.i("Button Clicked", "Clicked");
countDownTimer = new CountDownTimer(timerSeekBar.getProgress() * 1000 + 100, 1000) {
#Override
public void onTick(long millisUntilFinished) {
updateTimer((int) millisUntilFinished / 1000);
}
#Override
public void onFinish() {
MediaPlayer mediaPlayer = MediaPlayer.create(getApplicationContext(), R.raw.templebell);
mediaPlayer.start();
Log.i("Timer Finished", "Done!!");
resetTimer();
}
}.start();
}
}
public void updateTimer(int secondLefts){
int minutes = secondLefts / 60;
int seconds = secondLefts - (minutes * 60);
String secondString = Integer.toString(seconds);
if(seconds <= 9) {
secondString = "0" + seconds;
}
timerTv.setText(minutes + " : " + secondString );
}
}
I think you need to pause the timer.
First create a global long variable in your activity;
long timerProgress;
Change your restProgress() method like below, or you can add new method pauseTimer().
public void restTimer(){
//This is where I want to set the text.
updateTimer((int) timerProgress/1000);
startBtn.setText("START!");
timerSeekBar.setEnabled(true);
countDownTimer.cancel();
timerSeekBar.setProgress((int) timerProgress/1000);
counterisActive = false;
}
Know add this line to your override method onTick.
#Override
public void onTick(long millisUntilFinished) {
updateTimer((int) millisUntilFinished / 1000);
// add this line for store progress timer.
timerProgress = millisUntilFinished;
}
You can add another button one for pause and other for rest Timer.
Try replacing timerTv.setText(minutes + " : " + secondString ); with
runOnUiThread(new Runnable() {
#Override
public void run() {
timerTv.setText(minutes + " : " + secondString );
}
});
If you try to update the UI mid-thread, it will wait until the current thread has finished before updating the text.

Set Visibility after countdown ends

Despite thorough search of other user's questions, I don't seem to understand how to do a countdown timer. All I wanna do is setting visibility to GONE after 30 seconds without touching the screen. So far I've done this:
public class StatusFragment extends Fragment {
CountDownTimer countDownTimer;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
countDownTimer = new CountDownTimer(30000, 1000) {
public void onTick(long millisUntilFinished) {
//SET VISIBILITY TO VISIBLE
}
public void onFinish() {
//SET VISIBILITY TO GONE
}
}.start();
cpHover.setOnClickListener(new OnClickListener() {
//Should I countDownTimer.start()? It says there's an error
#Override
public void onClick(View view) {
if(textBox.getVisibility()==View.GONE){
donutProgress.setVisibility(View.VISIBLE);
textBox.setVisibility(View.VISIBLE);
image.setVisibility(View.VISIBLE);
}
else if(textBox.getVisibility()==View.VISIBLE){
donutProgress.setVisibility(View.GONE);
textBox.setVisibility(View.GONE);
image.setVisibility(View.GONE);
}
}
});
The process should be quite easy. Setting in onCreate() a 30-second countdown that starts every time the user clicks cpHover. When they click it again, it should restart the countdown. There are two ways of hiding the UI: clicking on the screen when it's visible or not clicking at all in 30+ seconds.
Thanks in advance.
add this inside your onCreate()
final Handler handler = new Handler();
handler.postDelayed(new Runnable() {
#Override
public void run() {
//set visibility as gone here
if(textBox.getVisibility()==View.VISIBLE){
donutProgress.setVisibility(View.GONE);
textBox.setVisibility(View.GONE);
image.setVisibility(View.GONE);
}
}
}, 30000);
Its very Simple, just change your code as per below :
countDownTimer = new CountDownTimer(30000, 1000) {
public void onTick(long millisUntilFinished) {
//SET VISIBILITY TO VISIBLE
donutProgress.setVisibility(View.VISIBLE);
textBox.setVisibility(View.VISIBLE);
image.setVisibility(View. VISIBLE);
}
public void onFinish() {
//SET VISIBILITY TO GONE
donutProgress.setVisibility(View.GONE);
textBox.setVisibility(View.GONE);
image.setVisibility(View.GONE);
}
}
}.start();
you want to start CountDownTimer in Click event then add above code in the click event
Happy Coading....
Update your code:
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setUpCountDown();
cpHover.setOnClickListener(new OnClickListener() {
//Should I countDownTimer.start()? It says there's an error
#Override
public void onClick(View view) {
if(countDownTimer != null) {
countDownTimer.cancel();
}
setUpCountDown();
}
);
}
private void setUpCountDown() {
countDownTimer = new CountDownTimer(30000, 1000) {
public void onTick(long millisUntilFinished) {
//SET VISIBILITY TO VISIBLE
donutProgress.setVisibility(View.VISIBLE);
textBox.setVisibility(View.VISIBLE);
image.setVisibility(View.VISIBLE);
}
public void onFinish() {
donutProgress.setVisibility(View.GONE);
textBox.setVisibility(View.GONE);
image.setVisibility(View.GONE);
}
}.start();
}

Android for loop not counting properly

So I have 3 timers. For the first one I want only to appear once, because it's something like get ready timer.
For the second and third I want to appear as many times as user wants. Before timers start user must select number of times by pressing on + or - buttons which then set value of a TextView.
That's done with this code:
int counter = 0;
homeScreenPlus.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
dodajInterval();
homeScreenMinus.setEnabled(counter > 0);
}
});
homeScreenMinus.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
oduzmiInterval();
homeScreenMinus.setEnabled(counter > 0);
}
});
}
private void oduzmiInterval() {
counter--;
brojIntervala.setText(Integer.toString(counter));
}
private void dodajInterval() {
counter++;
brojIntervala.setText(Integer.toString(counter));
}
And here's the code for timers:
public void homeScreenStart(View view) {
linearniLayoutSetup.setVisibility(View.GONE);
CountDownTimer firstCountDown = new CountDownTimer(seekBarTimerDelay.getProgress() * 1000 + 100, 1000) {
#Override
public void onTick(long millisUntilFinished) {
updateTimer((int) millisUntilFinished / 1000);
}
#Override
public void onFinish() {
textViewTimerVrijeme.setText("00:00");
countDownTimerTrci();
karticaTimera.setBackgroundColor(getResources().getColor(R.color.kartica_trci));
textViewTimerTrciHodajBlaBla.setText(getResources().getString(R.string.timer_trci));
}
}.start();
}
public void countDownTimerTrci() {
for (int i = 0; i < counter; i++) {
toolbar.setBackgroundColor(getResources().getColor(R.color.kartica_trci));
CountDownTimer secondCountDown = new CountDownTimer(seekBarIntervaliVisokogIntenziteta.getProgress() * 1000 + 100, 1000) {
#Override
public void onTick(long millisUntilFinished) {
updateTimer((int) millisUntilFinished / 1000);
}
#Override
public void onFinish() {
textViewTimerVrijeme.setText("00:00");
karticaTimera.setBackgroundColor(getResources().getColor(R.color.kartica_hodaj));
imageViewTimerSlika.setImageResource(R.drawable.ic_timer_niski_intenzitet);
textViewTimerTrciHodajBlaBla.setText(getResources().getString(R.string.timer_hodaj));
toolbar.setBackgroundColor(getResources().getColor(R.color.kartica_hodaj));
CountDownTimer thirdCountDown = new CountDownTimer(seekBarIntervaliNiskogIntenziteta.getProgress() * 1000 + 100, 1000) {
#Override
public void onTick(long millisUntilFinished) {
updateTimer((int) millisUntilFinished / 1000);
}
#Override
public void onFinish() {
textViewTimerVrijeme.setText("00:00");
countDownTimerTrci();
}
}.start();
}
}.start();
}
}
As you can see, it's a method which is called when button is pressed and I wan't first timer to appear only once and that's why I didn't include it in foor loop.
First timer shows only once and that works, but other two timers keep repeating until I close the app.
Can someone tell me where the problem is?
Try this ,replace your countDownTimerTrci method with mine
public void countDownTimerTrci() {
if(counter>0) {
toolbar.setBackgroundColor(getResources().getColor(R.color.kartica_trci));
CountDownTimer secondCountDown = new CountDownTimer(seekBarIntervaliVisokogIntenziteta.getProgress() * 1000 + 100, 1000) {
#Override
public void onTick(long millisUntilFinished) {
updateTimer((int) millisUntilFinished / 1000);
}
#Override
public void onFinish() {
textViewTimerVrijeme.setText("00:00");
karticaTimera.setBackgroundColor(getResources().getColor(R.color.kartica_hodaj));
imageViewTimerSlika.setImageResource(R.drawable.ic_timer_niski_intenzitet);
textViewTimerTrciHodajBlaBla.setText(getResources().getString(R.string.timer_hodaj));
toolbar.setBackgroundColor(getResources().getColor(R.color.kartica_hodaj));
CountDownTimer thirdCountDown = new CountDownTimer(seekBarIntervaliNiskogIntenziteta.getProgress() * 1000 + 100, 1000) {
#Override
public void onTick(long millisUntilFinished) {
updateTimer((int) millisUntilFinished / 1000);
}
#Override
public void onFinish() {
counter--;
textViewTimerVrijeme.setText("00:00");
countDownTimerTrci();
}
}.start();
}
}.start();
}
}

How to countDownTimer.cancel(); in OnTick(); function

Hi i am trying to cancel a countdown timer in On-tick function, It is working fine in lollipop but not working in Kitkat and below. How cancel it from a OnTick() function.
private void startTimer(final int minuti) {
countDownTimer = new CountDownTimer(60 * minuti * 1000 + sec * 1000,
500) {
#Override
public void onTick(long leftTimeInMilliseconds) {
CountDownTimer.cancel();
}
#Override
public void onFinish() {
}
}.start();
}
Somehow if you call countdowntimer.cancel of a CountDownTimer object in its own onTick method it won't work!
The simplest way to solve your problem is defining another CountDownTimer, same as the main one, in order to check the condition to call countdowntimer.cancel. The point is that you are calling objects cancel method from outside of its own onTick method.
Check the example below:
CountDownTimer countdowntimer;
CountDownTimer assist;
long millisuntillfinish = 10000;
int interval = 100;
countdowntimer = new CountDownTimer(millisuntillfinish, interval) {
#Override
public void onTick(long millisUntilFinished) {
// if(true) countdowntimer.cancel(); (doesnt work)
}
#Override
public void onFinish() {
}
};
assist = new CountDownTimer(timertillfinish, timerinterval) {
#Override
public void onTick(long millisUntilFinished) {
if (true) {
countdowntimer.cancel();
}
}
#Override
public void onFinish() {
assist.cancel();
}
};
I know this question is more than 6 years old, but calling super.cancel(); within onTick() did the trick for me.
Leaving this here for the next unfortunate soul looking for an answer to this question.
ie.
new CountDownTimer(5000, 1000) {
public void onTick(long millisUntilFinished) {
if(someCondition)
super.cancel();
}
public void onFinish() {
//do something else
}
}.start();
new CountDownTimer(time, 1000) {
public void onTick(long millisUntilFinished) {
if (((millisUntilFinished/1000)%5)==0){ //every 5 sec
if(true)
{
this.cancel();
}
}
}
public void onFinish() {
//do somethhing
}
}.start();
I have been looking around and I have found this post where they call to the cancel() method in the onTick() using an alternative to the Android countDownTimer.
I had also this problem, and I created a global variable of a countDownTimer and I called to the cancel method in the activity when I needed, like myCountDownTimer.cancel().
private CountDownTimer mCountDownTimer;
private CountDownTimer createTimer(){
return new CountDownTimer(30000, 1000) {
public void onTick(long millisUntilFinished) {
//do what you want
}
public void onFinish() {
//do what you want
}
}.start();
}
In your activity call:
mCountDownTimer = this.createTimer();
And if you want to cancel it:
mCountDownTimer.cancel();

Categories

Resources