如何在固定时间间隔后重复执行异步任务
如何使异步任务在一段时间间隔后重复执行,就像计时器一样...实际上,我正在开发一个应用程序,它将自动从服务器下载所有最新的未读问候语,为此目的,我必须在经过一些修复后检查服务器的更新时间间隔....我知道这可以通过计时器轻松完成,但我想使用异步任务,我认为这对于 Android 应用程序更有效。
How to make Async task execute repeatedly after some time interval just like Timer...Actually I am developing an application that will download automatically all the latest unread greeting from the server and for that purpose I have to check for updates from server after some fixed time intervals....I know that can be easily done through timer but I want to use async task which I think is more efficient for android applications.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
你可以只是一个处理程序:
但我建议你检查这个框架:http: //code.google.com/intl/de-DE/android/c2dm/ 是一种不同的方法:服务器会在准备就绪时通知手机(从而节省一些带宽和性能:))
You can just a handler:
But I would recommend you to check this framework: http://code.google.com/intl/de-DE/android/c2dm/ Is a different approach: the server will notify the phone when something is ready (thus, saving some bandwidth and performance:))
创建服务并通过警报管理器安排它不是更有效吗?
wouldn't it be more efficient to create a service and schedule it via Alarm Manager?
接受的答案是有问题的。
使用 TimerTask() 通过处理程序激活异步任务是一个坏主意。在方向改变时,您必须记住同时取消计时器和处理程序调用。如果不是,它将在每次轮换时一次又一次地调用异步任务。
它将导致应用程序炸毁服务器(如果这是剩余的 http get 请求)而不是 X 次 - 最终调用将是每秒实例多次调用。 (因为根据屏幕旋转次数会有很多计时器)。如果后台线程中运行的活动和任务很重,它可能会破坏应用程序。
如果您使用计时器,则将其设为类 memebr 并取消它 onStop():
相反,请尝试避免异步任务,如果您必须使用调度程序服务来运行异步任务。或应用程序类,例如这个好主意:
https://fattybeagle.com /2011/02/15/android-asynctasks-during-a-screen-rotation-part-ii/
或者使用简单的处理程序(没有计时器,只需使用postDelayed),另外一个好的做法是调用 onStop() 取消异步任务。这段代码使用 postDelayed 可以正常工作:
The accepted answer is problematic.
Using TimerTask() for activating async task via handler is a bad idea. on orientation change you must remember to cancel also the timer and the handler calls. if not it will call the async task again and again on each rotation.
It will cause the application to blow up the server (if this is rest http get request) instead of X time - eventually the calls will be instance many calls on each second. (because there will be many timers according to the number of screen rotations). It might crush the application if the activity and the task running in background thread are heavy.
if you use the timer then make it a class memebr and cancel it onStop():
Instead try to avoid async task, and if you must then use scheduler service to run the async task. or the application class such as in this nice idea:
https://fattybeagle.com/2011/02/15/android-asynctasks-during-a-screen-rotation-part-ii/
Or use simple handler (without the timer, just use postDelayed) and also good practive is to call cancel the async task onStop(). this code works fine using postDelayed: