Example usage for android.content ContentResolver getSyncAutomatically

List of usage examples for android.content ContentResolver getSyncAutomatically

Introduction

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

Prototype

public static boolean getSyncAutomatically(Account account, String authority) 

Source Link

Document

Check if the provider should be synced when a network tickle is received

This method requires the caller to hold the permission android.Manifest.permission#READ_SYNC_SETTINGS .

Usage

From source file:de.spiritcroc.syncsettings.Util.java

public static void autoSyncToggle(Account account, String authority) {
    if (DEBUG) {//from w  w  w. j a  va  2s  . c  o m
        Log.d(LOG_TAG, "sync toggle " + account + ", " + authority);
        Log.d(LOG_TAG, "previous " + ContentResolver.getSyncAutomatically(account, authority));
    }
    boolean autoSync = ContentResolver.getSyncAutomatically(account, authority);
    ContentResolver.setSyncAutomatically(account, authority, !autoSync);
    if (DEBUG) {
        Log.d("syncsettings", "now " + ContentResolver.getSyncAutomatically(account, authority));
    }
}

From source file:com.granita.contacticloudsync.syncadapter.AccountSettings.java

public Long getSyncInterval(String authority) {
    if (ContentResolver.getIsSyncable(account, authority) <= 0)
        return null;

    if (ContentResolver.getSyncAutomatically(account, authority)) {
        List<PeriodicSync> syncs = ContentResolver.getPeriodicSyncs(account, authority);
        if (syncs.isEmpty())
            return SYNC_INTERVAL_MANUALLY;
        else// w ww  .  ja  v a 2  s.co  m
            return syncs.get(0).period;
    } else
        return SYNC_INTERVAL_MANUALLY;
}

From source file:at.bitfire.davdroid.AccountSettings.java

public Long getSyncInterval(@NonNull String authority) {
    if (ContentResolver.getIsSyncable(account, authority) <= 0)
        return null;

    if (ContentResolver.getSyncAutomatically(account, authority)) {
        List<PeriodicSync> syncs = ContentResolver.getPeriodicSyncs(account, authority);
        if (syncs.isEmpty())
            return SYNC_INTERVAL_MANUALLY;
        else//  w  ww .  j a v a2s  .co  m
            return syncs.get(0).period;
    } else
        return SYNC_INTERVAL_MANUALLY;
}

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

public static void deleteIfSyncDisabled(Context context) {
    if (!(ContextCompat.checkSelfPermission(context,
            Manifest.permission.READ_CONTACTS) == PackageManager.PERMISSION_GRANTED)) {
        return;//w w  w  .jav  a2s .co m
    }

    Account account = KeychainApplication.createAccountIfNecessary(context);
    if (account == null) {
        return;
    }

    // if user has disabled automatic sync, delete linked OpenKeychain contacts
    if (!ContentResolver.getSyncAutomatically(account, ContactsContract.AUTHORITY)) {
        new ContactHelper(context).deleteAllContacts();
    }
}

From source file:com.odoo.MainActivity.java

private void updateSyncSettings() {
    Log.d(TAG, "MainActivity->updateSyncSettings()");

    PreferenceManager mPref = new PreferenceManager(mContext);
    int sync_interval = mPref.getInt("sync_interval", 1440);

    List<String> default_authorities = new ArrayList<String>();
    default_authorities.add("com.android.calendar");
    default_authorities.add("com.android.contacts");

    SyncAdapterType[] list = ContentResolver.getSyncAdapterTypes();

    Account mAccount = OdooAccountManager.getAccount(mContext, OUser.current(mContext).getAndroidName());

    for (SyncAdapterType lst : list) {
        if (lst.authority.contains("com.odoo") && lst.authority.contains("providers")) {
            default_authorities.add(lst.authority);
        }//from  w w  w.j  a  v a2  s  .  c  om
    }
    for (String authority : default_authorities) {
        boolean isSyncActive = ContentResolver.getSyncAutomatically(mAccount, authority);
        if (isSyncActive) {
            setSyncPeriodic(authority, sync_interval, 60, 1);
        }
    }
    Toast.makeText(this, R.string.toast_setting_saved, Toast.LENGTH_LONG).show();
}

From source file:com.openerp.MainActivity.java

private void updateSyncSettings() {
    Log.d(TAG, "MainActivity->updateSyncSettings()");

    PreferenceManager mPref = new PreferenceManager(mContext);
    int sync_interval = mPref.getInt("sync_interval", 1440);

    List<String> default_authorities = new ArrayList<String>();
    default_authorities.add("com.android.calendar");
    default_authorities.add("com.android.contacts");

    SyncAdapterType[] list = ContentResolver.getSyncAdapterTypes();

    Account mAccount = OpenERPAccountManager.getAccount(mContext, OEUser.current(mContext).getAndroidName());

    for (SyncAdapterType lst : list) {
        if (lst.authority.contains("com.openerp") && lst.authority.contains("providers")) {
            default_authorities.add(lst.authority);
        }//from   w  ww .ja v  a2s.c  o m
    }
    for (String authority : default_authorities) {
        boolean isSyncActive = ContentResolver.getSyncAutomatically(mAccount, authority);
        if (isSyncActive) {
            setSyncPeriodic(authority, sync_interval, 60, 1);
        }
    }
    Toast.makeText(this, R.string.toast_setting_saved, Toast.LENGTH_LONG).show();
}

From source file:org.mozilla.gecko.fxa.authenticator.AndroidFxAccount.java

public Map<String, Boolean> getAuthoritiesToSyncAutomaticallyMap() {
    final Map<String, Boolean> authoritiesToSync = new HashMap<>();
    for (String authority : DEFAULT_AUTHORITIES_TO_SYNC_AUTOMATICALLY_MAP.keySet()) {
        final boolean enabled = ContentResolver.getSyncAutomatically(account, authority);
        authoritiesToSync.put(authority, enabled);
    }//from  w  w  w. j a va2s.  c o  m
    return authoritiesToSync;
}

From source file:org.voidsink.anewjkuapp.utils.AppUtils.java

public static void updateSyncAlarm(Context context, boolean reCreateAlarm) {
    boolean mIsCalendarSyncEnabled = false;
    boolean mIsKusssSyncEnable = false;
    boolean mIsMasterSyncEnabled = ContentResolver.getMasterSyncAutomatically();

    if (mIsMasterSyncEnabled) {
        final Account mAccount = getAccount(context);
        if (mAccount != null) {
            mIsCalendarSyncEnabled = ContentResolver.getSyncAutomatically(mAccount,
                    CalendarContractWrapper.AUTHORITY());
            mIsKusssSyncEnable = ContentResolver.getSyncAutomatically(mAccount, KusssContentContract.AUTHORITY);
        }//  w  w w . j  ava  2  s  . c  o m
    }

    Log.d(TAG, String.format("MasterSync=%b, CalendarSync=%b, KusssSync=%b", mIsMasterSyncEnabled,
            mIsCalendarSyncEnabled, mIsKusssSyncEnable));

    AlarmManager am = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
    Intent intent = new Intent(context, SyncAlarmService.class);
    intent.putExtra(Consts.ARG_UPDATE_CAL, !mIsCalendarSyncEnabled);
    intent.putExtra(Consts.ARG_UPDATE_KUSSS, !mIsKusssSyncEnable);
    intent.putExtra(Consts.ARG_RECREATE_SYNC_ALARM, true);
    intent.putExtra(Consts.SYNC_SHOW_PROGRESS, true);

    // check if pending intent exists
    reCreateAlarm = reCreateAlarm
            || (PendingIntent.getService(context, 0, intent, PendingIntent.FLAG_NO_CREATE) == null);

    // new pending intent
    PendingIntent alarmIntent = PendingIntent.getService(context, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
    if (!mIsMasterSyncEnabled || !mIsCalendarSyncEnabled || !mIsKusssSyncEnable) {
        if (reCreateAlarm) {
            long interval = PreferenceWrapper.getSyncInterval(context) * DateUtils.HOUR_IN_MILLIS;

            // synchronize in half an hour
            am.setInexactRepeating(AlarmManager.RTC_WAKEUP,
                    System.currentTimeMillis() + AlarmManager.INTERVAL_HALF_HOUR, interval, alarmIntent);
        }
    } else {
        am.cancel(alarmIntent);
    }
}

From source file:com.android.exchange.EasAccountService.java

private void runPingLoop()
        throws IOException, StaleFolderListException, IllegalHeartbeatException, CommandStatusException {
    int pingHeartbeat = mPingHeartbeat;
    userLog("runPingLoop");
    // Do push for all sync services here
    long endTime = System.currentTimeMillis() + (30 * DateUtils.MINUTE_IN_MILLIS);
    HashMap<String, Integer> pingErrorMap = new HashMap<String, Integer>();
    ArrayList<String> readyMailboxes = new ArrayList<String>();
    ArrayList<String> notReadyMailboxes = new ArrayList<String>();
    int pingWaitCount = 0;
    long inboxId = -1;
    android.accounts.Account amAccount = new android.accounts.Account(mAccount.mEmailAddress,
            Eas.EXCHANGE_ACCOUNT_MANAGER_TYPE);
    while ((System.currentTimeMillis() < endTime) && !isStopped()) {
        // Count of pushable mailboxes
        int pushCount = 0;
        // Count of mailboxes that can be pushed right now
        int canPushCount = 0;
        // Count of uninitialized boxes
        int uninitCount = 0;

        Serializer s = new Serializer();
        Cursor c = mContentResolver.query(Mailbox.CONTENT_URI, Mailbox.CONTENT_PROJECTION,
                MailboxColumns.ACCOUNT_KEY + '=' + mAccount.mId
                        + AND_FREQUENCY_PING_PUSH_AND_NOT_ACCOUNT_MAILBOX,
                null, null);/*from www .  ja  v a2  s . c  o m*/
        if (c == null)
            throw new ProviderUnavailableException();
        notReadyMailboxes.clear();
        readyMailboxes.clear();
        // Look for an inbox, and remember its id
        if (inboxId == -1) {
            inboxId = Mailbox.findMailboxOfType(mContext, mAccount.mId, Mailbox.TYPE_INBOX);
        }
        try {
            // Loop through our pushed boxes seeing what is available to push
            while (c.moveToNext()) {
                pushCount++;
                // Two requirements for push:
                // 1) ExchangeService tells us the mailbox is syncable (not running/not stopped)
                // 2) The syncKey isn't "0" (i.e. it's synced at least once)
                long mailboxId = c.getLong(Mailbox.CONTENT_ID_COLUMN);
                String mailboxName = c.getString(Mailbox.CONTENT_DISPLAY_NAME_COLUMN);

                // See what type of box we've got and get authority
                int mailboxType = c.getInt(Mailbox.CONTENT_TYPE_COLUMN);
                String authority = EmailContent.AUTHORITY;
                switch (mailboxType) {
                case Mailbox.TYPE_CALENDAR:
                    authority = CalendarContract.AUTHORITY;
                    break;
                case Mailbox.TYPE_CONTACTS:
                    authority = ContactsContract.AUTHORITY;
                    break;
                }

                // See whether we can ping for this mailbox
                int pingStatus;
                if (!ContentResolver.getSyncAutomatically(amAccount, authority)) {
                    pingStatus = ExchangeService.PING_STATUS_DISABLED;
                } else {
                    pingStatus = ExchangeService.pingStatus(mailboxId);

                }

                if (pingStatus == ExchangeService.PING_STATUS_OK) {
                    String syncKey = c.getString(Mailbox.CONTENT_SYNC_KEY_COLUMN);
                    if ((syncKey == null) || syncKey.equals("0")) {
                        // We can't push until the initial sync is done
                        pushCount--;
                        uninitCount++;
                        continue;
                    }

                    if (canPushCount++ == 0) {
                        // Initialize the Ping command
                        s.start(Tags.PING_PING)
                                .data(Tags.PING_HEARTBEAT_INTERVAL, Integer.toString(pingHeartbeat))
                                .start(Tags.PING_FOLDERS);
                    }

                    String folderClass = getTargetCollectionClassFromCursor(c);
                    s.start(Tags.PING_FOLDER).data(Tags.PING_ID, c.getString(Mailbox.CONTENT_SERVER_ID_COLUMN))
                            .data(Tags.PING_CLASS, folderClass).end();
                    readyMailboxes.add(mailboxName);
                } else if ((pingStatus == ExchangeService.PING_STATUS_RUNNING)
                        || (pingStatus == ExchangeService.PING_STATUS_WAITING)) {
                    notReadyMailboxes.add(mailboxName);
                } else if (pingStatus == ExchangeService.PING_STATUS_UNABLE) {
                    pushCount--;
                    userLog(mailboxName, " in error state; ignore");
                    continue;
                } else if (pingStatus == ExchangeService.PING_STATUS_DISABLED) {
                    pushCount--;
                    userLog(mailboxName, " disabled by user; ignore");
                    continue;
                }
            }
        } finally {
            c.close();
        }

        if (Eas.USER_LOG) {
            if (!notReadyMailboxes.isEmpty()) {
                userLog("Ping not ready for: " + notReadyMailboxes);
            }
            if (!readyMailboxes.isEmpty()) {
                userLog("Ping ready for: " + readyMailboxes);
            }
        }

        // If we've waited 10 seconds or more, just ping with whatever boxes are ready
        // But use a shorter than normal heartbeat
        boolean forcePing = !notReadyMailboxes.isEmpty() && (pingWaitCount > 5);

        if ((canPushCount > 0) && ((canPushCount == pushCount) || forcePing)) {
            // If all pingable boxes are ready for push, send Ping to the server
            s.end().end().done();
            pingWaitCount = 0;
            mPostAborted = false;
            mPostReset = false;

            // If we've been stopped, this is a good time to return
            if (isStopped())
                return;

            long pingTime = SystemClock.elapsedRealtime();
            try {
                // Send the ping, wrapped by appropriate timeout/alarm
                if (forcePing) {
                    userLog("Forcing ping after waiting for all boxes to be ready");
                }
                EasResponse resp = sendPing(s.toByteArray(), forcePing ? mPingForceHeartbeat : pingHeartbeat);

                try {
                    int code = resp.getStatus();
                    userLog("Ping response: ", code);

                    // If we're not allowed to sync (e.g. roaming policy), terminate gracefully
                    // now; otherwise we might start a sync based on the response
                    if (!ExchangeService.canAutoSync(mAccount)) {
                        stop();
                    }

                    // Return immediately if we've been asked to stop during the ping
                    if (isStopped()) {
                        userLog("Stopping pingLoop");
                        return;
                    }

                    if (code == HttpStatus.SC_OK) {
                        if (!resp.isEmpty()) {
                            InputStream is = resp.getInputStream();
                            int pingResult = parsePingResult(is, mContentResolver, pingErrorMap);
                            // If our ping completed (status = 1), and wasn't forced and we're
                            // not at the maximum, try increasing timeout by two minutes
                            if (pingResult == PROTOCOL_PING_STATUS_COMPLETED && !forcePing) {
                                if (pingHeartbeat > mPingHighWaterMark) {
                                    mPingHighWaterMark = pingHeartbeat;
                                    userLog("Setting high water mark at: ", mPingHighWaterMark);
                                }
                                if ((pingHeartbeat < mPingMaxHeartbeat) && !mPingHeartbeatDropped) {
                                    pingHeartbeat += PING_HEARTBEAT_INCREMENT;
                                    if (pingHeartbeat > mPingMaxHeartbeat) {
                                        pingHeartbeat = mPingMaxHeartbeat;
                                    }
                                    userLog("Increase ping heartbeat to ", pingHeartbeat, "s");
                                }
                            } else if (pingResult == PROTOCOL_PING_STATUS_BAD_PARAMETERS
                                    || pingResult == PROTOCOL_PING_STATUS_RETRY) {
                                // These errors appear to be server-related (I've seen a bad
                                // parameters result with known good parameters...)
                                userLog("Server error during Ping: " + pingResult);
                                // Act as if we have an IOException (backoff, etc.)
                                throw new IOException();
                            }
                            // Make sure to clear out any pending sync errors
                            ExchangeService.removeFromSyncErrorMap(mMailboxId);
                        } else {
                            userLog("Ping returned empty result; throwing IOException");
                            // Act as if we have an IOException (backoff, etc.)
                            throw new IOException();
                        }
                    } else if (resp.isAuthError()) {
                        mExitStatus = EasSyncService.EXIT_LOGIN_FAILURE;
                        userLog("Authorization error during Ping: ", code);
                        throw new IOException();
                    }
                } finally {
                    resp.close();
                }
            } catch (IOException e) {
                String message = e.getMessage();
                // If we get the exception that is indicative of a NAT timeout and if we
                // haven't yet "fixed" the timeout, back off by two minutes and "fix" it
                boolean hasMessage = message != null;
                userLog("IOException runPingLoop: " + (hasMessage ? message : "[no message]"));
                if (mPostReset) {
                    // Nothing to do in this case; this is ExchangeService telling us to try
                    // another ping.
                } else if (mPostAborted || isLikelyNatFailure(message)) {
                    long pingLength = SystemClock.elapsedRealtime() - pingTime;
                    if ((pingHeartbeat > mPingMinHeartbeat) && (pingHeartbeat > mPingHighWaterMark)) {
                        pingHeartbeat -= PING_HEARTBEAT_INCREMENT;
                        mPingHeartbeatDropped = true;
                        if (pingHeartbeat < mPingMinHeartbeat) {
                            pingHeartbeat = mPingMinHeartbeat;
                        }
                        userLog("Decreased ping heartbeat to ", pingHeartbeat, "s");
                    } else if (mPostAborted) {
                        // There's no point in throwing here; this can happen in two cases
                        // 1) An alarm, which indicates minutes without activity; no sense
                        //    backing off
                        // 2) ExchangeService abort, due to sync of mailbox.  Again, we want to
                        //    keep on trying to ping
                        userLog("Ping aborted; retry");
                    } else if (pingLength < 2000) {
                        userLog("Abort or NAT type return < 2 seconds; throwing IOException");
                        throw e;
                    } else {
                        userLog("NAT type IOException");
                    }
                } else if (hasMessage && message.contains("roken pipe")) {
                    // The "broken pipe" error (uppercase or lowercase "b") seems to be an
                    // internal error, so let's not throw an exception (which leads to delays)
                    // but rather simply run through the loop again
                } else {
                    throw e;
                }
            }
        } else if (forcePing) {
            // In this case, there aren't any boxes that are pingable, but there are boxes
            // waiting (for IOExceptions)
            userLog("pingLoop waiting 60s for any pingable boxes");
            sleep(60 * DateUtils.SECOND_IN_MILLIS, true);
        } else if (pushCount > 0) {
            // If we want to Ping, but can't just yet, wait a little bit
            // TODO Change sleep to wait and use notify from ExchangeService when a sync ends
            sleep(2 * DateUtils.SECOND_IN_MILLIS, false);
            pingWaitCount++;
            //userLog("pingLoop waited 2s for: ", (pushCount - canPushCount), " box(es)");
        } else if (uninitCount > 0) {
            // In this case, we're doing an initial sync of at least one mailbox.  Since this
            // is typically a one-time case, I'm ok with trying again every 10 seconds until
            // we're in one of the other possible states.
            userLog("pingLoop waiting for initial sync of ", uninitCount, " box(es)");
            sleep(10 * DateUtils.SECOND_IN_MILLIS, true);
        } else if (inboxId == -1) {
            // In this case, we're still syncing mailboxes, so sleep for only a short time
            sleep(45 * DateUtils.SECOND_IN_MILLIS, true);
        } else {
            // We've got nothing to do, so we'll check again in 20 minutes at which time
            // we'll update the folder list, check for policy changes and/or remote wipe, etc.
            // Let the device sleep in the meantime...
            userLog(ACCOUNT_MAILBOX_SLEEP_TEXT);
            sleep(ACCOUNT_MAILBOX_SLEEP_TIME, true);
        }
    }

    // Save away the current heartbeat
    mPingHeartbeat = pingHeartbeat;
}

From source file:com.android.exchange.SyncManager.java

/**
 * See if we need to change the syncInterval for any of our PIM mailboxes based on changes
 * to settings in the AccountManager (sync settings).
 * This code is called 1) when SyncManager starts, and 2) when SyncManager is running and there
 * are changes made (this is detected via a SyncStatusObserver)
 */// w w  w  .ja v  a  2 s .  co m
private void updatePIMSyncSettings(Account providerAccount, int mailboxType, String authority) {
    ContentValues cv = new ContentValues();
    long mailboxId = Mailbox.findMailboxOfType(this, providerAccount.mId, mailboxType);
    // Presumably there is one, but if not, it's ok.  Just move on...
    if (mailboxId != Mailbox.NO_MAILBOX) {
        // Create an AccountManager style Account
        android.accounts.Account acct = new android.accounts.Account(providerAccount.mEmailAddress,
                Email.EXCHANGE_ACCOUNT_MANAGER_TYPE);
        // Get the mailbox; this happens rarely so it's ok to get it all
        Mailbox mailbox = Mailbox.restoreMailboxWithId(this, mailboxId);
        if (mailbox == null)
            return;
        int syncInterval = mailbox.mSyncInterval;
        // If we're syncable, look further...
        if (ContentResolver.getIsSyncable(acct, authority) > 0) {
            // If we're supposed to sync automatically (push), set to push if it's not
            if (ContentResolver.getSyncAutomatically(acct, authority)) {
                if (syncInterval == Mailbox.CHECK_INTERVAL_NEVER || syncInterval > 0) {
                    log("Sync for " + mailbox.mDisplayName + " in " + acct.name + ": push");
                    cv.put(MailboxColumns.SYNC_INTERVAL, Mailbox.CHECK_INTERVAL_PUSH);
                }
                // If we're NOT supposed to push, and we're not set up that way, change it
            } else if (syncInterval != Mailbox.CHECK_INTERVAL_NEVER) {
                log("Sync for " + mailbox.mDisplayName + " in " + acct.name + ": manual");
                cv.put(MailboxColumns.SYNC_INTERVAL, Mailbox.CHECK_INTERVAL_NEVER);
            }
            // If not, set it to never check
        } else if (syncInterval != Mailbox.CHECK_INTERVAL_NEVER) {
            log("Sync for " + mailbox.mDisplayName + " in " + acct.name + ": manual");
            cv.put(MailboxColumns.SYNC_INTERVAL, Mailbox.CHECK_INTERVAL_NEVER);
        }

        // If we've made a change, update the Mailbox, and kick
        if (cv.containsKey(MailboxColumns.SYNC_INTERVAL)) {
            mResolver.update(ContentUris.withAppendedId(Mailbox.CONTENT_URI, mailboxId), cv, null, null);
            kick("sync settings change");
        }
    }
}