首页 > 解决方案 > 停止处理程序线程

问题描述

在我们的一个应用程序中,我们使用带有通知的后台服务(基本上是前台服务,但您明白了,当服务保持活动状态时,活动是可关闭的。)

在此服务上,我们使用 3 个单独HandlerThreads的 withHandlers来管理各种延迟(例如,250 毫秒)的操作。现在,如果屏幕关闭,则需要停止这些操作,如果屏幕重新打开,则需要恢复这些操作,由于这种情况,我们向服务添加了广播接收器,并创建了删除线程。到目前为止一切正常。

为了停止操作,我们通过调用删除了处理程序上的消息Handler.removeCallbacksAndMessages(null),它实际上清除了消息队列。但是,处理程序线程保持活动状态。这是一个问题。

为了停止我们使用的线程,我们认为它会在HandlerThread.quit()内部调用Looper.quit()它,它会完成线程,但不,先生,它不会删除线程,因为我们从 Fabric 获得了一些报告pthread_create failed (1040kb stack), try again或者其他什么。在它下面,有 940 个单独的线程命名相同,这导致了 OOM(Out Of Memory)错误。这是我们犯下的一个巨大错误。

问题:我们如何停止处理程序线程?HandlerThread.interrupt()会够吗?任何帮助表示赞赏,谢谢。PS:我不能分享任何源代码,在这种情况下我认为没有必要,因为问题本身是不言自明的。

编辑:由于您要求提供一些代码,因此我将展示我正在遵循的一些逻辑的示例。

public class ThreadHelper implements Runnable
{

    private HandlerThread handlerThread = new HandlerThread("ThreadName");
    private Handler handler;

    private boolean shouldRun = true;

    public ThreadHelper()
    {
        handlerThread.start();
        startThread();
    }

    // Called if the screen state is turned on.
    public void startThread()
    {
        if (handlerThread == null)
        {
             handlerThread = new HandlerThread("ThreadName");
             handlerThread.start();
        }
        if (handler == null)
        {
             handler = new Handler(handlerThread.getLooper());
             handler.post(this);
        }
    }

    // Called if the screen state is turned off.
    public void stopThread()
    {
        shouldRun = false;
        handler.removeCallbacksAndMessages(null);
        handlerThread.quit();
        try
        {
            handlerThread.interrupt();
        }
        catch (Exception ignored)
        {
            // Skipped Thread.currentThread().interrupt() check here since this is
            // called from a different thread that is not associated.
        }

        // remove variables.
        handler = null;
        handlerThread = null;
    }

    @Override
    public void run()
    {
        if (shouldRun)
        {
            // rest of the code without having a long-running
            // operation. Mostly ends in 1~2 millseconds.

            // Continue looping.
            handler.postDelayed(this, 250); 
        }
    }
}

标签: androidmultithreadingandroid-service

解决方案


推荐阅读