gpt4 book ai didi

java - 如何使用 AlarmManager 在 AsyncTask 中下载失败时重试

转载 作者:行者123 更新时间:2023-11-29 06:19:34 25 4
gpt4 key购买 nike

我使用 AlarmManager 来运行尝试从 Web 下载文件的服务。如果失败,我想在 5 分钟后重试该服务。

在服务内部,我运行一个 AsyncTask 来运行我的代码。据我所知,我可以判断它是否失败的唯一方法是来自 onPostExecute()

再次重试该服务的最佳方式是什么?

最佳答案

Falmarri 的回答是正确的,我不理解你的顾虑。

onPostExecute() 中,当您确定出现问题时:

  1. 调用getSystemService(ALARM_SERVICE)获取AlarmManager
  2. AlarmManager 上调用 set() 以在 5 分钟内触发您

如果需要,在 PendingIntent 中的 Intent 上使用 extras 来为您提供有关重试内容的信息,或者使用自定义操作字符串来区分重试和计划的警报, 或者其他的东西。请注意,如果您使用 Intent extra,您将需要选择一个带有 PendingIntent 的适当标志(例如,FLAG_UPDATE_CURRENT)。

The problem is the AlarmManager is started from one class but the AsyncTask is in another class, therefore the class that starts the AlarmManager doesn't know whether it has failed or not.

所以呢?多个类可以与 AlarmManager 对话。此外,您可以随意通过其构造函数将数据传递给您的 AsyncTask 子类。

此外,您可能需要考虑使用 IntentService 而不是 ServiceAsyncTaskIntentService 自动为您提供后台线程。此外,它会在没有更多工作要做时关闭,这也很重要,因此您不会在市场上获得一堆一星评级来提示您一直在运行的服务。

I don't want to start an AlarmManager from the onPostExecute() of my Service class.

为什么不呢?

If I start an AlarmManager from within the Service then I'm sort of creating a recurring function where I'm calling the Service from itself.

当然。那就是你想要的。 ServiceAsyncTaskMyOtherReallyCoolClass 是否真正与 AlarmManager 对话并不重要 - - 重新安排 Service 的组件是 Service 本身。

关于java - 如何使用 AlarmManager 在 AsyncTask 中下载失败时重试,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3693672/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com