我创建了一个重复执行任务的处理程序,并且一旦条件满足,我也想在该处理程序中销毁它。
pinHandler = new Handler();
现在我分别创建了两个函数来启动和停止任务。
void startRepeatingPins() {
mPinSetter.run();
}
Runnable mPinSetter = new Runnable() {
@Override
public void run() {
try{
System.out.println("PinIndwx count is :"+pinIndexCount);
if(pinIndexCount==(plist.size()-1))
{
stopUpdatingPins();
pinIndexCount=0;
//pinHandler.removeCallbacks(mPinSetter);
System.out.println("Handler stopped by itself.");
}
else
{
updatePoint(plist.get(pinIndexCount));
pinIndexCount++;
}
}
finally {
pinHandler.postDelayed(mPinSetter, pinInterval);
}
}
};
private void stopUpdatingPins()
{
pinIndexCount=0;
pinHandler.removeCallbacks(mPinSetter);
System.out.println("Called the stop function.");
}
现在,问题在于,如果我调用stopUpdatingPins
函数,处理程序会停止,但是当我尝试从处理程序中自动停止它时,它就不会停止。虽然stopUpdatingPins
函数会被调用。
答案 0 :(得分:1)
像这样改变你startRepeatingPins()
,你不应该直接打电话。如果您的运行如此,那么就没有必要从Handler中删除它。因此,请使用Handler附加Runnable。
void startRepeatingPins() {
pinHandler.post(mPinSetter);
}
你在finally
中添加了帖子延迟,这意味着你在第一次停止并且最后再次开始,所以它永远不会停止。所以改变你的runnable,
Runnable mPinSetter = new Runnable() {
@Override
public void run() {
System.out.println("PinIndwx count is :"+pinIndexCount);
if(pinIndexCount==(plist.size()-1))
{
stopUpdatingPins();
pinIndexCount=0;
//pinHandler.removeCallbacks(mPinSetter);
System.out.println("Handler stopped by itself.");
}
else
{
updatePoint(plist.get(pinIndexCount));
pinIndexCount++;
pinHandler.postDelayed(mPinSetter, pinInterval);
}
}
};