如何终止HandlerThreads?

时间:2011-03-22 12:19:09

标签: android multithreading

按照Googles使用服务的示例,我创建了几个这样的线程。我不能使用IntentService,因为我正在做一些涉及等待回调的事情。

但是,我不知道如何终止以这种方式启动的Thread。据我了解,Threads会在run()方法返回时自动终止。但是,这种线程没有run方法。我的线程正在泄漏 - 它们在stopSelf()之后仍然存活。

@Override
public void onCreate() {

    HandlerThread thread = new HandlerThread("ServiceStartArguments",
            android.os.Process.THREAD_PRIORITY_BACKGROUND);
    thread.start();
    HandlerThread thread2 = new HandlerThread("CallbackHandling",
            android.os.Process.THREAD_PRIORITY_BACKGROUND);
    thread2.start();

    mServiceLooper = thread.getLooper();
    mCallbackLooper = thread2.getLooper();
    mServiceHandler = new MyHandler(mServiceLooper);
    mCallbackHandler = new Handler(mCallbackLooper);
}

@Override
public int onStartCommand(Intent intent, int flags, int startId) {
    Toast.makeText(this, "service starting", Toast.LENGTH_SHORT).show();

    // For each start request, send a message to start a job and deliver the
    // start ID so we know which request we're stopping when we finish the job
    Message msg = mServiceHandler.obtainMessage();
    msg.arg1 = startId;
    mServiceHandler.sendMessage(msg);
    mMainThreadHandler=new Handler();
    // If we get killed, after returning from here, restart
    return START_STICKY;
}

private final class MyHandler extends Handler {
    public MyHandler(Looper looper) {
        super(looper);
    }
    @Override
    public void handleMessage(Message msg) {
        cycle();


        // Stop the service using the startId, so that we don't stop
        // the service in the middle of handling another job
        stopSelf(msg.arg1);
    }
}

protected void cycle() {
    ...
    mCallbackHandler.post(new Runnable(){
        public void run(){
            goAskForSomeCallbacks();
        }
    });

    try {
        Thread.sleep(GIVE_UP_TIME);
    } catch (InterruptedException e){
        //The callback will interrupt this thread to stop it from waiting
        Log.d(TAG,"Got early callback, stop waiting.");
    }
    Thread.interrupted(); //clear the interrupt
    doStuff(); 

}

4 个答案:

答案 0 :(得分:16)

尝试在相应的Loopers上调用quit方法。

答案 1 :(得分:1)

您可以在处理程序线程上调用quit方法。

e.g。

thread.quit();
thread2.quit();

答案 2 :(得分:0)

您还可以使用以下推荐方法:

但是在使用它之前要小心,因为它会取消所有待处理的作业

handler.quitSafely();

答案 3 :(得分:-1)

强制关闭应用程序会这样做,但除此之外他们只是继续自行。