Adam,

interrupt() doesn't necessarily stop a thread right then and there. It sets an internal flag, which can be checked with isInterrupted(). If your thread happens to call wait() or sleep(), then this flag will be turned into an InterruptedException. Also this flag is reset after isInterrupted() returns true.

Given this, it might be better to implement your own flag that tells the thread that it should stop what it's doing and exit.

However, if the thread is inside a network call, it might not see the flag for a while. So one other fix is needed - add code to your thread (such as setting the handler to null) that tells it that the UI has gone away, and that it shouldn't try to update it.

You could also use AsyncTask rather than rolling your own thread, which has a method to cancel. Note however that prior to 2.2., this method has a race condition, and may occasionally not work properly.

-- Kostya

02.02.2011 14:07, Serdel пишет:
In my application I am connecting to a server and downloading some
things. Not much but the connection it self takes a while. Off course
this is done in a thread (class that implements runnable). If some
error occurs, the thread sends a message to the UI using a Handler and
the UI displays an dialog window.

My problem is that I can't stop the thread in the UI properly. For
example if during the connection I would press the 'home' button on
the phone, after some seconds I get an error saying that my
application couldn't create a dialog window (because it is not running
anymore). That means that my thread was not stopped and kept on
working until an error (i.e. timeout) occurred and tried to send a
massege to the UI by a handler.

to Stop the thread I have a function that I found:

                  public synchronized Thread stopThread(Thread thr){
                          if(thr != null){
                            Thread temp = thr;
                          thr = null;
                            temp.interrupt();
                          }
                          return thr;
                        }

And I use it like:

@Override
         public void onDestroy()
            {
                super.onDestroy();
               senderTh= stopThread(senderTh);
               finish();
            }

Why this doesn't stop my Thread? How can I do it from the UI?



--
Kostya Vasilyev -- WiFi Manager + pretty widget -- http://kmansoft.wordpress.com

--
You received this message because you are subscribed to the Google
Groups "Android Developers" group.
To post to this group, send email to [email protected]
To unsubscribe from this group, send email to
[email protected]
For more options, visit this group at
http://groups.google.com/group/android-developers?hl=en

Reply via email to