如何终止 HandlerThreads?

发布于 2024-10-24 19:25:59 字数 2088 浏览 2 评论 0原文

按照 Google 使用服务的示例,我创建了几个这样的线程。我无法使用 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(); 

}

Following Googles examples for using a Service, I created a couple of threads like this. I can't use IntentService, because I'm doing something that involves waiting for callbacks.

However, I don't know how to terminate a Thread started in this manner. As I understand it, Threads automatically terminate when the run() method returns. However, this kind of thread doesn't have a run method. My Threads are leaking--they stay alive after 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(); 

}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

多情出卖 2024-10-31 19:25:59

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

Try calling the quit method on the corresponding Loopers.

欢烬 2024-10-31 19:25:59

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

例如

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

You can call quit method on your handler threads.

e.g.

thread.quit();
thread2.quit();
黑寡妇 2024-10-31 19:25:59

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

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

handler.quitSafely();

You can also use the following recommended approach:

but be careful before using it because it cancels all pending jobs

handler.quitSafely();
万劫不复 2024-10-31 19:25:59

强制关闭应用程序可以做到这一点,但除此之外它们只是继续自己运行。

Force closing the app does it but otherwise they just keep going on their own.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文