Should I manually close HandlerThreads created by my application when destroying the activity?

Daniel L. picture Daniel L. · Feb 18, 2013 · Viewed 9.5k times · Source

My app is composed of a single Activity. In this activity, I'm creating multiple HandlerThreads which run in a loop to do socket blocking operations.

Currently I post a quit message to everyone of these HandlerThreads during my Activity.onDestroy().

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

My question is: What is the right way to close HandlerThread when I close my app? (Note that those threads might be blocking on a socket operation).

EDIT: More information: I have a pool of Handler Threads which is initiated in onCreate (No problem when I'm launching my app at the first time).

Each handler runnable loop is wrapped with an

 if (shouldRun) {
//body
} 
else { 
 close();
}

statement.

the close method remove all pending messages and runnables and post a message to the handler that will cause him to call its looper.quit(). This way, if the current handler thread is blocked by IO operation, only once it will finish it he will quit().

Answer

Andy McSherry picture Andy McSherry · Feb 18, 2013

Yes, it would be a good idea to close it. Also make sure to remove your callbacks.

@Override
public void onDestroy() {
    super.onDestroy();
    handler.removeCallbacksAndMessages(null);
    handler.getLooper().quit();
}