cornelyus cornelyus - 1 year ago 103
Android Question

Android , exiting / pausing application, how to destroy thread

I have an android application with a background thread that contains a socket connection for sending/receiving data from a server.

If my application ends (back button, etc) or is paused (Home button, calling other app), what is the best way of dealing with this background thread?

I have seen 2 ways:

  • Call
    after creation and before starting the thread

  • Override
    , or

I just want to ensure that my application doesn't hang or have other strange behavior.


Also, what's the best solution to close the socket? Do I close it and the inputStream as well? Is that enough?

Answer Source

I'd suggest using a signal variable of some sort: doing something like

public void run(){
  // do work

// clean up


And then in onStop() or onDestroy() set stopped to true. You'll need to make sure you clean up behind yourself as well, and if you need to re-start the thread you do so in onResume or onCreate.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download