Android定时任务(相当于cronjob)
上次(由不同的用户)提出这个问题时,答案是:
如果这是在正在运行的活动中,您可以使用 Timer/TimerTask 和 Handler,或者可以使用 postDelayed() 和 AsyncTask。
这里: Android 重复任务
我仍在学习如何对 android 进行编程。我已经了解了我所知道的技能,包括线程,并且我的代码遇到了许多问题。任何人都可以举一个如何使用的示例:time/timertask 和处理程序或 postDelayed() 和 AsyncTask。
The last time this question was asked (by a different user), the answer response was:
If this is in a running activity, you could use Timer/TimerTask and a Handler, or you could use postDelayed() and an AsyncTask.
Here: Android Repetitive Task
I am still learning how to program android. I have gone through the skills I do know including threads and had many issues with my code. Can anyone give an example of how to use: time/timertask and handler OR postDelayed() and AsyncTask.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
对于类似 Cron 的任务,您必须使用 AlarmManager,这是一个系统服务,要在代码中使用它,您需要调用:
有关 AlarmManager 的完整文档 此处。
For Cron like tasks you have to use AlarmManager, this is a system service, for using it in your code you need to call:
Full docs about AlarmManager here.
最合适的方法是通过服务。我通过查看 Android 附带的电子邮件应用程序的源代码,了解了如何编写服务。
总体思路是重写 Service 类,并设置 < a href="http://developer.android.com/reference/android/app/AlarmManager.html" rel="noreferrer">警报来激活您的服务。与守护进程和 Windows 服务不同,Android 服务并不总是运行 - 它们会启动(通常在由警报激活时)、执行工作,然后关闭。在某些情况下,您可能需要获取部分唤醒锁以保持服务将持续运行直至完成任务 - 否则,Android 可能会过早终止您的服务。
The most suitable approach is through services. I learned how to write services by looking at the source code for the stock Email app that is included with Android.
The general idea is that you override the Service class, and set up alarms to activate your service. Unlike daemons and Windows services, Android services aren't always running - they start up (usually when activated by an alarm), perform work, then shut down. In some cases, you may need to acquire a partial wake lock to keep the service going until it completes the task - otherwise, Android may kill your service prematurely.
如果你想构建一个 cronjob 运行程序,那么你想要的是一个 服务:
If you want to build a cronjob runner then what you want is a Service: