Reputation: 329
I'm using HandlerThread to handle threading in Android,
public class HandlerTest extends HandlerThread {
private static final int MESSAGE_TYPE0 = 0;
private static final String TAG = "TAG";
Handler mHandler;
public interface Listener {
void onHandlerTestDone(String str);
}
@SuppressLint("HandlerLeak")
@Override
protected void onLooperPrepared() {
Log.i(TAG, "OnLoopPrep");
mHandler = new Handler() {
@Override
public void handleMessage(Message msg) {
if (msg.what == MESSAGE_TYPE0) {
@SuppressWarnings("unchecked")
String msgObj = (String) msg.obj;
handleRequest(msgObj);
}
}
};
}
private void handleRequest(final String token) {
final String str = token;
try {
this.sleep(5000, 0);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
handleMessage(token);
}
public void clearQueue() {
mHandler.removeMessages(MESSAGE_TYPE0);
}
}
I have two activities, Activity 1 calls Activity 2, then On activity 2 I do this
HandlerTest hlrtest;
protected void onCreate(Bundle savedInstanceState) {
hlrtest.start();// start looper
hlrtest.getLooper();
hlrtest.PrepMessage("test1"); //will be handled by the thread then
//the thread will go to sleep for 5 second
hlrtest.PrepMessage("test2"); //will be queued
hlrtest.PrepMessage("test3"); //will be queued
hlrtest.PrepMessage("test4"); //will be queued
//Now quit this activity and go back to Activity 1
@Override
public void onDestroy() {
super.onDestroy();
hlrtest.clearQueue();
hlrtest.quit();
}
}
As you can see I make the thread sleep for 5 seconds to simulate that it's getting busy for that amount of time. when I send 4 requests and then I go back to Activity 1 the thread will handle only the first request and the queue will get cleared and the thread will exit as onDestroy() will do that after going back to Activity 1.
If I don't call clearQueue() and quit() in the destroy I will end up with a zombie thread.
How can I send many requests to the thread and I want the thread to handle them all and then quit when the queue is empty?
please note that I don't want to use quitSafely() as it's only supported from sdk 18 and above
Upvotes: 1
Views: 447
Reputation: 8371
You could create another message type that signals the Handler to clean up and quit. Perhaps something like this (untested) code for handleMessage()
:
@Override
public void handleMessage(Message msg) {
if (msg.what == MESSAGE_TYPE0) {
@SuppressWarnings("unchecked")
String msgObj = (String) msg.obj;
handleRequest(msgObj);
} else if (msg.what == MESSAGE_TYPE_FINISH) {
mHandler.clearQueue();
mHandler.quit();
}
};
Upvotes: 1