简体   繁体   English

在Android上与ASyncTask同步

[英]Synchronization with ASyncTask on android

I am thinking about implementation of synchronization in my android application with ASyncTask and AlarmManager . 我正在考虑在我的android应用程序中使用ASyncTaskAlarmManager实现同步。 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.). 试图对SyncAdapter进行同样的操作,但它只会使过程复杂化,并具有其他缺点(需要ContentProvider ,如果禁用了自动功能,需要用户等,则似乎无法进行手动同步)。

So, the question I have now with ASyncTask - let's say, it is started every 24 hours. 因此,我现在对ASyncTask提出的问题-假设它每24小时启动一次。 But in case if there is not internet connection at this time, synchronization will not happen. 但是如果此时没有Internet连接,则不会发生同步。 Next time attempt will happen after 24 hours again. 下次尝试将在24小时后再次发生。 What can I do to avoid this? 我该怎么做才能避免这种情况? Ie if 24 hours are already passed, then any time internet connection appeared, the task should be run. 即,如果已经过了24小时,那么只要出现Internet连接,就应该运行该任务。 After this moment next 24 hours to be counted. 此刻过后,接下来的24小时将被计数。 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. 相信,我可以更频繁地运行任务(例如,每30分钟运行一次),并将上次更新的时间存储在某个地方。 Or, I can listen for event when internet connection appears. 或者,当出现互联网连接时,我可以监听事件。 What is the best approach? 最好的方法是什么? Or, is there some standard functionality for the same? 或者,是否有一些相同的标准功能?

I would go with the BroadcastListener registered to do the syncing when internet connection is available. 当互联网连接可用时,我会去注册BroadcastListener以进行同步。 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. 您可以使用SharedPreferences指示此侦听器是否需要同步-因为我想您必须在清单中注册此侦听器,所以我认为没有办法动态处理此侦听器。

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. 这样,您可以确定如果有可用的网络连接,则将发生同步,而30分钟的轮询可能会错过机会。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM