0

I have Handler.I call my function every 10 second.Code working perfect,but i can't stop handler.This is my source code

handler=new Handler();
handler.post(runnable);
public Runnable runnable = new Runnable() {

    @Override
    public void run() {
        myFunction(position);
        handler.postDelayed(runnable,10000);
    }
};
public void myFunction(int position)
{
    if(position>10)
        handler.removeCallbacks(runnable);
}

I can call myfunction every 10 second,but i can't stop handler.Ho i can solve my problem?

BekaKK
  • 2,173
  • 6
  • 42
  • 80
  • What do you mean by "stopping handler"? Handler does not "run", it handles tasks given to him. Can you explain in a little more detail what do you want to achieve? – Okas Mar 29 '17 at 20:44

2 Answers2

0

You remove callback in myFunction but you postDelayed again when myFunction returns, just invert lines inside run()

@Override
    public void run() {       
        handler.postDelayed(runnable,10000);
        myFunction(position);
    }
from56
  • 3,976
  • 2
  • 13
  • 23
0

The problem is that myFunction removes the callback, then you still call handler.postDelayed to schedule a new one. There are plenty of ways to refactor this. For example:

handler=new Handler();
handler.post(runnable);
public Runnable runnable = new Runnable() {

    @Override
    public void run() {
        boolean reschedule = myFunction(position);
        if(reschedule) {
            handler.postDelayed(runnable,10000);
        }
    }
};
public boolean myFunction(int position)
{
    if(position>10) {
        return false;
    }
    return true;
}

You don't have to remove callbacks on the handler because a new one will not be scheduled in the first place.

James McCracken
  • 15,488
  • 5
  • 54
  • 62