Reputation: 3031
I have a thread:
handlerStoper.post(new Runnable() {
@Override
public void run() {
startTime.setText(""+count);
startTime.invalidate();
count++;
handlerStoper.postDelayed(this, 1000);
}
});
How can I stop this thread i other place?
Upvotes: 0
Views: 114
Reputation: 133560
public final void removeCallbacks (Runnable r)
Added in API level 1
Remove any pending posts of Runnable r that are in the message queue.
Use removeCallbacks
as @blackbelt Sugested or pass the runnable instance as param.
handlerStoper.removeCallbacks(null);
http://developer.android.com/reference/android/os/Handler.html#removeCallbacks(java.lang.Runnable)
Upvotes: 0
Reputation: 157447
to remove all the callback from an handler you have to call:
handlerStoper.removeCallbacks(null);
with the argument null
all the Runnable will be removed. If you want to remove a specific runnable you have to provide as parameter the instance of the Runnable you want to remove.
public final void removeCallbacks (Runnable r)
Added in API level 1
Remove any pending posts of Runnable r that are in the message queue.
http://developer.android.com/reference/android/os/Handler.html#removeCallbacks(java.lang.Runnable)
Upvotes: 4
Reputation: 832
Handler mhandler=new Handler();
Runnable r= new Runnable() {
@Override
public void run() {
startTime.setText(""+count);
startTime.invalidate();
count++;
mhandler.postDelayed(r, 1000);
}
});
//when stop thread write
mhandler.removeCallbacks(r);
Upvotes: 1
Reputation: 1879
public void run() {
startTime.setText(""+count);
startTime.invalidate();
count++;
if(flag){
handlerStoper.postDelayed(this, 1000);
}
}
set the flag value to false when you want to stop the thread.
Upvotes: 1