Android Runnable 在 removeCallbacks() 后不停止

Android Runnable not stopping after removeCallbacks()

我正在尝试使用 removeCallbacks 停止 Runnable,但不知何故它不会停止。 - 这是我的变量

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

和我的可运行

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);
        }
    }
};

我的方法 运行 直到它给了我一定的价值然后我停止

public void checkPayNow(){

    if (!url.isEmpty()){

        //url now has text

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


}

你可以尝试在没有 removeCallbacks 的情况下这样做:

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();


}
boolean stoped = false;

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

欲罢不能stoped = true

并从 checkPayNow() 中删除处理程序。

public void checkPayNow(){

    if (!url.isEmpty()){
        //url now has text
        //mHandler.removeCallbacks(mStatusChecker);
    }else {
        //no text yet
    }
}