概述
我在使用SyncAdapter而不使用ContentProvider,Authenticator ..等时使用Google's tutorial。当我需要通过de SyncAdapter“上传”到服务器时,我调用onPerformSync(...)
时效果很好。
现在,你可以想象,我也需要从服务器上下载(是的,我知道使用Google的Cloud Messaing系统会更好,但这是我给出的设置,我可以'改变那个)。为此,我想利用“网络痒”Android系统在有网络可用的情况下进行定期同步。为此我说明如下:
ContentResolver.setIsSyncable(accounts[0], AUTHORITY, 1);
ContentResolver.setSyncAutomatically(accounts[0], AUTHORITY, true);
但是我的SyncAdapter 没有被调用。查看其他stackOverFlow问题,如果使用SyncAdapter定位API 10或更低版本似乎存在问题,并且您必须在调用before方法之前明确地添加帐户。所以我最终得到了这个:
AccountManager accountManager = (AccountManager) context.getSystemService(ACCOUNT_SERVICE);
Account[] accounts = accountManager.getAccounts();
if(accounts.length == 0){ //ADD DUMMY ACCOUNT
Account newAccount = new Account(ACCOUNT, ACCOUNT_TYPE);
ContentResolver.setIsSyncable(accounts[0], AUTHORITY, 1);
ContentResolver.setSyncAutomatically(accounts[0], AUTHORITY, true);
accountManager.addAccountExplicitly(newAccount, null, null);
}else{
accounts = accountManager.getAccounts();
ContentResolver.setIsSyncable(accounts[0], AUTHORITY, 1);
ContentResolver.setSyncAutomatically(accounts[0], AUTHORITY, true);
}
现在,当用户登录时,或者应用程序被杀死并再次启动时,此代码将被执行。我想知道,我是否应该在第一次添加dummyAccount时调用setIsSyncable
和setSyncAutomatically
?
此外,SyncAdapter的“良好”部分是它会在发生异常时继续进行调用。但我不太明白这是怎么回事,所以相反,我有这个:
private void profileUpdate(){
TableAccounts db = TableAccounts.getInstance(getContext());
boolean isRecordDirty = db.isRecordDirty(signedInUser);
if(isRecordDirty){
if(server.upDateUserProfile(signedInUser)){
db.cleanDirtyRecord(signedInUser);
turnOffPeriodicSync();
}else{
this.turnOnPeriodicSync(this.sync_bundle);
}
}else
turnOffPeriodicSync();
}
如您所见,根据我上传到服务器的结果,我打开或关闭定期同步。
答案 0 :(得分:0)
由于accountManager.getAccounts []会返回设备上的每个帐户,因此我认为无法保证帐户[0]是您应用的帐户(也就是说,您的包名称为ACCOUNT_TYPE)。 - 你可以在任何情况下调用addAccountExplicitly(),如果它存在,那么没有任何反应。
Account account = new Account(ACCOUNT, ACCOUNT_TYPE);
AccountManager accountManager = (AccountManager) context.getSystemService(Context.ACCOUNT_SERVICE);
accountManager.addAccountExplicitly(account, null, null)
context.getContentResolver().setSyncAutomatically(account, AUTHORITY, true);
答案 1 :(得分:0)
Disclaimer: I might be mistaken.
On top everything you did, you also have to call ContentResolver.requestSync() from within your app every time you need a sync to run. The sync will not run immediately though, because Android is trying to cluster network activity.
Or you can use Googles Cloud Messaging API to request a sync, but I don't know a whole lot about that.