Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Timer does not stop in android

Tags:

android

timer

I made an application in android and used timer like this..

try {
    CountDownTimer  start1 = new CountDownTimer(20000, 1000) {

        public void onTick(long millisUntilFinished) {
                TextView timeShow = (TextView)findViewById(R.id.showTime);
        timeShow.setText(" "+" 00:" +millisUntilFinished / 1000);
            }

But my problem is i don't know how to stop timer. Any idea?

I already tried:

quitApplication.setOnClickListener(new OnClickListener() {
    public void onClick(View v) { 
        start1.cancel(); 
        Intent i = new Intent(v.getContext(), startGame.class);
        startActivity(i);
        // TODO Auto-generated method stub 
    } 
}); 
like image 654
BIBEKRBARAL Avatar asked Mar 04 '10 07:03

BIBEKRBARAL


People also ask

How do you stop a Timer flutter?

cancel method Null safety Cancels the timer. Once a Timer has been canceled, the callback function will not be called by the timer. Calling cancel more than once on a Timer is allowed, and will have no further effect.

What is delay and period in Timer Android?

delay - delay in milliseconds before task is to be executed. period - time in milliseconds between successive task executions. (Your IDE should also show it to you automatically)


3 Answers

start1.cancel() is the correct method to call to cancel the timer.

You did not provide any details about the error you got or why it didn't work for you, but I am assuming your program didn't compile because your variable start1 is a local variable. It is probably local to whatever method your try block is in. This means your OnClickListener construction has no idea what start1 is.

To fix this simply declare start1 as a class variable (outside of all methods but within the class):

public class someClass {

CountDownTimer start1;
// blah some code
public void someMethod {
   try {
      start1 = new CountDownTimer() { //etc

Doing so will allow other methods to recognize and interact with start1

like image 88
Tony Chan Avatar answered Nov 07 '22 22:11

Tony Chan


I know this is a year old but for future readers you just need to call the timer as a final.

like so

final CountDownTimer  start1 = new CountDownTimer(20000, 1000) {}

that should work

like image 44
Muller Avatar answered Nov 07 '22 22:11

Muller


call start1.cancel() when you want to stop the timer

like image 29
Prashast Avatar answered Nov 07 '22 20:11

Prashast