Android HandlerThread类

时间:2014-08-23 21:19:30

标签: android android-handler

我正在使用HandlerThread来处理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);
    }
}

我有两个活动,活动1调用活动2,然后在活动2上调用

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();
        }
}

正如你所看到的,我让线程休眠了5秒,以模拟它在这段时间内忙碌。当我发送4个请求然后我回到活动1时,线程将只处理第一个请求,队列将被清除,线程将退出,因为onDestroy()将在返回活动1后执行此操作。

如果我不在destroy中调用clearQueue()和quit(),我将以僵尸线程结束。

如何向线程发送许多请求,我希望线程处理它们,然后在队列为空时退出?

请注意我不想使用quitSafely(),因为它只支持sdk 18及以上版本

1 个答案:

答案 0 :(得分:1)

您可以创建另一个消息类型,指示处理程序清理并退出。也许类似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();                
    }
};