Android Runnable Handler not stop at specified intervals(seconds)

531 views Asked by At

I am using Runnable Handler to update my UI at specified intervals . However on button click event my this timer stops but at specified intervals it continues to go own . Here is my code .

public class MainActivity extends ActionBarActivity {
public TextView myCounter;
private int mInterval=50;
private Handler mHandler;
int i=1;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    mHandler = new Handler();
    myCounter = (TextView) findViewById(R.id.myCounter);
}
Runnable mStatusChecker=new Runnable() {
    @Override
    public void run() {

        updateCounter();
        mHandler.postDelayed(mStatusChecker,mInterval);
    }
};

void updateCounter(){
    myCounter.setText(""+i++);
    if(i==36)
    {
        stopRepeatingTask();
    }
    if(i==66)
    {
        stopRepeatingTask();
    }
    if(i==96)
    {
        stopRepeatingTask();
    }

}
void startRepeatingTask()
{
    mStatusChecker.run();
}

void stopRepeatingTask()
{
    mHandler.removeCallbacks(mStatusChecker);
}
public void StopClick(View view)
{
    stopRepeatingTask();
}

public void StartClick(View view)
{
startRepeatingTask();
}
}

UpdateCounter function keeps on running even the value of i ==36 or 66 or 96. But its stop when I click StopClick button click event . Need help.

1

There are 1 answers

0
Maximosaic On BEST ANSWER

As far as I can see you stop the task. This stopping is done in updateCounter(), however after that you start the handler again with mHandler.postDelayed(mStatusChecker,mInterval);

You could maybe set a boolean when stopping the counter

void stopRepeatingTask()
{
    isCancelled = true;
    mHandler.removeCallbacks(mStatusChecker);
}

so that you can check in your Runnable

if (!isCancelled) {
    mHandler.postDelayed(mStatusChecker,mInterval);
}