1

I am trying to stop Runnable using removeCallbacks, but somehow it wont stop. - here are my variables

 private int mInterval = 2000; // 2 seconds by default, can be changed later
private Handler mHandler = new Handler();

and my runnable

Runnable mStatusChecker = new Runnable() {
    @Override
    public void run() {
        try {

                checkPayNow();

        } finally {
            // 100% guarantee that this always happens, even if
            // your update method throws an exception
            mHandler.postDelayed(mStatusChecker, mInterval);
        }
    }
};

and the method I am running untill it gives me a certain value then i stop

public void checkPayNow(){

    if (!url.isEmpty()){

        //url now has text

        mHandler.removeCallbacks(mStatusChecker);
    }else {
        //no text yet
    }


}
Harian Manda
  • 248
  • 1
  • 9

2 Answers2

1
boolean stoped = false;

Runnable mStatusChecker = new Runnable() {
    @Override
    public void run() {
        try {    
             checkPayNow();
        } finally {
           if(!stoped)
            mHandler.postDelayed(mStatusChecker, mInterval);
        }
    }
};

Make stoped = true when you want to stop.

and remove handler from checkPayNow().

public void checkPayNow(){

    if (!url.isEmpty()){
        //url now has text
        //mHandler.removeCallbacks(mStatusChecker);
    }else {
        //no text yet
    }
}
Sohail Zahid
  • 8,099
  • 2
  • 25
  • 41
0

You can try to do it without removeCallbacks like this:

Runnable mStatusChecker = new Runnable() {
    @Override
    public void run() {
        if(!checkPayNow()) {
//if not ready so far, then check in some delay again
            mHandler.postDelayed(mStatusChecker, mInterval);
        }
    }
};

public boolean checkPayNow(){

    return !url.isEmpty();


}
Vladyslav Matviienko
  • 10,610
  • 4
  • 33
  • 52