如何使用 AlarmManager 在 AsyncTask 中下载失败时运行重试
我使用 AlarmManager
来运行尝试从网络下载文件的服务。如果失败,我想在 5 分钟内重试该服务。
在服务内部,我运行一个 AsyncTask
来运行我的代码。据我所知,判断它是否失败的唯一方法是通过 onPostExecute()
。
再次重试该服务的最佳方法是什么?
I use an AlarmManager
to run a Service which tries to download a file from the web. If it fails I'd like to retry that Service in 5 minutes.
Inside the Service I run an AsyncTask
to run my code. As far as I know the only way I can tell if it failed or not is from the onPostExecute()
.
What is the best way of implementing a retry of that Service again?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
法尔马里的答案是正确的,我不明白你的担忧。
在
onPostExecute()
中,当您确定出现问题时:getSystemService(ALARM_SERVICE)
获取AlarmManager
set()
上的AlarmManager
会在 5 分钟内触发您如果需要,请在
PendingIntent
中的Intent
上使用额外内容,为您提供以下信息:要重试什么,或者使用自定义操作字符串来区分重试和计划的警报等。请注意,如果您使用Intent
额外功能,则需要使用PendingIntent
选择适当的标志(例如FLAG_UPDATE_CURRENT
)。所以?多个类可以与
AlarmManager
通信。另外,请随意通过其构造函数将数据传递给您的AsyncTask
子类。此外,您可能需要考虑使用
IntentService
而不是Service
和AsyncTask
。IntentService
自动为您提供后台线程。另外,当没有更多的工作要做时,它就会关闭,这也很重要,这样你就不会在市场上得到一堆一星评级来抱怨你一直运行的服务。为什么不呢?
当然。这就是你想要的。实际与
AlarmManager
对话的是Service
、AsyncTask
还是MyOtherReallyCoolClass
并不重要 - - 重新调度Service
的组件是Service
本身。Falmarri's answer is the correct one, and I do not understand your concerns.
In
onPostExecute()
, when you determine that things went awry:getSystemService(ALARM_SERVICE)
to get theAlarmManager
set()
on theAlarmManager
to trigger you in 5 minutesIf needed, use extras on the
Intent
in thePendingIntent
to give you information about what to retry, or use a custom action string to distinguish retries from the scheduled alarm, or something. Note that if you useIntent
extras, you will need to choose an appropriate flag withPendingIntent
(e.g.,FLAG_UPDATE_CURRENT
).So? Multiple classes can talk to the
AlarmManager
. Also, feel free to pass data to yourAsyncTask
subclass via its constructor.Also, you might want to consider using an
IntentService
rather than aService
andAsyncTask
.IntentService
gives you a background thread automatically. Plus, it shuts down when there is no more work to be done, which is also important, so you don't get a bunch of one-star ratings on the Market complaining about the service you keep running all of the time.Why not?
Of course. That's what you want. It matters not a whit whether the
Service
or theAsyncTask
or theMyOtherReallyCoolClass
is the one actually talking toAlarmManager
-- the component that is rescheduling theService
is theService
itself.