2011-02-28 104 views

回答

4

我想你想要的是以下几点:

ContentResolver.setSyncAutomatically(account, authority, true/false); 
22

我认为你正在寻找

ContentResolver.setMasterSyncAutomatically(<boolean>); 

什么文件说:

设置主自动同步设置适用于所有提供商 和帐户。如果这是错误的,那么每个提供程序自动同步设置 将被忽略。

此方法要求主叫方拥有权限 WRITE_SYNC_SETTINGS。

所以不要忘记添加到许可的manifest.xml:

<uses-permission android:name="android.permission.WRITE_SYNC_SETTINGS" /> 

这应该禁用/启用所有同步。


@Sajmon:我更新了这个我认为非常有用的答案(我在我的个人项目中使用这个)。

+1

+1我编辑并更新了您的答案。现在我认为这个事情更清楚了。 – Sajmon

+0

是否可以从亚行做到? –

0

本是正确的。

您需要使用

ContentResolver.setSyncAutomatically(account, authority, true/false); 

您还需要添加许可 “WRITE_SYNC_SETTINGS”

<uses-permission android:name="android.permission.WRITE_SYNC_SETTINGS"/> 
+0

有什么办法可以防止用户通过设置屏幕禁用同步,所以同步将始终执行 – KJEjava48

3

代码同步帐户编程:

同步一次:

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秒)为论据

完成

相关问题