Reputation: 864
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.
Upvotes: 6
Views: 29246
Reputation: 65
Complete Code:
iterationCount = 0;
final Handler handler = new Handler();
final int delay = 1000; //milliseconds
handler.postDelayed(new Runnable() {
public void run() {
//do something
if (iterationCount < 10) {
handler.postDelayed(this, delay);
}
iterationCount++;
Log.e("tag", "after 1 second: " + iterationCount);
}
}, delay);
Upvotes: 1
Reputation: 10667
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.
Upvotes: 9
Reputation: 1103
Thread thread;
//inside start button
thread=new Thread(new Runnable() {
@Override
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);
});
thread.start();
//inside stop button
mHandler.removeCallbacksAndMessages(runnable);
thread.stop();
Upvotes: -2
Reputation: 9035
Use
mHandler.removeCallbacksAndMessages(runnable);
in pause button click.
Upvotes: 15