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.
As far as I can see you stop the task. This stopping is done in
updateCounter()
, however after that you start the handler again withmHandler.postDelayed(mStatusChecker,mInterval);
You could maybe set a boolean when stopping the counter
so that you can check in your Runnable