Example usage for android.content ContentResolver SYNC_EXTRAS_MANUAL

List of usage examples for android.content ContentResolver SYNC_EXTRAS_MANUAL

Introduction

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

Prototype

String SYNC_EXTRAS_MANUAL

To view the source code for android.content ContentResolver SYNC_EXTRAS_MANUAL.

Click Source Link

Document

Setting this extra is the equivalent of setting both #SYNC_EXTRAS_IGNORE_SETTINGS and #SYNC_EXTRAS_IGNORE_BACKOFF

Usage

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

@TargetApi(Build.VERSION_CODES.JELLY_BEAN)
@Override//from w  ww  .  j  a v a  2  s.  c o  m
public void onPerformSync(Account account, Bundle extras, String authority, ContentProviderClient provider,
        SyncResult syncResult) {
    Log.i(TAG, "Performing sync for authority " + authority);

    /* Set class loader for iCal4j ResourceLoader  this is required because the various
     * sync adapters (contacts, events, tasks) share the same :sync process (see AndroidManifest */
    Thread.currentThread().setContextClassLoader(getContext().getClassLoader());

    // create httpClient, if necessary
    httpClientLock.writeLock().lock();
    if (httpClient == null) {
        Log.d(TAG, "Creating new DavHttpClient");
        httpClient = DavHttpClient.create();
    }

    // prevent httpClient shutdown until we're ready by holding a read lock
    // acquiring read lock before releasing write lock will downgrade the write lock to a read lock
    httpClientLock.readLock().lock();
    httpClientLock.writeLock().unlock();

    Exception exceptionToShow = null; // exception to show notification for
    Intent exceptionIntent = null; // what shall happen when clicking on the exception notification
    try {
        // get local <-> remote collection pairs
        Map<LocalCollection<?>, WebDavCollection<?>> syncCollections = getSyncPairs(account, provider);
        if (syncCollections == null)
            Log.i(TAG, "Nothing to synchronize");
        else
            try {
                for (Map.Entry<LocalCollection<?>, WebDavCollection<?>> entry : syncCollections.entrySet())
                    new SyncManager(entry.getKey(), entry.getValue())
                            .synchronize(extras.containsKey(ContentResolver.SYNC_EXTRAS_MANUAL), syncResult);

            } catch (DavException ex) {
                syncResult.stats.numParseExceptions++;
                Log.e(TAG, "Invalid DAV response", ex);
                exceptionToShow = ex;

            } catch (HttpException ex) {
                if (ex.getCode() == HttpStatus.SC_UNAUTHORIZED) {
                    Log.e(TAG, "HTTP Unauthorized " + ex.getCode(), ex);
                    syncResult.stats.numAuthExceptions++; // hard error

                    exceptionToShow = ex;
                    exceptionIntent = new Intent(context, AccountActivity.class);
                    exceptionIntent.putExtra(AccountActivity.EXTRA_ACCOUNT, account);
                } else if (ex.isClientError()) {
                    Log.e(TAG, "Hard HTTP error " + ex.getCode(), ex);
                    syncResult.stats.numParseExceptions++; // hard error
                    exceptionToShow = ex;
                } else {
                    Log.w(TAG, "Soft HTTP error " + ex.getCode() + " (Android will try again later)", ex);
                    syncResult.stats.numIoExceptions++; // soft error
                }
            } catch (LocalStorageException ex) {
                syncResult.databaseError = true; // hard error
                Log.e(TAG, "Local storage (content provider) exception", ex);
                exceptionToShow = ex;
            } catch (IOException ex) {
                syncResult.stats.numIoExceptions++; // soft error
                Log.e(TAG, "I/O error (Android will try again later)", ex);
                if (ex instanceof SSLException) // always notify on SSL/TLS errors
                    exceptionToShow = ex;
            } catch (URISyntaxException ex) {
                syncResult.stats.numParseExceptions++; // hard error
                Log.e(TAG, "Invalid URI (file name) syntax", ex);
                exceptionToShow = ex;
            }
    } finally {
        // allow httpClient shutdown
        httpClientLock.readLock().unlock();
    }

    // show sync errors as notification
    if (exceptionToShow != null && Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
        if (exceptionIntent == null)
            exceptionIntent = new Intent(Intent.ACTION_VIEW, Uri.parse(Constants.WEB_URL_VIEW_LOGS));

        PendingIntent contentIntent = PendingIntent.getActivity(context, 0, exceptionIntent, 0);
        Notification.Builder builder = new Notification.Builder(context).setSmallIcon(R.drawable.ic_launcher)
                .setPriority(Notification.PRIORITY_LOW).setOnlyAlertOnce(true)
                .setWhen(System.currentTimeMillis())
                .setContentTitle(context.getString(R.string.sync_error_title))
                .setContentText(exceptionToShow.getLocalizedMessage()).setContentInfo(account.name)
                .setStyle(new Notification.BigTextStyle()
                        .bigText(account.name + ":\n" + ExceptionUtils.getStackTrace(exceptionToShow)))
                .setContentIntent(contentIntent);

        NotificationManager notificationManager = (NotificationManager) context
                .getSystemService(Context.NOTIFICATION_SERVICE);
        notificationManager.notify(account.name.hashCode(), builder.build());
    }

    Log.i(TAG, "Sync complete for " + authority);
}

From source file:com.ravi.apps.android.newsbytes.sync.NewsSyncAdapter.java

/**
 * Instructs the sync adapter to sync immediately.
 *//*w  w  w  .j av  a  2 s .co  m*/
public static void syncImmediately(Context context) {
    Log.d(LOG_TAG, context.getString(R.string.log_sync_immediately));

    Bundle bundle = new Bundle();
    bundle.putBoolean(ContentResolver.SYNC_EXTRAS_EXPEDITED, true);
    bundle.putBoolean(ContentResolver.SYNC_EXTRAS_MANUAL, true);
    ContentResolver.requestSync(getSyncAccount(context), context.getString(R.string.content_authority), bundle);
}

From source file:org.tasks.gtasks.GoogleTaskSyncAdapter.java

/**
 * Called by the Android system in response to a request to run the sync adapter. The work
 * required to read data from the network, parse it, and store it in the content provider is
 * done here. Extending AbstractThreadedSyncAdapter ensures that all methods within SyncAdapter
 * run on a background thread. For this reason, blocking I/O and other long-running tasks can be
 * run <em>in situ</em>, and you don't have to set up a separate thread for them.
 .
 *
 * <p>This is where we actually perform any work required to perform a sync.
 * {@link android.content.AbstractThreadedSyncAdapter} guarantees that this will be called on a non-UI thread,
 * so it is safe to peform blocking I/O here.
 *
 * <p>The syncResult argument allows you to pass information back to the method that triggered
 * the sync./*www .java 2  s .com*/
 */
@Override
public void onPerformSync(Account account, Bundle extras, String authority, ContentProviderClient provider,
        SyncResult syncResult) {
    if (!account.name.equals(gtasksPreferenceService.getUserName())) {
        Timber.d("Sync not enabled for %s", account);
        syncResult.stats.numAuthExceptions++;
        return;
    }
    if (!extras.getBoolean(ContentResolver.SYNC_EXTRAS_MANUAL, false)) {
        preferences.setBoolean(R.string.p_sync_warning_shown, false);
    }
    Timber.d("%s: start sync", account);
    RecordSyncStatusCallback callback = new RecordSyncStatusCallback(gtasksPreferenceService, broadcaster);
    try {
        callback.started();
        synchronize();
        gtasksPreferenceService.recordSuccessfulSync();
    } catch (UserRecoverableAuthIOException e) {
        Timber.e(e, e.getMessage());
        sendNotification(getContext(), e.getIntent());
    } catch (IOException e) {
        Timber.e(e, e.getMessage());
    } catch (Exception e) {
        tracker.reportException(e);
    } finally {
        callback.finished();
        Timber.d("%s: end sync", account);
    }
}

From source file:com.synox.android.syncadapter.FileSyncAdapter.java

/**
 * {@inheritDoc}//from   w w  w  . j a  va 2  s.c  o m
 */
@Override
public synchronized void onPerformSync(Account account, Bundle extras, String authority,
        ContentProviderClient providerClient, SyncResult syncResult) {

    mCancellation = false;
    mIsManualSync = extras.getBoolean(ContentResolver.SYNC_EXTRAS_MANUAL, false);
    mFailedResultsCounter = 0;
    mLastFailedResult = null;
    mConflictsFound = 0;
    mFailsInFavouritesFound = 0;
    mForgottenLocalFiles = new HashMap<>();
    mSyncResult = syncResult;
    mSyncResult.fullSyncRequested = false;
    mSyncResult.delayUntil = (System.currentTimeMillis() / 1000) + 3 * 60 * 60; // avoid too many automatic synchronizations

    this.setAccount(account);
    this.setContentProviderClient(providerClient);
    this.setStorageManager(new FileDataStorageManager(account, providerClient));

    try {
        this.initClientForCurrentAccount();
    } catch (IOException e) {
        /// the account is unknown for the Synchronization Manager, unreachable this context,
        // or can not be authenticated; don't try this again
        mSyncResult.tooManyRetries = true;
        notifyFailedSynchronization();
        return;
    } catch (AccountsException e) {
        /// the account is unknown for the Synchronization Manager, unreachable this context,
        // or can not be authenticated; don't try this again
        mSyncResult.tooManyRetries = true;
        notifyFailedSynchronization();
        return;
    }

    Log_OC.d(TAG, "Synchronization of ownCloud account " + account.name + " starting");
    sendLocalBroadcast(EVENT_FULL_SYNC_START, null, null); // message to signal the start
    // of the synchronization to the UI

    try {
        updateOCVersion();
        mCurrentSyncTime = System.currentTimeMillis();
        if (!mCancellation) {
            synchronizeFolder(getStorageManager().getFileByPath(OCFile.ROOT_PATH));

        } else {
            Log_OC.d(TAG, "Leaving synchronization before synchronizing the root folder "
                    + "because cancelation request");
        }

    } finally {
        // it's important making this although very unexpected errors occur;
        // that's the reason for the finally

        if (mFailedResultsCounter > 0 && mIsManualSync) {
            /// don't let the system synchronization manager retries MANUAL synchronizations
            //      (be careful: "MANUAL" currently includes the synchronization requested when
            //      a new account is created and when the user changes the current account)
            mSyncResult.tooManyRetries = true;

            /// notify the user about the failure of MANUAL synchronization
            notifyFailedSynchronization();
        }
        if (mConflictsFound > 0 || mFailsInFavouritesFound > 0) {
            notifyFailsInFavourites();
        }
        if (mForgottenLocalFiles.size() > 0) {
            notifyForgottenLocalFiles();
        }
        sendLocalBroadcast(EVENT_FULL_SYNC_END, null, mLastFailedResult); // message to signal
        // the end to the UI
    }

}

From source file:com.cerema.cloud2.syncadapter.FileSyncAdapter.java

/**
 * {@inheritDoc}/*from  www.j a va  2s.com*/
 */
@Override
public synchronized void onPerformSync(Account account, Bundle extras, String authority,
        ContentProviderClient providerClient, SyncResult syncResult) {

    mCancellation = false;
    mIsManualSync = extras.getBoolean(ContentResolver.SYNC_EXTRAS_MANUAL, false);
    mFailedResultsCounter = 0;
    mLastFailedResult = null;
    mConflictsFound = 0;
    mFailsInFavouritesFound = 0;
    mForgottenLocalFiles = new HashMap<String, String>();
    mSyncResult = syncResult;
    mSyncResult.fullSyncRequested = false;
    mSyncResult.delayUntil = (System.currentTimeMillis() / 1000) + 3 * 60 * 60; // avoid too many automatic synchronizations

    this.setAccount(account);
    this.setContentProviderClient(providerClient);
    this.setStorageManager(new FileDataStorageManager(account, providerClient));

    try {
        this.initClientForCurrentAccount();
    } catch (IOException e) {
        /// the account is unknown for the Synchronization Manager, unreachable this context,
        // or can not be authenticated; don't try this again
        mSyncResult.tooManyRetries = true;
        notifyFailedSynchronization();
        return;
    } catch (AccountsException e) {
        /// the account is unknown for the Synchronization Manager, unreachable this context,
        // or can not be authenticated; don't try this again
        mSyncResult.tooManyRetries = true;
        notifyFailedSynchronization();
        return;
    }

    Log_OC.d(TAG, "Synchronization of ownCloud account " + account.name + " starting");
    sendLocalBroadcast(EVENT_FULL_SYNC_START, null, null); // message to signal the start
                                                           // of the synchronization to the UI

    try {
        updateOCVersion();
        mCurrentSyncTime = System.currentTimeMillis();
        if (!mCancellation) {
            synchronizeFolder(getStorageManager().getFileByPath(OCFile.ROOT_PATH));

        } else {
            Log_OC.d(TAG, "Leaving synchronization before synchronizing the root folder "
                    + "because cancelation request");
        }

    } finally {
        // it's important making this although very unexpected errors occur;
        // that's the reason for the finally

        if (mFailedResultsCounter > 0 && mIsManualSync) {
            /// don't let the system synchronization manager retries MANUAL synchronizations
            //      (be careful: "MANUAL" currently includes the synchronization requested when
            //      a new account is created and when the user changes the current account)
            mSyncResult.tooManyRetries = true;

            /// notify the user about the failure of MANUAL synchronization
            notifyFailedSynchronization();
        }
        if (mConflictsFound > 0 || mFailsInFavouritesFound > 0) {
            notifyFailsInFavourites();
        }
        if (mForgottenLocalFiles.size() > 0) {
            notifyForgottenLocalFiles();
        }
        sendLocalBroadcast(EVENT_FULL_SYNC_END, null, mLastFailedResult); // message to signal
                                                                          // the end to the UI
    }

}

From source file:at.bitfire.davdroid.mirakel.syncadapter.DavSyncAdapter.java

@Override
public void onPerformSync(Account account, Bundle extras, String authority, ContentProviderClient provider,
        SyncResult syncResult) {/*from w  w  w .  ja  va 2  s  . com*/
    Log.i(TAG, "Performing sync for authority " + authority);
    // set class loader for iCal4j ResourceLoader
    Thread.currentThread().setContextClassLoader(getContext().getClassLoader());

    // create httpClient, if necessary
    httpClientLock.writeLock().lock();
    if (httpClient == null) {
        Log.d(TAG, "Creating new DavHttpClient");
        SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(getContext());
        httpClient = DavHttpClient.create(settings.getBoolean(Constants.SETTING_DISABLE_COMPRESSION, false),
                settings.getBoolean(Constants.SETTING_NETWORK_LOGGING, false));
    }

    // prevent httpClient shutdown until we're ready by holding a read lock
    // acquiring read lock before releasing write lock will downgrade the write lock to a read lock
    httpClientLock.readLock().lock();
    httpClientLock.writeLock().unlock();

    // TODO use VCard 4.0 if possible
    AccountSettings accountSettings = new AccountSettings(getContext(), account);
    Log.d(TAG, "Server supports VCard version " + accountSettings.getAddressBookVCardVersion());

    try {
        // get local <-> remote collection pairs
        Map<LocalCollection<?>, RemoteCollection<?>> syncCollections = getSyncPairs(account, provider);
        if (syncCollections == null)
            Log.i(TAG, "Nothing to synchronize");
        else
            try {
                for (Map.Entry<LocalCollection<?>, RemoteCollection<?>> entry : syncCollections.entrySet())
                    new SyncManager(entry.getKey(), entry.getValue())
                            .synchronize(extras.containsKey(ContentResolver.SYNC_EXTRAS_MANUAL), syncResult);

            } catch (DavException ex) {
                syncResult.stats.numParseExceptions++;
                Log.e(TAG, "Invalid DAV response", ex);
            } catch (HttpException ex) {
                if (ex.getCode() == HttpStatus.SC_UNAUTHORIZED) {
                    Log.e(TAG, "HTTP Unauthorized " + ex.getCode(), ex);
                    syncResult.stats.numAuthExceptions++;
                } else if (ex.isClientError()) {
                    Log.e(TAG, "Hard HTTP error " + ex.getCode(), ex);
                    syncResult.stats.numParseExceptions++;
                } else {
                    Log.w(TAG, "Soft HTTP error " + ex.getCode() + " (Android will try again later)", ex);
                    syncResult.stats.numIoExceptions++;
                }

            } catch (LocalStorageException ex) {
                syncResult.databaseError = true;
                Log.e(TAG, "Local storage (content provider) exception", ex);
            } catch (IOException ex) {
                syncResult.stats.numIoExceptions++;
                Log.e(TAG, "I/O error (Android will try again later)", ex);
            }
    } finally {
        // allow httpClient shutdown
        httpClientLock.readLock().unlock();
    }

    Log.i(TAG, "Sync complete for " + authority);
}

From source file:com.owncloud.android.syncadapter.FileSyncAdapter.java

/**
 * {@inheritDoc}/*from ww  w.j a va  2  s. c  o m*/
 */
@Override
public synchronized void onPerformSync(Account account, Bundle extras, String authority,
        ContentProviderClient providerClient, SyncResult syncResult) {

    mCancellation = false;
    mIsManualSync = extras.getBoolean(ContentResolver.SYNC_EXTRAS_MANUAL, false);
    mFailedResultsCounter = 0;
    mLastFailedResult = null;
    mConflictsFound = 0;
    mFailsInFavouritesFound = 0;
    mForgottenLocalFiles = new HashMap<String, String>();
    mSyncResult = syncResult;
    mSyncResult.fullSyncRequested = false;
    mSyncResult.delayUntil = 60 * 60 * 24; // avoid too many automatic synchronizations

    this.setAccount(account);
    this.setContentProviderClient(providerClient);
    this.setStorageManager(new FileDataStorageManager(account, providerClient));

    try {
        this.initClientForCurrentAccount();
    } catch (IOException e) {
        /// the account is unknown for the Synchronization Manager, unreachable this context,
        // or can not be authenticated; don't try this again
        mSyncResult.tooManyRetries = true;
        notifyFailedSynchronization();
        return;
    } catch (AccountsException e) {
        /// the account is unknown for the Synchronization Manager, unreachable this context,
        // or can not be authenticated; don't try this again
        mSyncResult.tooManyRetries = true;
        notifyFailedSynchronization();
        return;
    }

    Log_OC.d(TAG, "Synchronization of ownCloud account " + account.name + " starting");
    sendLocalBroadcast(EVENT_FULL_SYNC_START, null, null); // message to signal the start
                                                           // of the synchronization to the UI

    try {
        updateOCVersion();
        mCurrentSyncTime = System.currentTimeMillis();
        if (!mCancellation) {
            synchronizeFolder(getStorageManager().getFileByPath(OCFile.ROOT_PATH));

        } else {
            Log_OC.d(TAG, "Leaving synchronization before synchronizing the root folder "
                    + "because cancelation request");
        }

    } finally {
        // it's important making this although very unexpected errors occur;
        // that's the reason for the finally

        if (mFailedResultsCounter > 0 && mIsManualSync) {
            /// don't let the system synchronization manager retries MANUAL synchronizations
            //      (be careful: "MANUAL" currently includes the synchronization requested when
            //      a new account is created and when the user changes the current account)
            mSyncResult.tooManyRetries = true;

            /// notify the user about the failure of MANUAL synchronization
            notifyFailedSynchronization();
        }
        if (mConflictsFound > 0 || mFailsInFavouritesFound > 0) {
            notifyFailsInFavourites();
        }
        if (mForgottenLocalFiles.size() > 0) {
            notifyForgottenLocalFiles();
        }
        sendLocalBroadcast(EVENT_FULL_SYNC_END, null, mLastFailedResult); // message to signal
                                                                          // the end to the UI
    }

}

From source file:com.digitalarx.android.syncadapter.FileSyncAdapter.java

/**
 * {@inheritDoc}/*from  w w  w  . j a  va 2s.  co  m*/
 */
@Override
public synchronized void onPerformSync(Account account, Bundle extras, String authority,
        ContentProviderClient providerClient, SyncResult syncResult) {

    mCancellation = false;
    mIsManualSync = extras.getBoolean(ContentResolver.SYNC_EXTRAS_MANUAL, false);
    mFailedResultsCounter = 0;
    mLastFailedResult = null;
    mConflictsFound = 0;
    mFailsInFavouritesFound = 0;
    mForgottenLocalFiles = new HashMap<String, String>();
    mSyncResult = syncResult;
    mSyncResult.fullSyncRequested = false;
    mSyncResult.delayUntil = 60 * 60 * 24; // avoid too many automatic synchronizations

    this.setAccount(account);
    this.setContentProviderClient(providerClient);
    this.setStorageManager(new FileDataStorageManager(account, providerClient));

    try {
        this.initClientForCurrentAccount();
    } catch (IOException e) {
        /// the account is unknown for the Synchronization Manager, unreachable this context, or can not be authenticated; don't try this again
        mSyncResult.tooManyRetries = true;
        notifyFailedSynchronization();
        return;
    } catch (AccountsException e) {
        /// the account is unknown for the Synchronization Manager, unreachable this context, or can not be authenticated; don't try this again
        mSyncResult.tooManyRetries = true;
        notifyFailedSynchronization();
        return;
    }

    Log_OC.d(TAG, "Synchronization of ownCloud account " + account.name + " starting");
    sendLocalBroadcast(EVENT_FULL_SYNC_START, null, null); // message to signal the start of the synchronization to the UI

    try {
        updateOCVersion();
        mCurrentSyncTime = System.currentTimeMillis();
        if (!mCancellation) {
            synchronizeFolder(getStorageManager().getFileByPath(OCFile.ROOT_PATH));

        } else {
            Log_OC.d(TAG,
                    "Leaving synchronization before synchronizing the root folder because cancelation request");
        }

    } finally {
        // it's important making this although very unexpected errors occur; that's the reason for the finally

        if (mFailedResultsCounter > 0 && mIsManualSync) {
            /// don't let the system synchronization manager retries MANUAL synchronizations
            //      (be careful: "MANUAL" currently includes the synchronization requested when a new account is created and when the user changes the current account)
            mSyncResult.tooManyRetries = true;

            /// notify the user about the failure of MANUAL synchronization
            notifyFailedSynchronization();
        }
        if (mConflictsFound > 0 || mFailsInFavouritesFound > 0) {
            notifyFailsInFavourites();
        }
        if (mForgottenLocalFiles.size() > 0) {
            notifyForgottenLocalFiles();
        }
        sendLocalBroadcast(EVENT_FULL_SYNC_END, null, mLastFailedResult); // message to signal the end to the UI
    }

}

From source file:com.granita.icloudcalsync.syncadapter.DavSyncAdapter.java

@TargetApi(Build.VERSION_CODES.JELLY_BEAN)
@Override/*  w w w  . j a v  a  2s  .co m*/
public void onPerformSync(Account account, Bundle extras, String authority, ContentProviderClient provider,
        SyncResult syncResult) {
    Log.i(TAG, "Performing sync for authority " + authority);

    // set class loader for iCal4j ResourceLoader
    Thread.currentThread().setContextClassLoader(getContext().getClassLoader());

    // create httpClient, if necessary
    httpClientLock.writeLock().lock();
    if (httpClient == null) {
        Log.d(TAG, "Creating new DavHttpClient");
        SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(getContext());
        httpClient = DavHttpClient.create();
    }

    // prevent httpClient shutdown until we're ready by holding a read lock
    // acquiring read lock before releasing write lock will downgrade the write lock to a read lock
    httpClientLock.readLock().lock();
    httpClientLock.writeLock().unlock();

    // TODO use VCard 4.0 if possible
    AccountSettings accountSettings = new AccountSettings(getContext(), account);
    Log.d(TAG, "Server supports VCard version " + accountSettings.getAddressBookVCardVersion());

    Exception exceptionToShow = null; // exception to show notification for
    Intent exceptionIntent = null; // what shall happen when clicking on the exception notification
    try {
        // get local <-> remote collection pairs
        Map<LocalCollection<?>, RemoteCollection<?>> syncCollections = getSyncPairs(account, provider);
        if (syncCollections == null)
            Log.i(TAG, "Nothing to synchronize");
        else
            try {
                for (Map.Entry<LocalCollection<?>, RemoteCollection<?>> entry : syncCollections.entrySet())
                    new SyncManager(entry.getKey(), entry.getValue())
                            .synchronize(extras.containsKey(ContentResolver.SYNC_EXTRAS_MANUAL), syncResult);

            } catch (DavException ex) {
                syncResult.stats.numParseExceptions++;
                Log.e(TAG, "Invalid DAV response", ex);
                exceptionToShow = ex;

            } catch (HttpException ex) {
                if (ex.getCode() == HttpStatus.SC_UNAUTHORIZED) {
                    Log.e(TAG, "HTTP Unauthorized " + ex.getCode(), ex);
                    syncResult.stats.numAuthExceptions++; // hard error

                    exceptionToShow = ex;
                    exceptionIntent = new Intent(context, AccountActivity.class);
                    exceptionIntent.putExtra(AccountActivity.EXTRA_ACCOUNT, account);
                } else if (ex.isClientError()) {
                    Log.e(TAG, "Hard HTTP error " + ex.getCode(), ex);
                    syncResult.stats.numParseExceptions++; // hard error
                    exceptionToShow = ex;
                } else {
                    Log.w(TAG, "Soft HTTP error " + ex.getCode() + " (Android will try again later)", ex);
                    syncResult.stats.numIoExceptions++; // soft error
                }
            } catch (LocalStorageException ex) {
                syncResult.databaseError = true; // hard error
                Log.e(TAG, "Local storage (content provider) exception", ex);
                exceptionToShow = ex;
            } catch (IOException ex) {
                syncResult.stats.numIoExceptions++; // soft error
                Log.e(TAG, "I/O error (Android will try again later)", ex);
                if (ex instanceof SSLException) // always notify on SSL/TLS errors
                    exceptionToShow = ex;
            } catch (URISyntaxException ex) {
                syncResult.stats.numParseExceptions++; // hard error
                Log.e(TAG, "Invalid URI (file name) syntax", ex);
                exceptionToShow = ex;
            }
    } finally {
        // allow httpClient shutdown
        httpClientLock.readLock().unlock();
    }

    // show sync errors as notification
    if (exceptionToShow != null && Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
        if (exceptionIntent == null)
            exceptionIntent = new Intent(Intent.ACTION_VIEW, Uri.parse(Constants.WEB_URL_VIEW_LOGS));

        PendingIntent contentIntent = PendingIntent.getActivity(context, 0, exceptionIntent, 0);
        Notification.Builder builder = new Notification.Builder(context).setSmallIcon(R.drawable.ic_launcher)
                .setPriority(Notification.PRIORITY_LOW).setOnlyAlertOnce(true)
                .setWhen(System.currentTimeMillis())
                .setContentTitle(context.getString(R.string.sync_error_title))
                .setContentText(exceptionToShow.getLocalizedMessage()).setContentInfo(account.name)
                .setStyle(new Notification.BigTextStyle()
                        .bigText(account.name + ":\n" + ExceptionUtils.getFullStackTrace(exceptionToShow)))
                .setContentIntent(contentIntent);

        NotificationManager notificationManager = (NotificationManager) context
                .getSystemService(Context.NOTIFICATION_SERVICE);
        notificationManager.notify(account.name.hashCode(), builder.build());
    }

    Log.i(TAG, "Sync complete for " + authority);
}

From source file:org.codarama.haxsync.activities.WelcomeActivity.java

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    switch (item.getItemId()) {
    case R.id.nav_home: {
        // Create fragment and give it an argument specifying the article it should show
        HomeFragment newFragment = new HomeFragment();
        FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();

        // Replace whatever is in the fragment_container view with this fragment,
        // and add the transaction to the back stack so the user can navigate back
        transaction.replace(R.id.fragment_container, newFragment);
        transaction.addToBackStack(null);

        // Commit the transaction
        transaction.commit();/*from ww w .j av  a 2s.c  om*/
        return true;
    }

    case R.id.nav_settings: {
        Intent preferences = new Intent(getApplicationContext(), PreferencesActivity.class);
        startActivity(preferences);
        return true;
    }

    // as per https://developer.android.com/training/sync-adapters/running-sync-adapter.html
    // we might want to reconsider allowing manual sync - the basic flaw in this design is
    // that the user could not be trusted to know when it is the best time to sync
    case R.id.nav_manual_sync: {
        Log.d(TAG, "User requested manual sync");
        SyncAccount syncAccount = new SyncAccount(AccountManager.get(WelcomeActivity.this));
        Account account = syncAccount.getHaxSyncAccount(getResources().getString(R.string.ACCOUNT_TYPE));

        // Pass the settings flags by inserting them in a bundle
        Bundle settingsBundle = new Bundle();
        settingsBundle.putBoolean(ContentResolver.SYNC_EXTRAS_MANUAL, true);
        settingsBundle.putBoolean(ContentResolver.SYNC_EXTRAS_EXPEDITED, true);

        ContentResolver.requestSync(account, "com.android.contacts", settingsBundle);
        ContentResolver.requestSync(account, "com.android.calendar", settingsBundle);
        return true;
    }

    default: {
        // If we got here, the user's action was not recognized.
        // Invoke the superclass to handle it.
        return super.onOptionsItemSelected(item);
    }
    }
}