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; } });
Just use the removeCallbacks(Runnable r) method.
postDelayed(new Runnable() { @Override public void run() { Intent i = new Intent(MapsActivity. this,MapsActivity. class); startActivity(i); finish(); } }, TIME_OUT); Then you can use Handler#removeCallbacksAndMessages to remove this or any callback.
kill() mechanism, using existing API provided by the SDK. Manage your thread creation within a threadpool, and use Future. cancel() to kill the running thread: ExecutorService executorService = Executors.
A Handler allows you to send and process Message and Runnable objects associated with a thread's MessageQueue . Each Handler instance is associated with a single thread and that thread's message queue. When you create a new Handler it is bound to a Looper .
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); } });
protected void onStop() { super.onStop(); handler.removeCallbacks(runnable); }
you can stop it like this
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With