Example usage for android.content ContentResolver setIsSyncable

List of usage examples for android.content ContentResolver setIsSyncable

Introduction

In this page you can find the example usage for android.content ContentResolver setIsSyncable.

Prototype

public static void setIsSyncable(Account account, String authority, int syncable) 

Source Link

Document

Set whether this account/provider is syncable.

Usage

From source file:saschpe.birthdays.helper.AccountHelper.java

public static Bundle addAccount(Context context) {
    Log.d(TAG, "AccountHelper.addAccount: Adding account...");

    final Account account = new Account(context.getString(R.string.app_name),
            context.getString(R.string.account_type));
    AccountManager manager = AccountManager.get(context);

    if (manager.addAccountExplicitly(account, null, null)) {
        // Enable automatic sync once per day
        ContentResolver.setSyncAutomatically(account, context.getString(R.string.content_authority), true);
        ContentResolver.setIsSyncable(account, context.getString(R.string.content_authority), 1);

        // Add periodic sync interval based on user preference
        final long freq = PreferencesHelper.getPeriodicSyncFrequency(context);
        ContentResolver.addPeriodicSync(account, context.getString(R.string.content_authority), new Bundle(),
                freq);//from  w w  w. j ava2  s .c  o m

        Bundle result = new Bundle();
        result.putString(AccountManager.KEY_ACCOUNT_NAME, account.name);
        result.putString(AccountManager.KEY_ACCOUNT_TYPE, account.type);
        Log.i(TAG, "Account added: " + account.name);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            manager.notifyAccountAuthenticated(account);
        }
        return result;
    } else {
        Log.e(TAG, "Adding account explicitly failed!");
        return null;
    }
}

From source file:org.birthdayadapter.util.AccountHelper.java

/**
 * Add account for Birthday Adapter to Android system
 *//*w  w w.  j  av a  2  s.c  o m*/
public Bundle addAccountAndSync() {
    Log.d(Constants.TAG, "Adding account...");

    // enable automatic sync once per day
    ContentResolver.setSyncAutomatically(Constants.ACCOUNT, Constants.CONTENT_AUTHORITY, true);
    ContentResolver.setIsSyncable(Constants.ACCOUNT, Constants.ACCOUNT_TYPE, 1);

    // add periodic sync interval once per day
    long freq = AlarmManager.INTERVAL_DAY;
    ContentResolver.addPeriodicSync(Constants.ACCOUNT, Constants.ACCOUNT_TYPE, new Bundle(), freq);

    AccountManager am = AccountManager.get(mContext);
    if (am.addAccountExplicitly(Constants.ACCOUNT, null, null)) {
        Bundle result = new Bundle();
        result.putString(AccountManager.KEY_ACCOUNT_NAME, Constants.ACCOUNT.name);
        result.putString(AccountManager.KEY_ACCOUNT_TYPE, Constants.ACCOUNT.type);

        // Force a sync! Even when background sync is disabled, this will force one sync!
        manualSync();

        return result;
    } else {
        return null;
    }
}

From source file:at.bitfire.davdroid.syncadapter.AccountDetailsFragment.java

void addAccount() {
    ServerInfo serverInfo = (ServerInfo) getArguments().getSerializable(KEY_SERVER_INFO);
    String accountName = editAccountName.getText().toString();

    AccountManager accountManager = AccountManager.get(getActivity());
    Account account = new Account(accountName, Constants.ACCOUNT_TYPE);
    Bundle userData = new Bundle();
    userData.putString(Constants.ACCOUNT_KEY_BASE_URL, serverInfo.getBaseURL());
    userData.putString(Constants.ACCOUNT_KEY_USERNAME, serverInfo.getUserName());
    userData.putString(Constants.ACCOUNT_KEY_AUTH_PREEMPTIVE, Boolean.toString(serverInfo.isAuthPreemptive()));

    boolean syncContacts = false;
    for (ServerInfo.ResourceInfo addressBook : serverInfo.getAddressBooks())
        if (addressBook.isEnabled()) {
            userData.putString(Constants.ACCOUNT_KEY_ADDRESSBOOK_PATH, addressBook.getPath());
            ContentResolver.setIsSyncable(account, ContactsContract.AUTHORITY, 1);
            syncContacts = true;/*w  w  w . j a v  a 2 s .c o m*/
            continue;
        }
    if (syncContacts) {
        ContentResolver.setIsSyncable(account, ContactsContract.AUTHORITY, 1);
        ContentResolver.setSyncAutomatically(account, ContactsContract.AUTHORITY, true);
    } else
        ContentResolver.setIsSyncable(account, ContactsContract.AUTHORITY, 0);

    if (accountManager.addAccountExplicitly(account, serverInfo.getPassword(), userData)) {
        // account created, now create calendars
        ContentResolver.setIsSyncable(account, "com.android.calendar", 0);

        getActivity().finish();
    } else
        Toast.makeText(getActivity(), "Couldn't create account (account with this name already existing?)",
                Toast.LENGTH_LONG).show();
}

From source file:org.enbyted.android.zseinfo.view.activity.MainActivity.java

public static Account createSyncAccount(Context context) {
    Account newAccount = new Account(ACCOUNT, ACCOUNT_TYPE);
    AccountManager accountManager = (AccountManager) context.getSystemService(ACCOUNT_SERVICE);

    if (accountManager.addAccountExplicitly(newAccount, null, null)) {
        ContentResolver.setSyncAutomatically(newAccount, AUTHORITY, true);
        ContentResolver.setIsSyncable(newAccount, AUTHORITY, 1);
    } else {//from  w w w . ja v  a 2s .  c om

    }
    return newAccount;
}

From source file:org.andstatus.app.account.AccountData.java

/**
 * @param result /*  www.  j a  va 2s.  c  om*/
 * @return true if Android account changed
 */
void saveDataToAccount(MyContext myContext, Account androidAccount, SaveResult result) {
    AccountData oldData = fromAndroidAccount(myContext, androidAccount);
    result.changed = !this.equals(oldData);
    if (result.changed) {
        long syncFrequencySeconds = getDataLong(MyPreferences.KEY_SYNC_FREQUENCY_SECONDS, 0);
        if (syncFrequencySeconds > 0 && syncFrequencySeconds != getSyncFrequencySeconds(androidAccount)) {
            result.changed = true;
            setSyncFrequencySeconds(androidAccount, syncFrequencySeconds);
        }
        boolean isSyncable = getDataBoolean(MyAccount.KEY_IS_SYNCABLE, true);
        if (isSyncable != (ContentResolver.getIsSyncable(androidAccount, MyProvider.AUTHORITY) != 0)) {
            ContentResolver.setIsSyncable(androidAccount, MyProvider.AUTHORITY, isSyncable ? 1 : 0);
        }
        boolean syncAutomatically = getDataBoolean(MyAccount.KEY_SYNC_AUTOMATICALLY, true);
        if (syncAutomatically != ContentResolver.getSyncAutomatically(androidAccount, MyProvider.AUTHORITY)) {
            // We need to preserve sync on/off during backup/restore.
            // don't know about "network tickles"... See:
            // http://stackoverflow.com/questions/5013254/what-is-a-network-tickle-and-how-to-i-go-about-sending-one
            ContentResolver.setSyncAutomatically(androidAccount, MyProvider.AUTHORITY, syncAutomatically);
        }
        android.accounts.AccountManager am = AccountManager.get(myContext.context());
        am.setUserData(androidAccount, KEY_ACCOUNT, toJsonString());
        result.savedToAccountManager = true;
    }
    result.success = true;
}

From source file:org.pixmob.droidlink.ui.AccountInitTask.java

@Override
protected Integer doInBackground(String... params) {
    final String newAccount = params[0];
    final String oldAccount = prefs.getString(SP_KEY_ACCOUNT, null);

    // Make sure this user has an unique device identifier.
    final boolean newUserSet = !prefs.contains(SP_KEY_DEVICE_ID) || !newAccount.equals(oldAccount);
    if (newUserSet) {
        prefsEditor.putString(SP_KEY_DEVICE_ID, DeviceUtils.getDeviceId(fragment.getActivity(), newAccount));
    }/*from  w w w. j a  v  a2s  . c  o m*/

    prefsEditor.putString(SP_KEY_ACCOUNT, newAccount);
    Features.getFeature(SharedPreferencesSaverFeature.class).save(prefsEditor);

    final NetworkClient client = NetworkClient.newInstance(fragment.getActivity());

    int authResult = AUTH_FAIL;
    if (client != null) {
        final JSONObject data = new JSONObject();

        try {
            data.put("name", prefs.getString(SP_KEY_DEVICE_NAME, null));
            data.put("c2dm", prefs.getString(SP_KEY_DEVICE_C2DM, null));
            client.put("/devices/" + client.getDeviceId(), data);
            authResult = AUTH_OK;
        } catch (AppEngineAuthenticationException e) {
            if (e.isAuthenticationPending()) {
                authPendingIntent = e.getPendingAuthenticationPermissionActivity();
                authResult = AUTH_PENDING;
            }
            Log.w(TAG, "Failed to authenticate account", e);
        } catch (IOException e) {
            Log.w(TAG, "Failed to check account availability", e);
        } catch (JSONException e) {
            Log.w(TAG, "JSON error", e);
        } finally {
            client.close();
        }
    }

    if (AUTH_OK == authResult) {
        if (newUserSet) {
            // The user is different: clear events.
            contentResolver.delete(EventsContract.CONTENT_URI, null, null);
        }

        prefsEditor.putString(SP_KEY_ACCOUNT, newAccount);

        // Enable synchronization only for our user.
        for (final Account account : accounts) {
            final boolean syncable = account.name.equals(newAccount);
            ContentResolver.setIsSyncable(account, EventsContract.AUTHORITY, syncable ? 1 : 0);
        }
        ContentResolver.setSyncAutomatically(new Account(newAccount, GOOGLE_ACCOUNT), EventsContract.AUTHORITY,
                true);
    } else {
        // Restore old account.
        prefsEditor.putString(SP_KEY_ACCOUNT, oldAccount);
    }

    Features.getFeature(SharedPreferencesSaverFeature.class).save(prefsEditor);

    if (AUTH_OK == authResult) {
        // Start synchronization.
        EventsContract.sync(getFragment().getActivity(), EventsContract.FULL_SYNC, null);
    }

    return authResult;
}

From source file:net.sf.diningout.app.ui.InitActivity.java

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    if (resultCode == RESULT_OK) { // initialise the selected account
        Prefs.putString(this, APP, ACCOUNT_NAME, data.getStringExtra(KEY_ACCOUNT_NAME));
        Account account = Accounts.selected();
        ContentResolver.setIsSyncable(account, AUTHORITY, 1);
        ContentResolver.setSyncAutomatically(account, AUTHORITY, true);
        if (Network.isConnected(this)) {
            Fragments.open(this).add(android.R.id.content, new ProgressBarFragment(), PROGRESS).commit();
            mReceiver.start(this);
            Content.requestSyncNow(account, AUTHORITY);
            return;
        }// w w  w  .java  2 s.com
    } else {
        event("account", "not chosen", "result code " + resultCode);
    }
    /* proceed without account and/or network connection */
    invalidateOptionsMenu(); // API 16 overwrites 'done' with 'add' without this
    setDefaultContentView();
}

From source file:at.bitfire.davdroid.ui.setup.AccountDetailsFragment.java

protected boolean createAccount(String accountName, DavResourceFinder.Configuration config) {
    Account account = new Account(accountName, Constants.ACCOUNT_TYPE);

    // create Android account
    Bundle userData = AccountSettings.initialUserData(config.userName);
    App.log.log(Level.INFO, "Creating Android account with initial config", new Object[] { account, userData });

    AccountManager accountManager = AccountManager.get(getContext());
    if (!accountManager.addAccountExplicitly(account, config.password, userData))
        return false;

    // add entries for account to service DB
    App.log.log(Level.INFO, "Writing account configuration to database", config);
    @Cleanup/*from  w ww .  j a  v a2  s  . c om*/
    OpenHelper dbHelper = new OpenHelper(getContext());
    SQLiteDatabase db = dbHelper.getWritableDatabase();
    try {
        AccountSettings settings = new AccountSettings(getContext(), account);

        Intent refreshIntent = new Intent(getActivity(), DavService.class);
        refreshIntent.setAction(DavService.ACTION_REFRESH_COLLECTIONS);

        if (config.cardDAV != null) {
            // insert CardDAV service
            long id = insertService(db, accountName, Services.SERVICE_CARDDAV, config.cardDAV);

            // start CardDAV service detection (refresh collections)
            refreshIntent.putExtra(DavService.EXTRA_DAV_SERVICE_ID, id);
            getActivity().startService(refreshIntent);

            // initial CardDAV account settings
            int idx = spnrGroupMethod.getSelectedItemPosition();
            String groupMethodName = getResources()
                    .getStringArray(R.array.settings_contact_group_method_values)[idx];
            settings.setGroupMethod(GroupMethod.valueOf(groupMethodName));

            // enable contact sync
            ContentResolver.setIsSyncable(account, ContactsContract.AUTHORITY, 1);
            settings.setSyncInterval(ContactsContract.AUTHORITY, DEFAULT_SYNC_INTERVAL);
        } else
            // disable contact sync when CardDAV is not available
            ContentResolver.setIsSyncable(account, ContactsContract.AUTHORITY, 0);

        if (config.calDAV != null) {
            // insert CalDAV service
            long id = insertService(db, accountName, Services.SERVICE_CALDAV, config.calDAV);

            // start CalDAV service detection (refresh collections)
            refreshIntent.putExtra(DavService.EXTRA_DAV_SERVICE_ID, id);
            getActivity().startService(refreshIntent);

            // enable calendar sync
            ContentResolver.setIsSyncable(account, CalendarContract.AUTHORITY, 1);
            settings.setSyncInterval(CalendarContract.AUTHORITY, DEFAULT_SYNC_INTERVAL);

            // enable task sync, if possible
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                /* Android >=6, it's possible to gain OpenTasks permissions dynamically, so
                 * OpenTasks sync will be enabled by default. Setting the sync interval to "manually"
                 * if OpenTasks is not installed avoids the "sync error" in Android settings / Accounts. */
                ContentResolver.setIsSyncable(account, TaskProvider.ProviderName.OpenTasks.authority, 1);
                settings.setSyncInterval(TaskProvider.ProviderName.OpenTasks.authority,
                        LocalTaskList.tasksProviderAvailable(getContext()) ? DEFAULT_SYNC_INTERVAL
                                : AccountSettings.SYNC_INTERVAL_MANUALLY);
            } else {
                // Android <6: enable task sync according to whether OpenTasks is accessible
                if (LocalTaskList.tasksProviderAvailable(getContext())) {
                    ContentResolver.setIsSyncable(account, TaskProvider.ProviderName.OpenTasks.authority, 1);
                    settings.setSyncInterval(TaskProvider.ProviderName.OpenTasks.authority,
                            DEFAULT_SYNC_INTERVAL);
                } else
                    // Android <6 only: disable OpenTasks sync forever when OpenTasks is not installed
                    // because otherwise, there will be a non-catchable SecurityException as soon as OpenTasks is installed
                    ContentResolver.setIsSyncable(account, TaskProvider.ProviderName.OpenTasks.authority, 0);
            }
        } else {
            // disable calendar and task sync when CalDAV is not available
            ContentResolver.setIsSyncable(account, CalendarContract.AUTHORITY, 0);
            ContentResolver.setIsSyncable(account, TaskProvider.ProviderName.OpenTasks.authority, 0);
        }

    } catch (InvalidAccountException e) {
        App.log.log(Level.SEVERE, "Couldn't access account settings", e);
    }

    return true;
}

From source file:org.sufficientlysecure.keychain.service.ContactSyncAdapterService.java

public static void enableContactsSync(Context context) {
    Account account = KeychainApplication.createAccountIfNecessary(context);
    if (account == null) {
        return;/* w  w  w . j a v a 2s .c o m*/
    }

    ContentResolver.setIsSyncable(account, ContactsContract.AUTHORITY, 1);
    ContentResolver.setSyncAutomatically(account, ContactsContract.AUTHORITY, true);
}

From source file:com.rukman.emde.smsgroups.authenticator.GMSAuthenticatorActivity.java

/**
 * Called when response is received from the server for authentication
 * request. See onAuthenticationResult(). Sets the
 * AccountAuthenticatorResult which is sent back to the caller. We store the
 * authToken that's returned from the server as the 'password' for this
 * account - so we're never storing the user's actual password locally.
 *
 * @param result the confirmCredentials result.
 *//*from  w w  w . ja  v a2  s. c  o  m*/
private void finishLogin(String authToken) {

    Log.i(TAG, "finishLogin()");
    final Account account = new Account(mUsername, GMSApplication.ACCOUNT_TYPE);
    if (mIsUnknownAccountName) {
        mAccountManager.addAccountExplicitly(account, mPassword, null);
        // Set contacts sync for this account.
        ContentResolver.setIsSyncable(account, GMSProvider.AUTHORITY, 1);
        ContentResolver.setSyncAutomatically(account, GMSProvider.AUTHORITY, true);
    } else {
        mAccountManager.setPassword(account, mPassword);
    }
    final Intent intent = new Intent();
    intent.putExtra(AccountManager.KEY_ACCOUNT_NAME, mUsername);
    intent.putExtra(AccountManager.KEY_ACCOUNT_TYPE, GMSApplication.ACCOUNT_TYPE);
    setAccountAuthenticatorResult(intent.getExtras());
    setResult(RESULT_OK, intent);
    finish();
}