[英]Android how to enable/disable auto sync programmatically
我需要知道如何以編程方式打開和關閉自動同步。
我想你在找
ContentResolver.setMasterSyncAutomatically(<boolean>);
什么文檔說:
設置適用於所有提供者和帳戶的主自動同步設置。 如果為false,則忽略每個提供程序的自動同步設置。
此方法要求調用者保留WRITE_SYNC_SETTINGS權限。
所以不要忘記在manifest.xml中添加權限:
<uses-permission android:name="android.permission.WRITE_SYNC_SETTINGS" />
這應該禁用/啟用所有同步。
@Sajmon:我更新了這個我認為非常有用的答案(我在我的個人項目中使用它)。
我想你想要的是以下內容:
ContentResolver.setSyncAutomatically(account, authority, true/false);
代碼同步帳戶代碼:
同步一次:
public static void syncAllAccounts(Context contextAct) throws Exception {
AccountManager manager = AccountManager.get(contextAct);
Account[] accounts = manager.getAccountsByType("com.google");
String accountName = "";
String accountType = "";
for (Account account : accounts) {
accountName = account.name;
accountType = account.type;
break;
}
Account a = new Account(accountName, accountType);
ContentResolver.requestSync(a, "com.android.calendar", new Bundle());
}
自動同步時間間隔:
public static void syncAllAccountsPeriodically(Context contextAct, long seconds) throws Exception {
AccountManager manager = AccountManager.get(contextAct);
Account[] accounts = manager.getAccountsByType("com.google");
String accountName = "";
String accountType = "";
for (Account account : accounts) {
accountName = account.name;
accountType = account.type;
break;
}
Account a = new Account(accountName, accountType);
ContentResolver.addPeriodicSync(a, "com.android.calendar", new Bundle(), seconds*1000);
}
如果要同步帳戶一次 ,請調用第一種方法,如果要在某個時間間隔內 同步 ,則必須調用第二種方法並將秒 (如10秒)作為參數傳遞。
完成
本是對的。
你需要使用
ContentResolver.setSyncAutomatically(account, authority, true/false);
你還需要添加權限“WRITE_SYNC_SETTINGS”
<uses-permission android:name="android.permission.WRITE_SYNC_SETTINGS"/>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.