MonoDroid定时器
如果我按照本文描述的方式设置计时器,我不确定有几个事物。我知道我的第二个问题可能有也可能没有明确的答案,所以如果我的第一个问题能够得到解决,我会接受作为答案。
1)如果计时器由一个活动启动,并设置为每 5 分钟运行一次,直到被告知停止,该活动完成或被用户更改活动发送到后台是否会影响它?我有一次使用计时器似乎非常断断续续,不知道这是我做错的事情还是只是计时器的固有问题。
2)我看到有些人说即使是android也不建议使用定时器。我已经看到了 postDelayed() 的建议,但正如我引用的文章中所解释的,对于需要每 X 分钟重复一次的任务,这可能会出现问题。我是否缺少更可取的选择?
基本上,我会在将信息同步回服务器之前检查与互联网的连接。如果设备未连接,我想启动一个计时器来检查连接情况,并尝试每 5 或 10 分钟运行一次我的同步方法,直到成功为止,此时计时器可以停止。该计时器需要能够从任何活动开始,每 5 或 10 分钟继续运行一次,无论当前正在使用什么活动,并且可以从任何活动取消。
If I set up a timer in the way that this article describes, I am unsure of a couple things. I understand my 2nd question may or may not have a definite answer, so I will accept as the answer if my first question can be addressed.
1) If the timer is begun by one activity and is set to run every 5 minutes until told to stop, does that activity finishing or being sent to the background by the user changing activities affect it? The one time I've used a timer seemed VERY intermittent and don't know if it is something I did wrong or just an inherent issue with timers.
2) I've seen a few people say that even android doesn't recommend using timers. I've seen the recommendation for postDelayed(), but as explained in the article I referenced, for tasks that need to be repeated every X minutes, that can be problematic. Is there a more preferable option that I am missing?
Basically, I am checking for connectivity to internet before syncing information back to the server. If the device is not connected, I want to start a timer that checks for connectivity and attempts to run my Sync method every 5 or 10 minutes until successful at which point the timer can stop. This timer needs to be able to start from any activity, continue running every 5 or 10 minutes regardless of what activity is currently being used and be cancel-able from any activity.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
看看 TinyIoC/TinyMessenger。
我做了与您所描述的类似的事情:
如果您启动一个新线程,一个实现计时器的服务,您可以从任何地方启动/停止/暂停它,并且您可以接收它广播的任何消息(完成/错误等)。
您只需要小心,您明确如果回调需要为用户写入消息,则在 UI 线程上运行。
当您停止服务时,如果您有对其运行的线程的引用,则只需广播服务的停止消息并调用 join() 即可。
希望有帮助。
Take a look at TinyIoC/TinyMessenger.
I do a similar thing to what you're describing by:
If you kick off on a new thread, a service that implements a timer, you can start/stop/pause it from anywhere and you can receive any messages it broadcasts (completion/error etc.)
You just to have be careful that you explicitly run on the UI thread, if the callbacks need to write messages for the user.
When you stop the service, if you have a reference to the thread it runs on, you just broadcast the service's stop message and call join().
Hope that helps.