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

标签 java android service android-asynctask alarmmanager

我使用 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/

相关文章:

Java collections.Shuffle 只洗牌一次

java - Intellij 需要很长时间才能执行 JUnit 测试的 Maven 目标

android - Ionic 应用程序适用于 Android,但不适用于 IOS

authentication - Azure 移动服务/身份验证

javascript - 如何在 JavaScript 中强制等待 REST Api

java - intern() 方法对性能有影响吗?

c# - 如何使用 iText 创建多份文档

android - Intent 打开选项卡式 Activity 的特定选项卡

android - 我如何解决 R.layout.main 无法在我的 android 应用程序中解析?

安卓下载服务:getting empty file