连接恢复后,同步适配器仅运行一次

时间:2018-01-08 15:31:44

标签: android android-syncadapter

我试图实施SyncAdapter,它几​​乎正确地工作,就像我想要的那样。  唯一的问题是当用户离线并且调用周期性同步时(例如:10次),当用户恢复互联网连接时,同步适配器调用将重复10次:

按钮按下时如何调用它:

val bundle = Bundle()
bundle.putBoolean(ContentResolver.SYNC_EXTRAS_MANUAL, true);
bundle.putBoolean(ContentResolver.SYNC_EXTRAS_EXPEDITED, true);
bundle.putString(SYNC_TRIGGER_SOURCE, SyncManager.FROM_SYNC_CLICK);
ContentResolver.requestSync(account, AUTHORITY_PONTOTEL, bundle);

如果用户将其连接更改为离线,则单击按钮293879878923792387次,当他将连接重新设置为联机时,它将调用服务器293879878923792387(x 50000用户,服务器将被ddosed; |)

有没有办法在不锁定按钮的情况下避免这种情况?

有没有办法清除同步队列并只保留最后一个?

1 个答案:

答案 0 :(得分:0)

Is there a way to CLEAR the sync queue and keep only the last one?

Actually, this should be the default behavior. Provided that you request the sync with the same arguments and for the same account, it will cancel any previously queued syncs before queuing the new request, or not queue it at all if there is a sync with the same arguments already running. (if you'd like to have a look yourself, you can check the source code of SyncManager, where they will compare keys and bundles to remove duplicates)

This said, I would advise you to make sure to verify how and where you request a sync. If you use the same account and add the same arguments to your Bundle, then it should only run one sync, ignoring further requests with the same payload.

It might be that SYNC_EXTRAS_EXPEDITED overrides the mentioned behavior in some way, so I'd try to run your code without the flag and see if that fixes it, although I don't see any signs of this in the SDK 26 source code.

And as a last resort you could use cancelSync to cancel all syncs for an Account, but I don't believe that this will be necessary.