Stop handler.postDelayed()
You can define a boolean and change it to false when you want to stop handler. Like this..
boolean stop = false;
handler.postDelayed(new Runnable() {
@Override
public void run() {
//do your work here..
if (!stop) {
handler.postDelayed(this, delay);
}
}
}, delay);
this may be old, but for those looking for answer you can use this...
public void stopHandler() {
handler.removeMessages(0);
}
cheers
Boolean condition=false; //Instance variable declaration.
//-----------------Inside oncreate---------------------------------------------------
start =(Button)findViewById(R.id.id_start);
start.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
starthandler();
if(condition=true)
{
condition=false;
}
}
});
stop=(Button) findViewById(R.id.id_stoplocatingsmartplug);
stop.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
stophandler();
}
});
}
//-----------------Inside oncreate---------------------------------------------------
public void starthandler()
{
handler = new Handler();
handler.postDelayed(new Runnable() {
@Override
public void run() {
if(!condition)
{
//Do something after 100ms
}
}
}, 5000);
}
public void stophandler()
{
condition=true;
}
You can use:
Handler handler = new Handler()
handler.postDelayed(new Runnable())
Or you can use:
handler.removeCallbacksAndMessages(null);
Docs
public final void removeCallbacksAndMessages (Object token)
Added in API level 1 Remove any pending posts of callbacks and sent messages whose obj is token. If token is null, all callbacks and messages will be removed.
Or you could also do like the following:
Handler handler = new Handler()
Runnable myRunnable = new Runnable() {
public void run() {
// do something
}
};
handler.postDelayed(myRunnable,zeit_dauer2);
Then:
handler.removeCallbacks(myRunnable);
Docs
public final void removeCallbacks (Runnable r)
Added in API level 1 Remove any pending posts of Runnable r that are in the message queue.
public final void removeCallbacks (Runnable r, Object token)
Edit:
Change this:
@Override
public void onClick(View v) {
Handler handler = new Handler();
Runnable myRunnable = new Runnable() {
To:
@Override
public void onClick(View v) {
handler = new Handler();
myRunnable = new Runnable() { /* ... */}
Because you have the below. Declared before onCreate
but you re-declared and then initialized it in onClick
leading to a NPE.
Handler handler; // declared before onCreate
Runnable myRunnable;