Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android how to enable/disable auto sync programmatically

Tags:

android

sync

I need to know how to toggle auto sync on and off programmatically.

like image 953
Blake Avatar asked Feb 28 '11 04:02

Blake


People also ask

Do I want auto sync on or off?

If you leave auto-sync on, you may find your Android device running low on battery power much quicker than you want. So it's best to turn it off unless you really need it.

What is sync automatically?

With auto-sync, you no longer have to transfer data manually, saving you time and making sure that essential data is backed up to another device. The Gmail app syncs data automatically into data clouds so you can access information off of any device at any time.


2 Answers

I think you are looking for

ContentResolver.setMasterSyncAutomatically(<boolean>);

What docs says:

Sets the master auto-sync setting that applies to all the providers and accounts. If this is false then the per-provider auto-sync setting is ignored.

This method requires the caller to hold the permission WRITE_SYNC_SETTINGS.

So don't forget to add permission into manifest.xml:

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

This should disable / enable all the syncs.


@Sajmon: I updated this i think very useful answer (i'm using this in my personal project).

like image 188
kingston Avatar answered Oct 04 '22 22:10

kingston


Code for Sync Accounts Programmatically:

Sync once:

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());
}

Sync on time interval automatically:

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);
}

If you want to sync accounts once, call first method and if you want to sync on some time of interval you have to call second method and pass seconds (Like 10 Seconds) as arguments in it.

Done

like image 23
Hiren Patel Avatar answered Oct 04 '22 21:10

Hiren Patel