CountDownTimer cancel method not working - android

I was doing a basic test on "CountDownTimer" and after a particular sec i want to stop
the countdowntimer completely. i used the method cancel but its not working the way i want
please help me out.
below is the complete code
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
display = (TextView)findViewById(R.id.txtView);
startTimer();
}
public void startTimer()
{
countDownTimer = new CountDownTimer(30000, 1000) {
public void onTick(long millisUntilFinished) {
secondsLeft = millisUntilFinished / 1000;
display.setText("seconds remaining: " + secondsLeft );
if(secondsLeft == 10)
{
display.setText("CountDownTimer Canceled");
countDownTimer.cancel();
}
}
public void onFinish() {
display.setText("done!");
}
}.start();
}

Try following code, worked for me
if(TimeUnit.MILLISECONDS.toMinutes( millisUntilFinished)==0<put min here> && TimeUnit.MILLISECONDS.toSeconds(millisUntilFinished) -
TimeUnit.MINUTES.toSeconds(TimeUnit.MILLISECONDS.toMinutes(millisUntilFinished))==50<put your seconds here>)
{
display.setText("CountDownTimer Canceled");
countDownTimer.cancel();
}
Hope this will help

Related

add value every 5 minutes and reset textview

I am a beginner in Android. I have created a chronometer and it works. I added a new function (every 5 minutes a value 1000 shown in the textview, after 10 minutes it takes 2000). This function works but if I click a button exit and I re-open the chronometer, after 5 minutes the value continues to add to the previous value but I want to reset this value once I click exit. I have used
finish(); handler.removeCallbacks(null); handler.postDelayed(test, 100); but it doesn't seem to work. Thanks.
btnStart.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (lastPause != 0) {
chronometer.setBase(chronometer.getBase() + SystemClock.elapsedRealtime() - lastPause);
} else {
chronometer.setBase(SystemClock.elapsedRealtime());
}
chronometer.start();
suppl();
btnStart.setEnabled(false);
btnStop.setEnabled(true);
btnExit.setEnabled(false);
}
});
btnStop.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
chronometer.stop();
onPause();
lastPause = SystemClock.elapsedRealtime();
btnStop.setEnabled(false);
btnStart.setEnabled(false);
btnExit.setEnabled(true);
}
});
btnExit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
finish();
handler.removeCallbacks(null);
handler.postDelayed(test, 100);
}
});
}
Handler handler = new Handler();
Runnable test;
public void suppl() {
test = new Runnable() {
#Override
public void run() {
count += 1000;
tprice.setText(String.valueOf(count));
handler.postDelayed(test, 5000);
}
};
handler.postDelayed(test, 5000);
}
public void onPause() {
super.onPause();
if (handler != null)
handler.removeCallbacks(test);
}
I would suggest using a TimerTask for this purpose.
While using time task you can cancel all the pending tasks by using cancel() on the timer.
if you have any doubts in this solution, let me know.
Instead use CountDownTimer
CountDownTimer CD = new CountDownTimer(11000, 1000) {
public void onTick(long millisUntilFinished) {
xo = (int) (millisUntilFinished / 1000);
secondsleftimg.setText("seconds remaining: " + millisUntilFinished / 1000);
Try this out :
Replace this line of code :
handler.removeCallbacks(null);
with this :
handler.removeCallbacksAndMessages(null); // it will remove all hadler
btnExit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
focus.setBase(SystemClock.elapsedRealtime());
handler.removeCallbacksAndMessages(null);
lastPause= 0;
}
});

How to stop the CountDownTimer?

where should I edit this code, that i can stop the CountDown ?
How to delete the old one before I start the next new CountDown ?
public void MyCounter1(){
new CountDownTimer(60000, 1000) {
public void onTick(long millisUntilFinished) {
txt_timer.setText("Left time : " + millisUntilFinished / 1000);
}
public void onFinish() {
txt_timer.setText("done");
}
}.start();
}
here is code:
CountDownTimer timer= null;
public void MyCounter1(){
timer =new CountDownTimer(60000, 1000) {
public void onTick(long millisUntilFinished) {
txt_timer.setText("Left time : " + millisUntilFinished / 1000);
}
public void onFinish() {
txt_timer.setText("done");
}
};
timer.start();
}
// To stop & start new timer check not null of timer instance first then cancel existing timer & start new one
if(timer != null){
timer.cancel();
MyCounter1();
}
also if you want to cancel first instance and start new one you can add above lines in onFinish method which will be get called when timer finish his time.
check this:
CountDownTimer timer= null;
public void MyCounter1(){
timer =new CountDownTimer(60000, 1000) {
public void onTick(long millisUntilFinished) {
txt_timer.setText("Left time : " + millisUntilFinished / 1000);
}
public void onFinish() {
txt_timer.setText("done");
if(timer != null){
timer.cancel();
MyCounter1();
}
}
};
timer.start();
}
I did these 2 lines. I works at the time fine:
public void MyCounter1(){
CountDownTimer countDownTimer = new CountDownTimer(60000, 1000) {
public void onTick(long millisUntilFinished) {
if(my_condition=1){ //1- just make my_condition<>1 to stop the counter
txt_timer.setText("Left time : " + millisUntilFinished / 1000); }
}
public void onFinish() {
countDownTimer.cacel(); // 2- delete old one
txt_timer.setText("done");
}
}.start();
}
private int time = 10; //example 10 min.
CountDownTimer(60000 * time, 1000)
#Override
public void onFinish() {
txt_timer.setText("done");
cancel();
time = 0;

Close and go to an activity after user downtime

I want to make a method (service, alarm, etc.) that can be calculated after x downtime user with the app
Which closes the current activity
and will send the initial activity (login)
Thank you very much
http://androidbite.blogspot.in/2012/11/android-count-down-timer-example.html
new CountDownTimer(30000, 1000) {
public void onTick(long millisUntilFinished) {
mTextField.setText("seconds remaining: " + millisUntilFinished / 1000);
//here you can have your logic to set text to edittext
}
public void onFinish() {
mTextField.setText("done!");
}
}.start();
Refer this link and some examples on countdown timer if you want to use this.
I answer
code is
private long startTime=15*60*1000; // 15 MINS IDLE TIME
private final long interval = 1 * 1000;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
countDownTimer = new MyCountDownTimer(startTime, interval);
}
#Override
public void onUserInteraction(){
super.onUserInteraction();
//Reset the timer on user interaction...
countDownTimer.cancel();
countDownTimer.start();
}
public class MyCountDownTimer extends CountDownTimer {
public MyCountDownTimer(long startTime, long interval) {
super(startTime, interval);
}
#Override
public void onFinish() {
//DO WHATEVER YOU WANT HERE
// CIERRA LA APP MATANDO EL PROCESO Y VUELVE A ABRIRLO.
android.os.Process.killProcess(android.os.Process.myPid());
}
#Override
public void onTick(long millisUntilFinished) {
}
}
use
act.finishAffinity();
act.startActivity(new Intent(act, actMain.class));

Checking if CountDownTimer is running

Ive been looking to see a method to see if a CountDownTimer is running or not, but I cant find a way to, any help would be greatly appreciated
if (position == 0) {
mCountDown = new CountDownTimer((300 * 1000), 1000) {
public void onTick(long millisUntilFinished) {
mTextField.setText("seconds remaining: "
+ millisUntilFinished / 1000);
}
public void onFinish() {
mTextField.setText("0:00");
String path = "/sdcard/Music/ZenPing.mp3";
try {
mp.reset();
mp.setDataSource(path);
mp.prepare();
mp.start();
} catch (IOException e) {
Log.v(getString(R.string.app_name),
e.getMessage());
}
}
}.start();
}
For that how can I check if mCountDown is currently running?
Just put a boolean flag which indicate that by following code
boolean isRunning = false;
mCountDown = new CountDownTimer((300 * 1000), 1000) {
public void onTick(long millisUntilFinished) {
isRunning = true;
//rest of code
}
public void onFinish() {
isRunning= false;
//rest of code
}
}.start();
onTick is your callback for a running process, you can either set a property to track the status.
isTimerRunning =false;
After start -> make it true;
Inside OnTick -> make it true (not actually required, but a double check)
Inside OnFinish -> make it false;
use the isTimerRunning property to track the status.
Check if the CountDownTimer is Running and also if the app is running in the background.
#Override
protected void onCreate(Bundle savedInstanceState) {
...
myButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
myButton.setText("Button clicked");
countDownTimer = new CountDownTimer( 3000, 1000) {
#Override
public void onTick(long millisUntilFinished) {
//After turning the Smartphone the follow both methods do not work anymore
if (!runningBackground) {
myButton.setText("Calc: " + millisUntilFinished / 1000);
myTextView.setText("Calc: " + millisUntilFinished / 1000);
}
}
#Override
public void onFinish() {
if (!runningBackground) {
//Do something
}
mTextMessage.setText("DONE");
runningBackground = false;
running = false;
}
};
//timer started
countDownTimer.start();
running = true;
}
});
}
#Override
protected void onResume() {
super.onResume();
runningBackground = false;
}
#Override
protected void onPause() {
runningBackground = true;
super.onPause();
}

CountDownTimer in android - how to restart it

I have to restart a CountDownTimer. I read a lot of question here but no one of the answer helped me.
When I use the following code
if(Const.counter != null){
Const.counter.cancel();
Const.counter = null;
}
Const.counter = new CustomTimerTask(Const.currentLevel.timeGoal * 1000,1000);
Const.counter.start();
I started a new counter but the old one also continues work. Please help me solve it.
You can realize it by cancelling and restarting. The following example should work.
CountDownTimer mCountDownTimer = new CountDownTimer(500, 1000) {
#Override
public void onTick(long millisUntilFinished) {}
#Override
public void onFinish() {
isCounterRunning = false;
}
};
boolean isCounterRunning = false;
private void yourOperation() {
if( !isCounterRunning ){
isCounterRunning = true;
mCountDownTimer.start();
}
else{
mCountDownTimer.cancel(); // cancel
mCountDownTimer.start(); // then restart
}
}
I did some different trick here. Hope this will help you.
if (myCountDownTimer != null) {
myCountDownTimer.cancel();
}
myCountDownTimer = new MyCountDownTimer(10000, 500);
myCountDownTimer.start();
coutdown timer for quiz
if(countDownTimer!=null)
{
countDownTimer.cancel();
countDownTimer.start();
}
else {
countDownTimer = new CountDownTimer(30000, 1000) {
public void onTick(long l) {
mtimer.setText("remaining time" + l / 1000);//mtime is a textview
}
public void onFinish() {//here mnext is the button from which we can get next question.
mnext.performClick();//this is used to perform clik automatically
}
}.start();
Just call again the start() method:
CountDownTimer cdt = new CountDownTimer(30000, 1000) {
public void onTick(long millisUntilFinished) {
mTextField.setText("seconds remaining: " + millisUntilFinished / 1000);
}
public void onFinish() {
this.start(); //start again the CountDownTimer
}
};
private fun startTimer() {
var timeInMilliSeconds = 11000L
val countDownTimer: CountDownTimer = object : CountDownTimer(timeInMilliSeconds, 1000) {
override fun onFinish() {
Timber.d("Times Up!")
setupResult("")
this.cancel()
timeInMilliSeconds = 11000L
this.start()
}
override fun onTick(p0: Long) {
val seconds = (p0 / 1000) % 60
Timber.d("Timer: $p0")
timer?.text = "$seconds"
}
}
countDownTimer.start()
}

Categories

Resources