title: Should I manually close HandlerThreads created by my application when destroying the activity?
body: <p>My app is composed of a single <code>Activity</code>. In this activity, I'm creating multiple <code>HandlerThread</code>s which run in a loop to do socket blocking operations.</p>
  
  <p>Currently I post a quit message to everyone of these <code>HandlerThread</code>s during my <code>Activity.onDestroy()</code>.</p>
  
  <p>Sometimes, when I open my app, close it and relaunch it, it crashes (many time due to posting a message to a handler thread which is not running).</p>
  
  <p>My question is: <em>What is the right way to close <code>HandlerThread</code> when I close my app?</em> (Note that those threads might be blocking on a socket operation).</p>
  
  <p><strong>EDIT: More information:</strong>
  I have a pool of Handler Threads which is initiated in onCreate (No problem when I'm launching my app at the first time).</p>
  
  <p>Each handler runnable loop is wrapped with an </p>
  
  <pre><code> if (shouldRun) {
  //body
  } 
  else { 
   close();
  }
  </code></pre>
  
  <p>statement.</p>
  
  <p>the close method remove all pending messages and runnables and post a message to the handler that will cause him to call its <code>looper.quit()</code>.
  This way, if the current handler thread is blocked by IO operation, only once it will finish it he will quit().</p>