I tried this way:
private Runnable changeColor = new Runnable() { private boolean killMe=false; public void run() { //some work if(!killMe) color_changer.postDelayed(changeColor, 150); } public void kill(){ killMe=true; } };
but I can't access kill()
method!
You can call cancel() on the returned Future to stop your Runnable task. cancel attempts to cancel the execution but doesn't guarantee it.
only the android will stop the thread when requires.. you cannot stop or destroy it.. instead try like this.. class MyThread extends Thread { void run() { while(bool){ //My code which takes time. } } } bool=false; now your code doesnt run... and you can start new thread...
A task that can be scheduled for one-time or repeated execution by a Timer . The Runnable interface should be implemented by any class whose instances are intended to be executed by a thread. The class must define a method of no arguments called run .
The simple fix to your example is : handler = new Handler(); final Runnable r = new Runnable() { public void run() { tv. append("Hello World"); handler. postDelayed(this, 1000); } }; handler.
Instead implement your own thread.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.newSingleThreadExecutor(); Runnable longRunningTask = new Runnable(); // submit task to threadpool: Future longRunningTaskFuture = executorService.submit(longRunningTask); ... ... // At some point in the future, if you want to kill the task: longRunningTaskFuture.cancel(true); ... ...
Cancel method will behave differently based on your task running state, check the API for more details.
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