I have to start runnable on start button click and stop it on pause button click. My code for start runnable on start button click is
// TODO Auto-generated method stub
//while (running) {
mUpdateTime = new Runnable() {
public void run() {
sec += 1;
if(sec >= 60) {
sec = 0;
min += 1;
if (min >= 60) {
min = 0;
hour += 1;
}
}
Min_txtvw.setText(String.format(mTimeFormat, hour, min, sec));
mHandler.postDelayed(mUpdateTime, 1000);
}
};
mHandler.postDelayed(mUpdateTime, 1000);
//}
now i want to stop that runnable on pause button click
pause_btn.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
play_btn.setVisibility(View.VISIBLE);
pause_btn.setVisibility(View.INVISIBLE);
}
});
How can i stop that runnable on pause button click if anyone knows please help me.
Use
mHandler.removeCallbacksAndMessages(runnable);
in pause button click.
Keep a boolean cancelled
flag to store status. Initialize it to false and then modify it to true on click of stop button.
And inside your run()
method keep checking for this flag.
Edit
Above approach works usually but still not the most appropriate way to stop a runnable/thread. There could be a situation where task is blocked and not able to check the flag as shown below:
public void run(){
while(!cancelled){
//blocking api call
}
}
Assume that task is making a blocking api call and then cancelled flag is modified. Task will not be able to check the change in status as long as blocking API call is in progress.
Alternative and Safe Approach
Most reliable way to stop a thread or task (Runnable) is to use the interrupt mechanism. Interrupt is a cooperative mechanism to make sure that stopping the thread doesn't leave it in an inconsistent state.
On my blog, I have discussed in detail about interrupt, link.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With