我试图使用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
}
}
答案 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();
}