如何停止Handler Runnable?

我在下面的程序中使用一个处理程序,我想停止它,当我= 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; } }); 

Solutions Collecting From Web of "如何停止Handler Runnable?"

因为您在删除回叫后再次调用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); } }); 
 protected void onStop() { super.onStop(); handler.removeCallbacks(runnable); } 

你可以像这样阻止它

我find了一个适合我的解决scheme。 这是一个代码示例,我希望计时器能够停下来,但即使我没有活动,我仍然看到它还活着:

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

你不显示“我”被初始化的地方。 也许它从来没有<5。