本文介绍了如何停止Handler Runnable?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我在以下程序中使用处理程序,我想在i = 5时停止它,但处理程序不会停止并连续运行。
I am using a handler in the following program and I want to stop it when i=5 but the handler doesn't stop and run continuously.
b1.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
handler = new Handler();
runnable = new Runnable() {
public void run() {
try {
Toast.makeText(getApplicationContext(), "Handler is working", Toast.LENGTH_LONG).show();
System.out.print("Handler is working");
if(i==5){
//Thread.currentThread().interrupt();
handler.removeCallbacks(runnable);
System.out.print("ok");
Toast.makeText(getApplicationContext(), "ok", Toast.LENGTH_LONG).show();
}
i++;
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
handler.postDelayed(this, 5000);
}
};
handler.postDelayed(runnable, 5000);
//return;
}
});
推荐答案
因为你打电话给 postDelayed(删除回拨后再次
。请使用此代码:
Because you call postDelayed()
again after removing call backs. Please use this code:
final Handler handler = new Handler();
final Runnable runnable = new Runnable() {
public void run() {
Log.d("Runnable","Handler is working");
if(i == 5){ // just remove call backs
handler.removeCallbacks(this);
Log.d("Runnable","ok");
} else { // post again
i++;
handler.postDelayed(this, 5000);
}
}
};
//now somewhere in a method
b1.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
handler.removeCallbacks(runnable);
handler.postDelayed(runnable, 5000);
}
});
这篇关于如何停止Handler Runnable?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!