Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android: How do I stop Runnable?

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!

like image 563
c0dehunter Avatar asked Feb 26 '12 22:02

c0dehunter


People also ask

How do I exit runnable?

You can call cancel() on the returned Future to stop your Runnable task. cancel attempts to cancel the execution but doesn't guarantee it.

How do you stop a thread from running on Android?

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...

What is a runnable in Android?

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 .

How do I start runnable on Android?

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.


1 Answers

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.

like image 125
yorkw Avatar answered Nov 09 '22 15:11

yorkw