2

I have an application which uses a separate thread to execute a calculation performed in code from a separate library. I would like the user to able to cancel this operation as, depending on the parameters, it can take a long time.

I cannot use a stopping variable or check for interrupts as the calculation from the applications point of view is a single line

public void run() {
    result = library.performCalculation(params);
}

I would like to be able to use thread.stop() but as far as I'm aware this is not posible on android.

Is there anyway I can cause the thread to stop running?

1

2 Answers 2

1

You're correct, Thread.stop() is not available on Android (and even on systems where it is still supported, its problems outweight its usefulness).

What you can do is two-fold. First, call thread.interrupt() to set an interrupted flag on the thread running your library. Second, modify your library at appropriate point(s) to call isInterrupted() to determine if it is interrupted and, if so, it should voluntarily clean up and leave.

1
  • Thank you very much. I was hoping that I wouldn't have to modify the library, it wasn't exactly built with this in mind. In the places that I have implemented the isInterrupted() check though it's working well.
    – Ryan
    Aug 28, 2012 at 20:39
0

An AsyncTask can be Cancelled. Put that into an AsyncTask and call

 AsyncTask.cancel(true);
1
  • 1
    Like the thread.interrupt() call in my answer, AsyncTask.cancel() does not stop the thread, it only sets a flag. The thread must still check the flag and decide what to do if its doInBackground() method is still busy.
    – mah
    Aug 28, 2012 at 20:14

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.