android - 停止处理程序线程
问题描述
在我们的一个应用程序中,我们使用带有通知的后台服务(基本上是前台服务,但您明白了,当服务保持活动状态时,活动是可关闭的。)
在此服务上,我们使用 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);
}
}
}
解决方案
推荐阅读
- python - 使用 f2py 将锯齿状数组传递给 Fortran
- javascript - 如何将 /Date(1606867200000)/ 这样的日期转换为 dd/MM/yyyy 格式的字符串
- java - 如何在 Apache Jena 中将 TriG 文件解析为 RDF 模型?
- python - 在 DataFrame 中仅移动一列
- flutter - Flutter 为什么futureBuilder 认为null firestore 文档不为null?
- c# - 如何加入拆分为多个 TCP/IP 数据包的大量数据
- html - 如何在 google cdn 中设置缓存规则
- android - 是否可以在一个应用程序中使用多个自定义身份验证器?
- python - 在 Pandas 中,出现重复的列,名称后附加“.1”
- reactjs - React 功能组件是否应该始终显示 console.log 这意味着它正在重新渲染?