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:org.exfio.weavedroid.syncadapter.WeaveSyncAdapter.java

@Override
public void onPerformSync(Account account, Bundle extras, String authority, ContentProviderClient provider,
        SyncResult syncResult) {/*from  w ww.  j ava2s . c  om*/
    Log.i(TAG, "Performing sync for authority " + authority);

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

    AccountSettings settings = new AccountSettings(getContext(), account);

    //TODO - handle user defined Weave Storage version

    //DEBUG only
    if (SystemUtils.isDebuggable(getContext())) {
        org.exfio.weavedroid.util.Log.init("debug");
    }

    Log.d(TAG, String.format("Weave credentials - username: %s, password: %s, synckey: %s",
            settings.getUserName(), settings.getPassword(), settings.getSyncKey()));

    //get weave account params
    WeaveClientV5Params params = new WeaveClientV5Params();
    params.baseURL = settings.getBaseURL();
    params.user = settings.getUserName();
    params.password = settings.getPassword();
    params.syncKey = settings.getSyncKey();

    //TODO - validate weave account settings
    if (params.baseURL == null) {
        Log.e(TAG, "Weave account settings invalid");
        return;
    }

    //Initialise weave client
    try {
        weaveClient = WeaveClientFactory.getInstance(params);
    } catch (WeaveException e) {
        Log.e(TAG, e.getMessage());
        closeWeaveClient();
        return;
    }

    Log.i(TAG, String.format("Checking messages"));

    Message[] messages = null;

    try {

        //Initialise sqldroid jdbc provider
        Class.forName("org.sqldroid.SQLDroidDriver");
        String databasePath = getContext().getDatabasePath(settings.getGuid()).getAbsolutePath();

        Log.d(TAG, String.format("Database path: %s", databasePath));

        ClientAuth auth = new ClientAuth(weaveClient, databasePath);

        String curStatus = auth.getAuthStatus();
        messages = auth.processClientAuthMessages();
        String newStatus = auth.getAuthStatus();

        if (curStatus != null && curStatus.equals("pending")) {

            //If client has been authorised update configuration
            if (newStatus.equals("authorised")) {
                //Update synckey, re-initialise weave client and notify user clientauth request approved

                Log.i(TAG, String.format("Client auth request approved by '%s'", auth.getAuthBy()));

                accountManager.setPassword(account,
                        AccountSettings.encodePassword(settings.getPassword(), auth.getSyncKey()));

                params.syncKey = auth.getSyncKey();
                weaveClient.init(params);

                //Notify user that clientauth request has been approved
                displayNotificationApprovedClientAuth(account.name, auth.getAuthBy());

            } else if (newStatus.equals("pending")) {
                //Client not yet authenticated

                Log.i(TAG, String.format("Client auth request pending with authcode '%s'", auth.getAuthCode()));

                //Notify user of the authcode to be entered in authorising device
                displayNotificationPendingClientAuth(account.name, auth.getAuthCode());

                return;
            }
        }

    } catch (Exception e) {
        Log.e(TAG, String.format("%s - %s", e.getClass().getName(), e.getMessage()));
        return;
    }

    Log.d(TAG, String.format("Processing %d pending client auth request messages", messages.length));

    for (Message msg : messages) {
        ClientAuthRequestMessage caMsg = (ClientAuthRequestMessage) msg;

        Log.i(TAG,
                String.format("Client auth request pending approval for client '%s'", caMsg.getClientName()));

        //Notify user that a clientauth request is waiting for approval
        displayNotificationReceivedClientAuth(account.name, caMsg);
    }

    //getSyncPairs() overridden by implementing classes, i.e. ContactsSyncAdapter 
    Map<LocalCollection<?>, WeaveCollection<?>> syncCollections = null;
    try {
        syncCollections = getSyncPairs(account, provider, weaveClient);
    } catch (WeaveException e) {
        Log.e(TAG, e.getMessage());
        closeWeaveClient();
        return;
    }

    if (syncCollections == null)
        Log.i(TAG, "Nothing to synchronize");
    else {
        try {
            // prevent weave http client shutdown until we're ready
            weaveClient.lock();

            for (Map.Entry<LocalCollection<?>, WeaveCollection<?>> entry : syncCollections.entrySet())
                new SyncManager(entry.getKey(), entry.getValue())
                        .synchronize(extras.containsKey(ContentResolver.SYNC_EXTRAS_MANUAL), syncResult);

        } catch (WeaveException ex) {
            syncResult.stats.numParseExceptions++;
            Log.e(TAG, "Invalid Weave response", ex);

            //FIXME - log sync status

            //         } 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 {
            // close weave http client
            weaveClient.unlock();
            closeWeaveClient();
        }
    }
}

From source file:com.hybris.mobile.app.commerce.CommerceApplicationBase.java

/**
 * Request a sync of the catalog sync adapter
 *
 * @param bundle/*from   w w w  .  java 2s. c o  m*/
 */
public static void requestCatalogSyncAdapter(Bundle bundle) {
    bundle.putBoolean(ContentResolver.SYNC_EXTRAS_MANUAL, true);
    bundle.putBoolean(ContentResolver.SYNC_EXTRAS_EXPEDITED, true);
    ContentResolver.requestSync(
            new Account(mInstance.getString(R.string.account_name), mInstance.getString(R.string.account_type)),
            mInstance.getString(R.string.provider_authority), bundle);
}

From source file:com.beesham.popularmovies.sync.MoviesSyncAdapter.java

public static void syncImmediately(Context context) {
    Bundle b = new Bundle();
    b.putBoolean(ContentResolver.SYNC_EXTRAS_EXPEDITED, true);
    b.putBoolean(ContentResolver.SYNC_EXTRAS_MANUAL, true);

    ContentResolver.requestSync(getSyncAccount(context), context.getString(R.string.content_authority), b);
}

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

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    BaseSection currentSection = pagerAdapter.getSection(getSupportActionBar().getSelectedTab().getPosition());
    switch (item.getItemId()) {
    case R.id.action_refresh: {
        if (currentSection.isRefreshActive()) {
            currentSection.onRefreshPressed();
        }/*  w ww  .ja  v a  2 s.c  o  m*/
        break;
    }
    case android.R.id.home: {
        if (currentSection.isBackActive()) {
            currentSection.onBackPressed();
        }
        break;
    }
    case R.id.action_settings: {
        Intent intent = new Intent(this, SettingsActivity.class);
        startActivity(intent);
        break;
    }
    case R.id.action_about: {
        Intent intent = new Intent(this, AboutActivity.class);
        startActivity(intent);
        break;
    }
    case R.id.action_synchronise: {
        Toast.makeText(this, "Rozpoczynanie synchronizacji.", Toast.LENGTH_LONG).show();

        Bundle extras = new Bundle();
        extras.putBoolean(ContentResolver.SYNC_EXTRAS_EXPEDITED, true);
        extras.putBoolean(ContentResolver.SYNC_EXTRAS_MANUAL, true);
        extras.putBoolean("config", true);
        extras.putBoolean("replacements", true);
        extras.putBoolean("timetables", true);

        ContentResolver.requestSync(account, AUTHORITY, extras);
        break;
    }
    }

    return false;
}

From source file:com.gaba.alex.trafficincidents.MainActivity.java

private void refresh() {
    Bundle settingsBundle = new Bundle();
    settingsBundle.putBoolean(ContentResolver.SYNC_EXTRAS_MANUAL, true);
    settingsBundle.putBoolean(ContentResolver.SYNC_EXTRAS_EXPEDITED, true);
    ContentResolver.requestSync(mAccount, AUTHORITY, settingsBundle);
}

From source file:com.jasonmheim.rollout.station.CoreContentProvider.java

@Override
public Cursor query(Uri uri, String[] projection, String selection, String[] selectionArgs, String sortOrder) {

    StationDataCursor cursor = new StationDataCursor();
    if (stationList == null) {
        Log.i("Rollout", "Provider not yet initialized, checking local storage...");
        stationList = stationDataStorage.get();
    }/*  w  ww .j ava 2  s . com*/
    if (stationList == null) {
        Log.i("Rollout", "Local storage was empty.");
        Future<StationList> future = executorService.submit(stationListDownloader);
        try {
            StationList providerList = future.get();
            if (providerList == null) {
                Log.i("Rollout", "Station list failed to download from query, requesting sync");
                Bundle settingsBundle = new Bundle();
                settingsBundle.putBoolean(ContentResolver.SYNC_EXTRAS_MANUAL, true);
                settingsBundle.putBoolean(ContentResolver.SYNC_EXTRAS_EXPEDITED, true);
                ContentResolver.requestSync(ACCOUNT, AUTHORITY, settingsBundle);
            } else {
                Log.i("Rollout", "Direct download succeeded.");
                // This implicitly sets stationList
                internalInsert(providerList);
            }
        } catch (InterruptedException ex) {
            Log.w("Rollout", "Content provider sync was interrupted", ex);
        } catch (ExecutionException ex) {
            Log.w("Rollout", "Content provider sync execution failed", ex);
        }
    }
    if (stationList != null) {
        cursor.setStationDataJson(gson.toJson(stationList));
    }
    cursor.setNotificationUri(getContext().getContentResolver(), Constants.STATION_URI);
    return cursor;
}

From source file:de.stkl.gbgvertretungsplan.fragments.MainFragment.java

public void actionRefresh() {
    // only if neither pending nor active
    if (!ContentResolver.isSyncActive(((MainActivity) getActivity()).mDefaultAccount,
            getString(Account.CONTENT_AUTHORITY))
            && !ContentResolver.isSyncPending(((MainActivity) getActivity()).mDefaultAccount,
                    getString(Account.CONTENT_AUTHORITY))) {
        Bundle settingsBundle = new Bundle();
        settingsBundle.putBoolean(ContentResolver.SYNC_EXTRAS_MANUAL, true); // this is a manual sync
        settingsBundle.putBoolean(ContentResolver.SYNC_EXTRAS_EXPEDITED, true); // start immediately
        ContentResolver.requestSync(Authenticator.getDefaultAccount(getActivity()),
                getString(Account.CONTENT_AUTHORITY), settingsBundle);
    }/*from   w ww.  j av  a2 s. com*/
}

From source file:p1.nd.khan.jubair.mohammadd.popularmovies.sync.MovieSyncAdapter.java

/**
 * Method to load more data based on scrolling.
 *
 * @param context The context used to load more movie.
 * @param offset  page number to request/load the data.
 *///from   ww  w  . j ava2s  .  c o m
public static void loadMoreData(Context context, int offset) {
    //Log.v("LOG_TAG","loadMoreData:"+offset);
    Bundle bundle = new Bundle();
    bundle.putBoolean(ContentResolver.SYNC_EXTRAS_EXPEDITED, true);
    bundle.putBoolean(ContentResolver.SYNC_EXTRAS_MANUAL, true);
    bundle.putInt("page", offset);
    ContentResolver.requestSync(getSyncAccount(context), context.getString(R.string.content_authority), bundle);
}

From source file:org.gots.ui.BaseGotsActivity.java

protected void onRefresh(String AUTHORITY) {
    if (AUTHORITY == null || "".equals(AUTHORITY)) {
        Log.d(TAG, "You call onRefresh without Content Resolver Authority");
        return;//  www. j  a v  a  2s.co m
    }
    Account userAccount = gotsPrefs.getUserAccount();
    ContentResolver.setSyncAutomatically(userAccount, AUTHORITY, true);
    Bundle bundle = new Bundle();
    bundle.putBoolean(ContentResolver.SYNC_EXTRAS_EXPEDITED, true);
    bundle.putBoolean(ContentResolver.SYNC_EXTRAS_MANUAL, true);
    ContentResolver.requestSync(userAccount, AUTHORITY, bundle);
}

From source file:com.sintef_energy.ubisolar.activities.DrawerActivity.java

@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    Session.getActiveSession().onActivityResult(this, requestCode, resultCode, data);

    if (requestCode == LOGIN_CALL_ID) {
        if (resultCode == Activity.RESULT_OK) {
            Log.v(TAG, "Login was successful. Starting to attain session data.");

            startFacebookLogin(null);/*from w  w w  .java 2  s. c  o  m*/

            // Find the account
            Account[] accounts = getAccounts(getApplicationContext(), ACCOUNT_TYPE);
            for (Account account : accounts) {
                if (account.name.equals(data.getStringExtra(AccountManager.KEY_ACCOUNT_NAME))) {
                    mAccount = account;
                    break;
                }
            }

            if (mAccount == null) {
                Log.e(TAG, "Account creation somehow failed to make an account.");
                return;
            }

            /* The same as ticking allow sync */
            ContentResolver.setSyncAutomatically(mAccount, AUTHORITY_PROVIDER, true);

            /* Request a sync operation */
            Bundle bundle = new Bundle();
            bundle.putBoolean(ContentResolver.SYNC_EXTRAS_MANUAL, true); //Do sync regardless of settings
            bundle.putBoolean(ContentResolver.SYNC_EXTRAS_EXPEDITED, true); //Force sync immediately
            ContentResolver.requestSync(mAccount, AUTHORITY_PROVIDER, bundle);

            /* Update all -1 users to the current user id. */
            AccountManager accountManager = (AccountManager) getApplicationContext()
                    .getSystemService(ACCOUNT_SERVICE);

            String facebookUID = accountManager.getUserData(mAccount, Global.DATA_FB_UID);

            ContentValues values = new ContentValues();
            values.put(DeviceModel.DeviceEntry.COLUMN_USER_ID, facebookUID);
            values.put(DeviceModel.DeviceEntry.COLUMN_LAST_UPDATED, System.currentTimeMillis() / 1000L);

            getContentResolver().update(EnergyContract.Devices.CONTENT_URI, values,
                    EnergyContract.Devices.COLUMN_USER_ID + "=?", new String[] { "-1" });

            //Publish a post saying you started using Wattitude
            RequestManager.getInstance().doFriendRequest().createWallPost(
                    new NewsFeedPost(0, Long.valueOf(facebookUID), 1, System.currentTimeMillis() / 1000), null);
        } else {
            Log.v(TAG, "Login failed");
        }
    }
}