Android 上与 ASyncTask 同步
我正在考虑使用 ASyncTask
和 AlarmManager
在我的 Android 应用程序中实现同步。尝试对 SyncAdapter 执行相同的操作,但它只会使过程复杂化并具有其他缺点(需要 ContentProvider
,如果禁用自动,则手动同步似乎是不可能的,用户需要等)。
所以,我现在对 ASyncTask
提出的问题 - 比方说,它每 24 小时启动一次。但如果此时没有互联网连接,则不会进行同步。下次尝试将在 24 小时后再次进行。我可以做什么来避免这种情况?即,如果已经过了 24 小时,则只要出现互联网连接,就应该运行该任务。从这一刻开始算接下来的24小时。 例如,
sync 1 - day 1 12:00 (successful)
sync 2 - day 2 12:00 (failed - no internet connection)
sync 3 - day 2 20:00 (successful, internet connection appeared)
sync 4 - day 3 20:00 (successful)
相信,我可以更频繁地运行我的任务(例如,每 30 分钟)并将上次更新的时间存储在某处。或者,我可以在出现互联网连接时监听事件。最好的方法是什么?或者,是否有一些相同的标准功能?
I am thinking about implementation of synchronization in my android application with ASyncTask
and AlarmManager
. Tried to do the same with SyncAdapter
, but it just complicates the process and has other disadvantages (ContentProvider
is needed, manual sync seems to be impossible if automated is disabled, user is needed etc.).
So, the question I have now with ASyncTask
- let's say, it is started every 24 hours. But in case if there is not internet connection at this time, synchronization will not happen. Next time attempt will happen after 24 hours again. What can I do to avoid this? I.e. if 24 hours are already passed, then any time internet connection appeared, the task should be run. After this moment next 24 hours to be counted.
For ex.,
sync 1 - day 1 12:00 (successful)
sync 2 - day 2 12:00 (failed - no internet connection)
sync 3 - day 2 20:00 (successful, internet connection appeared)
sync 4 - day 3 20:00 (successful)
Believe, I can either run my task more often (for ex., each 30 minutes) and store time of last update somewhere. Or, I can listen for event when internet connection appears. What is the best approach? Or, is there some standard functionality for the same?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
当互联网连接可用时,我会使用注册的 BroadcastListener 进行同步。您可以使用 SharedPreferences 来指示此侦听器需要同步 - 因为我猜您必须在清单中注册此侦听器,我认为没有办法动态处理此问题。
这样,您就可以确保在有可用网络连接的情况下会进行同步,而 30 分钟轮询可能会错过机会。
I would go with the BroadcastListener registered to do the syncing when internet connection is available. You could use the SharedPreferences to indicate for this listener, that sync is needed - because I guess you'd have to register this listener in the manifest, I think there's no way to handle this dynamically.
This way you can be sure that sync will happen if there's net connection available, while the 30-min-polling might miss the chance.