CountDownTimer Check every two seconds - android

I have one CountDownTimer and i want to do an action for every two wasted seconds.
countdowntimer = new CountDownTimer(10000, 1) {
#Override
public void onTick(long millisUntilFinished) {
}
#Override
public void onFinish() {
}
}.start();
For example when it starts time remaining = 10 seconds
When time remaining = 8 seconds I want to do an action
When time remaining = 6 seconds I want to do an action
and so on......

Just check if it is divisible by 2.
#Override
public void onTick(long millisUntilFinished) {
long seconds = millisUntilFinished/1000;
if ((seconds % 2) == 0)
{ // even number--do some action }
}
This is assuming you are calling the onTick() every second like
countdowntimer = new CountDownTimer(10000, 1000) {
This is probably preferable for you
Setting it up to call every 2 seconds should also work and better but leaving the original answer in case someone needs to call onTick() more often
countdowntimer = new CountDownTimer(10000, 2000) {
then you could just do the action with every call to onTick()
CountDownTimer Docs

Related

Android How do i wait for a specified time of a video

I want to wait until a specified time of a video then do smthg. How can make it in android? handler.postDelay and wait comments are not sensible I think.
Assuming that you are using android.media.MediaPlayer class for playing videos.
There are methods .getCurrentPosition()(returns current time in milliseconds) and .getDuration() (returns video duration in milliseconds) that can help you.
You can call every second(or any other time interval) .getCurrentPosition() and when it returns a specified time you can do things you need.
Same techique can be applied to Vitamio player or ExoPlayer, or any other that is able return current position.
You can use countDownTimer
Switch(v.getId()){
case R.id.Yourid1:
CountDownTimer test= new CountDownTimer(3000,1000) { //count down from 3 sec to 1 sec
#Override
public void onTick(long millisUntilFinished) {
//do some thing after starting timer
}
#Override
public void onFinish() {
// do something after timer is finished
}
};
test.start();
break;
case R.id.YourId2:
CountDownTimer test1= new CountDownTimer(3000,1000) { //count down from 3 sec to 1 sec
#Override
public void onTick(long millisUntilFinished) {
//do some thing after starting timer
}
#Override
public void onFinish() {
// do something after timer is finished
}
};
test1.start();
}
break;

How to update TextView with CountdownTimer onResume?

I want to use a Countdown Timer but have a problem. If i start it and then press a Back button (change lifecycle to onStop) and return back to activity - i cant see timer values in TextView. But in Logcat i see that the timer works.
Question: how to update TextView after return on activity (onResume)
UPDATE.
While i'll not close activity this code works as it should - well. But if i press back button there is no values in TextView.
The timer method code (this method is called from onCreate):
timer = new CountDownTimer(rest + 1000, 1000) {
#Override
public void onTick(long millisUntilFinished) {
secondsUntilFinish = Math.round(millisUntilFinished / 1000);
String minutes = String.format("%02d",TimeUnit.SECONDS.toMinutes(secondsUntilFinish));
String seconds = String.format("%02d",TimeUnit.SECONDS.toSeconds(secondsUntilFinish) - TimeUnit.MINUTES.toSeconds(TimeUnit.SECONDS.toMinutes(secondsUntilFinish)));
tvRoutineTimer.setText(getResources().getString(R.string.exercise_rest_timer, minutes, seconds));
Log.d(LOG_TAG, "onTick = " + getResources().getString(R.string.exercise_rest_timer, minutes, seconds));
}
#Override
public void onFinish() {
tvRoutineProgress.setText(getString(R.string.routine_progress, currentStep, totalSteps));
tvRoutineTimer.setText(getString(R.string.exercise_rest_timer, "00", "00"));
notificationAfterRest();
btnExerciseDone.setText(getString(R.string.button_exercise_done));
btnExerciseDone.setEnabled(true);
tvExercisePlaceholder.setText(getString(R.string.exercise_current_title));
}
}.start();
You need to update your TextView from the UI thread. Update your TextView like this:
runOnUiThread(new Runnable() {
#Override
public void run() {
tvRoutineTimer.setText(getResources().getString(R.string.exercise_rest_timer, minutes, seconds));
});
Place the runOnUiThread inside the onTick()

Get remaining time on CountdownTimer and use the remaining time as a score android

So i have here Quiz App and have timer. So what i want to happen for example i have set the timer for 15 seconds and if the user answer the question in 5 seconds i want the 10 seconds ramaining become 10 points and it will add to previous score plus the score of you will get upon answering the questions. so for now i have this ...
if(savedInstanceState!=null){
//saved instance state data
int exScore = savedInstanceState.getInt("score");
scoreText.setText("Score: "+exScore);
}
Timer = new CountDownTimer(15000, 1000) {
#Override
public void onTick(long millisUntilFinished) {
tv_time.setText("" + millisUntilFinished / 1000);
int progress = (int) (millisUntilFinished / 150);
progressBar.setProgress(progress);
}
#Override
public void onFinish() {
progressBar.setProgress(0);
timeUp(context);
}
}.start();
and here is the one for onclick. if the user answer correctly it will add 10points automatically
public void onClick(View view) {
Button clicked = (Button) view;
int exScore = getScore();
if (clicked.getText().toString().equals(this.active_question.getAnswer()) ) {
if (this.questions.size() > 0) {
setQuestion(questions.poll());
scoreText.setText("Score: " + (exScore + 10))
} else {
CustomGameOver cdd = new CustomGameOver(PlayQuizActivity.this);
cdd.getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
cdd.show();
setHighScore();
Timer.cancel();
}
}
I dont have any idea on how to get the remaianing time on CountdownTimer and add it as a score when the answer is correct. could anyone please help me please.
Just use millisUntilFinished from onTick of the CountDownTimer
And the bonus will be millisUntilFinished/1000
P.S I think you better use a lower interval than 1000, so the ProgressBar will seem smoother.
All you need to do is declare a long variable timeleft in your MainActivity.
long timeleft;
Then, when you create a new Timer, set the "onTick" override to update the timeleft variable each "onTick" (which in the following example is 1000 milliseconds )
timer = new CountDownTimer(time, 1000) {
#Override
public void onTick(long millisecondsUntilFinished) {
timeleft = millisecondsUntilFinished;
}
}
Your app can access then the variable timeleft every time you need to check how much time is left.
score = score + timeleft / 1000; // divide by 1000 to get seconds
Have in mind that if you need to update the timer, you have to cancel it and create a new timer with the updated time left (and the same override);
timeleft = timeleft + bonustime; // (if you want to add bonus time, remember has to be in milliseconds)
if( timer != null){ timer.cancel();} // better check first if the timer exists
timer = new CountDownTimer(timeleft, 1000) {
#Override
public void onTick(long millisecondsUntilFinished) {
timeleft = millisecondsUntilFinished;
}

Problems with starting and stopping CountDownTimer with buttons

I have an edit text for entering a time in minutes, a button to start a countdown timer using the minutes entered in the edit text which updates a text view, and a button which I want to cancel the countdown timer before it finishes.
The problems I'm having are...the variable the countdown timer needs (the milliseconds) can't get assigned until I click the start timer button because it's coming from an edit text. So I created the countdown timer inside of the onClick for the start timer button. However...I want another button to cancel the timer...and it doesn't have access to the countdown timer. So that didn't solve anything and I'm confused at how to do this. Any advice would help.
Edit: I just realized I could move the stop timer button with the listener to the start timer button onClick also...under the countdown timer. I'm just confused about how the countdown timer could find the milliseconds variable if I have countdown timer outside of the start timer onClick. I guess moving the stop timer under countdown timer works...but still feels like I'm missing something.
Edit2: I tried moving countDownTimer into onCreate and making milliseconds global...but I have to make countDownTimer final in order for the buttons to be able to use it, and countDownTimer just skips to onFinish.
mTimerTextView = (TextView)findViewById(R.id.timer_text_view);
mTimerEditText = (EditText)findViewById(R.id.timer_edit_text);
mStartTimerButton = (Button)findViewById(R.id.btn_start_timer);
mStartTimerButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// Getting time in minutes from edit text
int timeEntered = Integer.parseInt(mTimerEditText.getText().toString());
long milliseconds = timeEntered * 60000;
CountDownTimer countDownTimer = new CountDownTimer(milliseconds, 1000) {
#Override
public void onTick(long millisUntilFinished) {
int seconds = (int) (millisUntilFinished / 1000) % 60;
int minutes = (int) ((millisUntilFinished / (1000*60)) % 60);
int hours = (int) ((millisUntilFinished / (1000*60*60)) % 24);
mTimerTextView.setText(String.format("%02d:%02d:%02d", hours, minutes, seconds));
}
#Override
public void onFinish() {
new AlertDialog.Builder(DailyGoalActivity.this)
.setTitle("Time's Up")
.setPositiveButton("OK", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
}).show();
}
};
countDownTimer.start();
}
});
mStopTimerButton = (Button)findViewById(R.id.btn_stop_timer);
mStopTimerButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
// countDownTimer.cancel(); <- How could I do this?
}
});
there are two possible reason for your problem first one is that you need to create countdown timer in onCreate and second one is that you are stopping null countdown timer.
solution-1 you can use a boolean variable to check that timer has start or not and then start timer accordingly on button click.Apart from this initialize timer in on create and start in on click follow this code please follow this link
solution-2 to stop the timer use this code
if(countDownTimer != null) {
countDownTimer .cancel();
countDownTimer = null;
}
Isn't the simple solution to declare CountDownTimer variable globally?
Move this code to onCreate
CountDownTimer countDownTimer = new CountDownTimer(milliseconds, 1000) {
#Override
public void onTick(long millisUntilFinished) {
int seconds = (int) (millisUntilFinished / 1000) % 60;
int minutes = (int) ((millisUntilFinished / (1000*60)) % 60);
int hours = (int) ((millisUntilFinished / (1000*60*60)) % 24);
mTimerTextView.setText(String.format("%02d:%02d:%02d", hours, minutes, seconds));
}
}
Then start timer in Start button's onClick and cancel in Stop button's onClick.
Hope it helps.

how to display Count down clock?

In my application one option is there which is used to select the application trigger time that is implemented in RadioButtons like : 10 mins, 20Mins, 30mins and 60mins
after selecting one of them the application starts at that time.. up to this working fine.
But, now I want to display a count down clock after selecting one option from above from that time onwords one clock, I want to display
That will useful to user how much time remaining to trigger the application
if any body knows about this please try to help me
Thanks for reading
Something like this for short counts:
public void timerCountDown(final int secondCount){
Handler handler = new Handler();
handler.postDelayed(new Runnable() {
public void run() {
if (secondCount > 0){
//format time and display
counterBox.setText(Integer.toString((secondCount)));
timerCountDown(secondCount - 1);
}else{
//do after time is up
removeCounterViews();
}
}
}, 1000);
}
But this one is even better and it has two events which update the main UI thread: on tick and on finish, where tick's lenght is defined in the second parameter:
new CountdownTimer(30000, 1000) {
public void onTick(long millisUntilFinished) {
mTextField.setText("seconds remaining: " + millisUntilFinished / 1000);
}
public void onFinish() {
mTextField.setText("done!");
}
}.start();

Categories

Resources