我在以下程序中使用处理程序,我想在i = 5时停止它,但处理程序不会停止并连续运行。
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;
}
});
答案 0 :(得分:47)
因为您在删除回拨后再次致电postDelayed()
。请使用此代码:
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);
}
});
答案 1 :(得分:22)
protected void onStop() {
super.onStop();
handler.removeCallbacks(runnable);
}
你可以像这样停止它
答案 2 :(得分:0)
我找到了一个适合我的解决方案。这是一个代码示例,我希望计时器停止,但我看到它还活着,即使我没有活动:
boolean bFlagForceExit = false;
Handler timerHandler = new Handler();
private Runnable timerRunnable = new Runnable() {
@Override
public void run() {
if (bFlagForceExit )
MyProcessForExit();
if (bSomeflagForRunAction)
RunProcess();
timerHandler.postDelayed(this, MILISEGUNDOS_ESPERA); }
};
private void MyProcessForExit()
{
timerHandler.removeCallbacks(timerRunnable);
// close activity or whatever
finish();
}
private void RunProcess()
{
// action that i do when tick
// time to leave or stop
bFlagForceExit = true;
}
然后我发现如果要求removeCallbacks(timerRunnable)
,这是有效的
其他线程,所以,我解决了这个问题。
boolean bFlagForceExit = false;
Handler timerHandler = new Handler();
private Runnable timerRunnable = new Runnable() {
@Override
public void run() {
if (bFlagForceExit )
{
// add a thred for run your stop handler
new Thread(new Runnable() {
public void run() {
SalirDeProceso();
}
}).start();
}
if (bSomeflagForRunAction)
RUnProcess();
timerHandler.postDelayed(this, MILISEGUNDOS_ESPERA); }
};
答案 3 :(得分:0)
您没有显示初始化“i”的位置。也许它永远不会< 5。
答案 4 :(得分:0)
刚刚看到了这个问题。 我会改用CountDownTimer()。 总共运行5秒钟,每秒:
new CountDownTimer(5000, 1000) {
public void onTick(long milsecRemain) {
// Code to run every second
Log.i("Seconds left", String.valueOf(milsecRemain/1000));
}
public void onFinish() {
// 10 seconds have passed
}
}.start();