Example usage for android.content ContentResolver getMasterSyncAutomatically

List of usage examples for android.content ContentResolver getMasterSyncAutomatically

Introduction

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

Prototype

public static boolean getMasterSyncAutomatically() 

Source Link

Document

Gets the master auto-sync setting that applies to all the providers and accounts.

Usage

From source file:org.anhonesteffort.flock.MigrationService.java

private void handleReplaceEventsAndContacts() {
    Log.d(TAG, "handleReplaceEventsAndContacts()");

    handleEnableAllSyncAdapters();/*  www  . j  a va 2 s .co  m*/
    if (!ContentResolver.getMasterSyncAutomatically()) {
        handleAskUserToEnableSync();
        return;
    }
    handleUpdateNotificationUsingState();

    Long firstRecordedCalendarSync = getTimeFirstSync(KEY_TIME_FIRST_CALENDAR_SYNC);
    Optional<Long> timeLastCalendarSync = new CalendarsSyncScheduler(getBaseContext()).getTimeLastSync();

    if (firstRecordedCalendarSync <= 0) {
        if (!timeLastCalendarSync.isPresent())
            recordTimeFirstSync(KEY_TIME_FIRST_CALENDAR_SYNC, new Date().getTime());
        else
            recordTimeFirstSync(KEY_TIME_FIRST_CALENDAR_SYNC, timeLastCalendarSync.get());

        new CalendarsSyncScheduler(getBaseContext()).requestSync();
    }

    Long firstRecordedAddressbookSync = getTimeFirstSync(KEY_TIME_FIRST_ADDRESSBOOK_SYNC);
    Optional<Long> timeLastAddressbookSync = new AddressbookSyncScheduler(getBaseContext()).getTimeLastSync();

    if (firstRecordedAddressbookSync <= 0) {
        if (!timeLastAddressbookSync.isPresent())
            recordTimeFirstSync(KEY_TIME_FIRST_ADDRESSBOOK_SYNC, new Date().getTime());
        else
            recordTimeFirstSync(KEY_TIME_FIRST_ADDRESSBOOK_SYNC, timeLastAddressbookSync.get());

        new AddressbookSyncScheduler(getBaseContext()).requestSync();
    }

    if (firstRecordedCalendarSync > 0 && firstRecordedAddressbookSync > 0) {
        if (timeLastCalendarSync.isPresent() && timeLastAddressbookSync.isPresent()) {
            if (timeLastCalendarSync.get() > firstRecordedCalendarSync
                    && timeLastAddressbookSync.get() > firstRecordedAddressbookSync) {
                setState(STATE_REPLACED_EVENTS_AND_CONTACTS);
            }
        }
    }
}

From source file:com.chen.emailsync.SyncManager.java

/**
 * Determine whether a mailbox of a given type in a given account can be synced automatically
 * by SyncServiceManager.  This is an increasingly complex determination, taking into account
 * security policies and user settings (both within the Email application and in the Settings
 * application)/*from  ww  w . j  a  va 2  s.c o  m*/
 *
 * @param account the Account that the mailbox is in
 * @param type the type of the Mailbox
 * @return whether or not to start a sync
 */
private boolean isMailboxSyncable(Account account, int type) {
    // This 'if' statement performs checks to see whether or not a mailbox is a
    // candidate for syncing based on policies, user settings, & other restrictions
    if (type == Mailbox.TYPE_OUTBOX) {
        // Outbox is always syncable
        return true;
    } else if (type == Mailbox.TYPE_EAS_ACCOUNT_MAILBOX) {
        // Always sync EAS mailbox unless master sync is off
        return ContentResolver.getMasterSyncAutomatically();
    } else if (type == Mailbox.TYPE_CONTACTS || type == Mailbox.TYPE_CALENDAR) {
        // Contacts/Calendar obey this setting from ContentResolver
        if (!ContentResolver.getMasterSyncAutomatically()) {
            return false;
        }
        // Get the right authority for the mailbox
        String authority;
        if (type == Mailbox.TYPE_CONTACTS) {
            authority = ContactsContract.AUTHORITY;
        } else {
            authority = CalendarContract.AUTHORITY;
            if (!mCalendarObservers.containsKey(account.mId)) {
                // Make sure we have an observer for this Calendar, as
                // we need to be able to detect sync state changes, sigh
                registerCalendarObserver(account);
            }
        }
        // See if "sync automatically" is set; if not, punt
        if (!ContentResolver.getSyncAutomatically(mAccountList.getAmAccount(account), authority)) {
            return false;
            // See if the calendar is enabled from the Calendar app UI; if not, punt
        } else if ((type == Mailbox.TYPE_CALENDAR) && !isCalendarEnabled(account.mId)) {
            return false;
        }
        // Never automatically sync trash
    } else if (type == Mailbox.TYPE_TRASH) {
        return false;
        // For non-outbox, non-account mail, we do two checks:
        // 1) are we restricted by policy (i.e. manual sync only),
        // 2) has the user checked the "Sync Email" box in Account Settings, and
    } else if (!canAutoSync(account) || !canSyncEmail(mAccountList.getAmAccount(account))) {
        return false;
    }
    return true;
}

From source file:com.sentaroh.android.TaskAutomation.TaskExecutor.java

final static public boolean setAutoSyncEnabled(TaskManagerParms taskMgrParms, EnvironmentParms envParms,
        CommonUtilities util, TaskResponse taskResponse, ActionResponse ar) {
    if (!ContentResolver.getMasterSyncAutomatically()) {
        ContentResolver.setMasterSyncAutomatically(true);
        return true;
    } else {/*w  ww .j  a  v  a  2  s  . c  om*/
        ar.action_resp = ActionResponse.ACTION_WARNING;
        ar.resp_msg_text = "AutoSync was already enabled, action ignored";
        return false;
    }
}

From source file:com.sentaroh.android.TaskAutomation.TaskExecutor.java

final static public boolean setAutoSyncDisabled(TaskManagerParms taskMgrParms, EnvironmentParms envParms,
        CommonUtilities util, TaskResponse taskResponse, ActionResponse ar) {
    if (ContentResolver.getMasterSyncAutomatically()) {
        ContentResolver.setMasterSyncAutomatically(false);
        return true;
    } else {/*  w w  w.j a  v a 2  s .  c o  m*/
        ar.action_resp = ActionResponse.ACTION_WARNING;
        ar.resp_msg_text = "AutoSync was already disabled, action ignored";
        return false;
    }
}

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

private long checkMailboxes() {
    // First, see if any running mailboxes have been deleted
    ArrayList<Long> deletedMailboxes = new ArrayList<Long>();
    synchronized (sSyncLock) {
        for (long mailboxId : mServiceMap.keySet()) {
            Mailbox m = Mailbox.restoreMailboxWithId(this, mailboxId);
            if (m == null) {
                deletedMailboxes.add(mailboxId);
            }//from   w w  w  .ja  va  2s  . c om
        }
        // If so, stop them or remove them from the map
        for (Long mailboxId : deletedMailboxes) {
            AbstractSyncService svc = mServiceMap.get(mailboxId);
            if (svc == null || svc.mThread == null) {
                releaseMailbox(mailboxId);
                continue;
            } else {
                boolean alive = svc.mThread.isAlive();
                log("Deleted mailbox: " + svc.mMailboxName);
                if (alive) {
                    stopManualSync(mailboxId);
                } else {
                    log("Removing from serviceMap");
                    releaseMailbox(mailboxId);
                }
            }
        }
    }

    long nextWait = SYNC_MANAGER_HEARTBEAT_TIME;
    long now = System.currentTimeMillis();

    // Start up threads that need it; use a query which finds eas mailboxes where the
    // the sync interval is not "never".  This is the set of mailboxes that we control
    if (mAccountObserver == null) {
        log("mAccountObserver null; service died??");
        return nextWait;
    }
    Cursor c = getContentResolver().query(Mailbox.CONTENT_URI, Mailbox.CONTENT_PROJECTION,
            mAccountObserver.getSyncableEasMailboxWhere(), null, null);

    // Contacts/Calendar obey this setting from ContentResolver
    // Mail is on its own schedule
    boolean masterAutoSync = ContentResolver.getMasterSyncAutomatically();
    try {
        while (c.moveToNext()) {
            long mid = c.getLong(Mailbox.CONTENT_ID_COLUMN);
            AbstractSyncService service = null;
            synchronized (sSyncLock) {
                service = mServiceMap.get(mid);
            }
            if (service == null) {
                // We handle a few types of mailboxes specially
                int type = c.getInt(Mailbox.CONTENT_TYPE_COLUMN);

                // If background data is off, we only sync Outbox
                // Manual syncs are initiated elsewhere, so they will continue to be respected
                if (!mBackgroundData && type != Mailbox.TYPE_OUTBOX) {
                    continue;
                }

                if (type == Mailbox.TYPE_CONTACTS || type == Mailbox.TYPE_CALENDAR) {
                    // We don't sync these automatically if master auto sync is off
                    if (!masterAutoSync) {
                        continue;
                    }
                    // Get the right authority for the mailbox
                    String authority;
                    Account account = getAccountById(c.getInt(Mailbox.CONTENT_ACCOUNT_KEY_COLUMN));
                    if (account != null) {
                        if (type == Mailbox.TYPE_CONTACTS) {
                            authority = ContactsContract.AUTHORITY;
                        } else {
                            authority = Calendar.AUTHORITY;
                            if (!mCalendarObservers.containsKey(account.mId)) {
                                // Make sure we have an observer for this Calendar, as
                                // we need to be able to detect sync state changes, sigh
                                registerCalendarObserver(account);
                            }
                        }
                        android.accounts.Account a = new android.accounts.Account(account.mEmailAddress,
                                Email.EXCHANGE_ACCOUNT_MANAGER_TYPE);
                        // See if "sync automatically" is set; if not, punt
                        if (!ContentResolver.getSyncAutomatically(a, authority)) {
                            continue;
                            // See if the calendar is enabled; if not, punt
                        } else if ((type == Mailbox.TYPE_CALENDAR) && !isCalendarEnabled(account.mId)) {
                            continue;
                        }
                    }
                } else if (type == Mailbox.TYPE_TRASH) {
                    continue;
                }

                // Check whether we're in a hold (temporary or permanent)
                SyncError syncError = mSyncErrorMap.get(mid);
                if (syncError != null) {
                    // Nothing we can do about fatal errors
                    if (syncError.fatal)
                        continue;
                    if (now < syncError.holdEndTime) {
                        // If release time is earlier than next wait time,
                        // move next wait time up to the release time
                        if (syncError.holdEndTime < now + nextWait) {
                            nextWait = syncError.holdEndTime - now;
                            mNextWaitReason = "Release hold";
                        }
                        continue;
                    } else {
                        // Keep the error around, but clear the end time
                        syncError.holdEndTime = 0;
                    }
                }

                // Otherwise, we use the sync interval
                long interval = c.getInt(Mailbox.CONTENT_SYNC_INTERVAL_COLUMN);
                if (interval == Mailbox.CHECK_INTERVAL_PUSH) {
                    Mailbox m = EmailContent.getContent(c, Mailbox.class);
                    requestSync(m, SYNC_PUSH, null);
                } else if (type == Mailbox.TYPE_OUTBOX) {
                    int cnt = EmailContent.count(this, Message.CONTENT_URI,
                            EasOutboxService.MAILBOX_KEY_AND_NOT_SEND_FAILED,
                            new String[] { Long.toString(mid) });
                    if (cnt > 0) {
                        Mailbox m = EmailContent.getContent(c, Mailbox.class);
                        startServiceThread(new EasOutboxService(this, m), m);
                    }
                } else if (interval > 0 && interval <= ONE_DAY_MINUTES) {
                    long lastSync = c.getLong(Mailbox.CONTENT_SYNC_TIME_COLUMN);
                    long sinceLastSync = now - lastSync;
                    if (sinceLastSync < 0) {
                        log("WHOA! lastSync in the future for mailbox: " + mid);
                        sinceLastSync = interval * MINUTES;
                    }
                    long toNextSync = interval * MINUTES - sinceLastSync;
                    String name = c.getString(Mailbox.CONTENT_DISPLAY_NAME_COLUMN);
                    if (toNextSync <= 0) {
                        Mailbox m = EmailContent.getContent(c, Mailbox.class);
                        requestSync(m, SYNC_SCHEDULED, null);
                    } else if (toNextSync < nextWait) {
                        nextWait = toNextSync;
                        if (Eas.USER_LOG) {
                            log("Next sync for " + name + " in " + nextWait / 1000 + "s");
                        }
                        mNextWaitReason = "Scheduled sync, " + name;
                    } else if (Eas.USER_LOG) {
                        log("Next sync for " + name + " in " + toNextSync / 1000 + "s");
                    }
                }
            } else {
                Thread thread = service.mThread;
                // Look for threads that have died and remove them from the map
                if (thread != null && !thread.isAlive()) {
                    if (Eas.USER_LOG) {
                        log("Dead thread, mailbox released: "
                                + c.getString(Mailbox.CONTENT_DISPLAY_NAME_COLUMN));
                    }
                    releaseMailbox(mid);
                    // Restart this if necessary
                    if (nextWait > 3 * SECONDS) {
                        nextWait = 3 * SECONDS;
                        mNextWaitReason = "Clean up dead thread(s)";
                    }
                } else {
                    long requestTime = service.mRequestTime;
                    if (requestTime > 0) {
                        long timeToRequest = requestTime - now;
                        if (service instanceof AbstractSyncService && timeToRequest <= 0) {
                            service.mRequestTime = 0;
                            service.alarm();
                        } else if (requestTime > 0 && timeToRequest < nextWait) {
                            if (timeToRequest < 11 * MINUTES) {
                                nextWait = timeToRequest < 250 ? 250 : timeToRequest;
                                mNextWaitReason = "Sync data change";
                            } else {
                                log("Illegal timeToRequest: " + timeToRequest);
                            }
                        }
                    }
                }
            }
        }
    } finally {
        c.close();
    }
    return nextWait;
}

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

private long checkMailboxes() {
    // First, see if any running mailboxes have been deleted
    ArrayList<Long> deletedMailboxes = new ArrayList<Long>();
    synchronized (sSyncLock) {
        for (long mailboxId : mServiceMap.keySet()) {
            Mailbox m = Mailbox.restoreMailboxWithId(this, mailboxId);
            if (m == null) {
                deletedMailboxes.add(mailboxId);
            }//from  w w w  .  ja v a2s.co  m
        }
        // If so, stop them or remove them from the map
        for (Long mailboxId : deletedMailboxes) {
            AbstractSyncService svc = mServiceMap.get(mailboxId);
            if (svc == null || svc.mThread == null) {
                releaseMailbox(mailboxId);
                continue;
            } else {
                boolean alive = svc.mThread.isAlive();
                log("Deleted mailbox: " + svc.mMailboxName);
                if (alive) {
                    stopManualSync(mailboxId);
                } else {
                    log("Removing from serviceMap");
                    releaseMailbox(mailboxId);
                }
            }
        }
    }

    long nextWait = SYNC_MANAGER_HEARTBEAT_TIME;
    long now = System.currentTimeMillis();

    // Start up threads that need it; use a query which finds eas mailboxes where the
    // the sync interval is not "never".  This is the set of mailboxes that we control
    if (mAccountObserver == null) {
        log("mAccountObserver null; service died??");
        return nextWait;
    }
    Cursor c = getContentResolver().query(Mailbox.CONTENT_URI, Mailbox.CONTENT_PROJECTION,
            mAccountObserver.getSyncableEasMailboxWhere(), null, null);

    // Contacts/Calendar obey this setting from ContentResolver
    // Mail is on its own schedule
    boolean masterAutoSync = ContentResolver.getMasterSyncAutomatically();
    try {
        while (c.moveToNext()) {
            long mid = c.getLong(Mailbox.CONTENT_ID_COLUMN);
            AbstractSyncService service = null;
            synchronized (sSyncLock) {
                service = mServiceMap.get(mid);
            }
            if (service == null) {
                // We handle a few types of mailboxes specially
                int type = c.getInt(Mailbox.CONTENT_TYPE_COLUMN);

                // If background data is off, we only sync Outbox
                // Manual syncs are initiated elsewhere, so they will continue to be respected
                if (!mBackgroundData && type != Mailbox.TYPE_OUTBOX) {
                    continue;
                }

                if (type == Mailbox.TYPE_CONTACTS || type == Mailbox.TYPE_CALENDAR) {
                    // We don't sync these automatically if master auto sync is off
                    if (!masterAutoSync) {
                        continue;
                    }
                    // Get the right authority for the mailbox
                    String authority;
                    Account account = getAccountById(c.getInt(Mailbox.CONTENT_ACCOUNT_KEY_COLUMN));
                    if (account != null) {
                        if (type == Mailbox.TYPE_CONTACTS) {
                            authority = ContactsContract.AUTHORITY;
                        } else {
                            authority = Calendar.AUTHORITY;
                            if (!mCalendarObservers.containsKey(account.mId)) {
                                // Make sure we have an observer for this Calendar, as
                                // we need to be able to detect sync state changes, sigh
                                registerCalendarObserver(account);
                            }
                        }
                        android.accounts.Account a = new android.accounts.Account(account.mEmailAddress,
                                Email.EXCHANGE_ACCOUNT_MANAGER_TYPE);
                        // See if "sync automatically" is set; if not, punt
                        if (!ContentResolver.getSyncAutomatically(a, authority)) {
                            continue;
                            // See if the calendar is enabled; if not, punt
                        } else if ((type == Mailbox.TYPE_CALENDAR) && !isCalendarEnabled(account.mId)) {
                            continue;
                        }
                    }
                } else if (type == Mailbox.TYPE_TRASH) {
                    continue;
                }

                // Check whether we're in a hold (temporary or permanent)
                SyncError syncError = mSyncErrorMap.get(mid);
                if (syncError != null) {
                    // Nothing we can do about fatal errors
                    if (syncError.fatal)
                        continue;
                    if (now < syncError.holdEndTime) {
                        // If release time is earlier than next wait time,
                        // move next wait time up to the release time
                        if (syncError.holdEndTime < now + nextWait) {
                            nextWait = syncError.holdEndTime - now;
                            mNextWaitReason = "Release hold";
                        }
                        continue;
                    } else {
                        // Keep the error around, but clear the end time
                        syncError.holdEndTime = 0;
                    }
                }

                // Otherwise, we use the sync interval
                long interval = c.getInt(Mailbox.CONTENT_SYNC_INTERVAL_COLUMN);
                if (interval == Mailbox.CHECK_INTERVAL_PUSH) {
                    Mailbox m = EmailContent.getContent(c, Mailbox.class);
                    requestSync(m, SYNC_PUSH, null);
                } else if (type == Mailbox.TYPE_OUTBOX) {
                    int cnt = EmailContent.count(this, Message.CONTENT_URI,
                            EasOutboxService.MAILBOX_KEY_AND_NOT_SEND_FAILED,
                            new String[] { Long.toString(mid) });
                    if (cnt > 0) {
                        Mailbox m = EmailContent.getContent(c, Mailbox.class);
                        startServiceThread(new EasOutboxService(this, m), m);
                    }
                } else if (interval > 0 && interval <= ONE_DAY_MINUTES) {
                    long lastSync = c.getLong(Mailbox.CONTENT_SYNC_TIME_COLUMN);
                    long sinceLastSync = now - lastSync;
                    if (sinceLastSync < 0) {
                        log("WHOA! lastSync in the future for mailbox: " + mid);
                        sinceLastSync = interval * MINUTES;
                    }
                    long toNextSync = interval * MINUTES - sinceLastSync;
                    String name = c.getString(Mailbox.CONTENT_DISPLAY_NAME_COLUMN);
                    if (toNextSync <= 0) {
                        Mailbox m = EmailContent.getContent(c, Mailbox.class);
                        requestSync(m, SYNC_SCHEDULED, null);
                    } else if (toNextSync < nextWait) {
                        nextWait = toNextSync;
                        if (Eas.USER_LOG) {
                            log("Next sync for " + name + " in " + nextWait / 1000 + "s");
                        }
                        mNextWaitReason = "Scheduled sync, " + name;
                    } else if (Eas.USER_LOG) {
                        log("Next sync for " + name + " in " + toNextSync / 1000 + "s");
                    }
                }
            } else {
                Thread thread = service.mThread;
                // Look for threads that have died and remove them from the map
                if (thread != null && !thread.isAlive()) {
                    if (Eas.USER_LOG) {
                        log("Dead thread, mailbox released: "
                                + c.getString(Mailbox.CONTENT_DISPLAY_NAME_COLUMN));
                    }
                    releaseMailbox(mid);
                    // Restart this if necessary
                    if (nextWait > 3 * SECONDS) {
                        nextWait = 3 * SECONDS;
                        mNextWaitReason = "Clean up dead thread(s)";
                    }
                } else {
                    long requestTime = service.mRequestTime;
                    if (requestTime > 0) {
                        long timeToRequest = requestTime - now;
                        if (timeToRequest <= 0) {
                            service.mRequestTime = 0;
                            service.alarm();
                        } else if (requestTime > 0 && timeToRequest < nextWait) {
                            if (timeToRequest < 11 * MINUTES) {
                                nextWait = timeToRequest < 250 ? 250 : timeToRequest;
                                mNextWaitReason = "Sync data change";
                            } else {
                                log("Illegal timeToRequest: " + timeToRequest);
                            }
                        }
                    }
                }
            }
        }
    } finally {
        c.close();
    }
    return nextWait;
}

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

/**
 * Determine whether a mailbox of a given type in a given account can be synced automatically
 * by ExchangeService.  This is an increasingly complex determination, taking into account
 * security policies and user settings (both within the Email application and in the Settings
 * application)/*from ww  w . ja v a  2s.  co  m*/
 *
 * @param account the Account that the mailbox is in
 * @param type the type of the Mailbox
 * @return whether or not to start a sync
 */
private boolean isMailboxSyncable(Account account, int type) {
    // This 'if' statement performs checks to see whether or not a mailbox is a
    // candidate for syncing based on policies, user settings, & other restrictions
    if (type == Mailbox.TYPE_OUTBOX || type == Mailbox.TYPE_EAS_ACCOUNT_MAILBOX) {
        // Outbox and account mailbox are always syncable
        return true;
    } else if (type == Mailbox.TYPE_CONTACTS || type == Mailbox.TYPE_CALENDAR) {
        // Contacts/Calendar obey this setting from ContentResolver
        if (!ContentResolver.getMasterSyncAutomatically()) {
            return false;
        }
        // Get the right authority for the mailbox
        String authority;
        if (type == Mailbox.TYPE_CONTACTS) {
            authority = ContactsContract.AUTHORITY;
        } else {
            authority = CalendarContract.AUTHORITY;
            if (!mCalendarObservers.containsKey(account.mId)) {
                // Make sure we have an observer for this Calendar, as
                // we need to be able to detect sync state changes, sigh
                registerCalendarObserver(account);
            }
        }
        // See if "sync automatically" is set; if not, punt
        if (!ContentResolver.getSyncAutomatically(account.mAmAccount, authority)) {
            return false;
            // See if the calendar is enabled from the Calendar app UI; if not, punt
        } else if ((type == Mailbox.TYPE_CALENDAR) && !isCalendarEnabled(account.mId)) {
            return false;
        }
        // Never automatically sync trash
    } else if (type == Mailbox.TYPE_TRASH) {
        return false;
        // For non-outbox, non-account mail, we do three checks:
        // 1) are we restricted by policy (i.e. manual sync only),
        // 2) has the user checked the "Sync Email" box in Account Settings, and
        // 3) does the user have the master "background data" box checked in Settings
    } else if (!canAutoSync(account) || !canSyncEmail(account.mAmAccount) || !mBackgroundData) {
        return false;
    }
    return true;
}