Android Runnable在removeCallbacks()之后没有停止

时间:2016-08-31 10:51:40

标签: android runnable

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

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

和我的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);
        }
    }
};

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

public void checkPayNow(){

    if (!url.isEmpty()){

        //url now has text

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


}

2 个答案:

答案 0 :(得分:1)

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

答案 1 :(得分:0)

您可以尝试不使用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();


}