Android: finish() of CountDownTimer is called even if cancel() is called

10,476

Solution 1

Inside your onClick set a Boolean (buttonPressed for example) to true.

In your onFinish check this Boolean:

if (buttonPressed == true)
{
    //do nothing
}
else
{
    //run code
}

Solution 2

You could use Timer instead and do something like this:

private Runnable mUpdateTimeTask = new Runnable() {
    public void run() {
        // do your updates here
        mUpdateTimeHandler.postDelayed(this, 1000);
    }
};

Handler mUpdateTimeHandler = new Handler();
mUpdateTimeHandler.postDelayed(mUpdateTimeTask, 100);

When cancelling the task:

mUpdateTimeHandler.removeCallbacks(mUpdateTimeTask);
Share:
10,476
Moyeen
Author by

Moyeen

Updated on June 05, 2022

Comments

  • Moyeen
    Moyeen almost 2 years

    I have used Countdown Timer like this

    new CountDownTimer(15000, 15) {
    
                 public void onTick(long millisUntilFinished) {
    
                     long seconds=millisUntilFinished/1000;
                     long min=millisUntilFinished%100;
    
                     timeleft=(int) (seconds*1000+min);
                     if(millisUntilFinished>=10000)
                     {
                         changeText.setTextColor(Color.GREEN);
                     }
                     else if(millisUntilFinished>=5000)
                     {
                         changeText.setTextColor(Color.MAGENTA); 
                     }
                     else
                     {
                         changeText.setTextColor(Color.RED);
    
                     }
                     changeText.setText(String.format("%02d", seconds )+ "."+String.format("%02d", min )+" sec");
    
                 }
    
                 public void onFinish() {
    
                     timeleft=0;
                     missed++;
                      nametext.setTextColor(Color.RED);
                     nametext.setText("Time Up!");
                          bottombutton.setVisibility(View.INVISIBLE);   
                        globalflag=13;
                    changeText.setTextColor(Color.RED);
                    changeText.setText("0.00 Sec");
                        Handler myHandler = new Handler();
                        myHandler.postDelayed(mMyRunnablecif, 3000);
    
    
    
                 }
              }.start(); 
    

    On a button click I have called cancel() but it stops counting for a while and then calls onFinish(). I need not to call onFinish() after calling cancel(). Is there any solution for this. Any help will be highly appreciated.

  • Moyeen
    Moyeen almost 12 years
    Does onFinish() recalls the acivity where it belongs to? or calls call back oncreate()
  • Tony
    Tony almost 12 years
    onFinish() with regards to countdown timer is not connected to the activity. It is just the method called when the countdown timer completes.