I am making network request over TCP/IP and listening to the response on a separate thread. Each time I make a network call, I want to stop previous thread which is listening to response and make a new one.
Unfortunately, older HandlerThread is not getting terminated before starting the new one.
if (mHandler != null) {
mHandler.getLooper().quit();
}
if (mHandlerThread != null) {
mHandlerThread.interrupt();
mHandlerThread.quit();
}
mHandlerThread = new HandlerThread("socket-reader-thread");
mHandlerThread.start();
mHandler = new Handler(mHandlerThread.getLooper());
mHandler.post(() -> {
try {
String line;
while ((line = mBufferedReader.readLine()) != null) // BLOCKING CALL
{
...
}
mBufferedReader.close();
} catch (IOException e) {
e.printStackTrace();
}
});
Is there a way to terminate these HandlerThread
s?