如何终止HandlerThreads?

9
按照Google关于使用Service的示例,我创建了几个类似于这样的线程。因为我正在等待回调,所以无法使用IntentService。
但是,我不知道如何终止以这种方式启动的线程。据我了解,当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(); 

}

我不明白为什么使用回调会阻止您使用IntentService。我希望“等待回调”在这里并不意味着忙等待。如果是的话,那么我建议重新设计。如果不是,那么没有理由保留单独的HandlerThread和每个预期回调的基础。即使涉及到对回调提供的数据进行大量后处理,也可能明智地为此设置队列等。因此,了解您心中的架构将是很好的。 - class stacker
4个回答

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

2
@TenFour04,您能发布最终解决方案吗? - eros

1
你可以使用以下推荐的方法:
但在使用之前要小心,因为它会取消所有待处理的任务。
handler.quitSafely();

1
你可以在处理程序线程上调用quit()方法。
例如:
thread.quit();
thread2.quit();

-1

强制关闭应用程序可以解决问题,但否则它们会继续自行运行。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接