Example usage for android.content ContentResolver setSyncAutomatically

List of usage examples for android.content ContentResolver setSyncAutomatically

Introduction

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

Prototype

public static void setSyncAutomatically(Account account, String authority, boolean sync) 

Source Link

Document

Set whether or not the provider is synced when it receives a network tickle.

Usage

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

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

    // Make sure this user has an unique device identifier.
    final boolean newUserSet = !prefs.contains(SP_KEY_DEVICE_ID) || !newAccount.equals(oldAccount);
    if (newUserSet) {
        prefsEditor.putString(SP_KEY_DEVICE_ID, DeviceUtils.getDeviceId(fragment.getActivity(), newAccount));
    }/*from   ww w  .  jav a2  s .co m*/

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

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

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

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

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

        prefsEditor.putString(SP_KEY_ACCOUNT, newAccount);

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

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

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

    return authResult;
}

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

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

From source file:me.philio.ghost.ui.LoginActivity.java

@Override
public void onSuccess(String email, String password, Token token, User user) {
    // Create the account
    Account account = new Account(AccountUtils.getName(mBlogUrl, email), getString(R.string.account_type));
    Bundle userdata = new Bundle();
    userdata.putString(KEY_BLOG_URL, mBlogUrl);
    userdata.putString(KEY_EMAIL, email);
    userdata.putString(KEY_ACCESS_TOKEN_TYPE, token.tokenType);
    userdata.putString(KEY_ACCESS_TOKEN_EXPIRES,
            Long.toString(System.currentTimeMillis() + (token.expires * 1000)));

    // Add account to the system
    AccountManager accountManager = AccountManager.get(this);
    accountManager.addAccountExplicitly(account, password, userdata);

    // Set the account auth tokens
    accountManager.setAuthToken(account, TOKEN_TYPE_ACCESS, token.accessToken);
    accountManager.setAuthToken(account, TOKEN_TYPE_REFRESH, token.refreshToken);

    // Create initial database records
    Blog blog = new Blog();
    blog.url = mBlogUrl;/*  ww  w .j  a  v  a2s . com*/
    blog.email = email;
    user.blog = blog;
    ActiveAndroid.beginTransaction();
    try {
        blog.save();
        user.save();
        ActiveAndroid.setTransactionSuccessful();
    } finally {
        ActiveAndroid.endTransaction();
    }

    // Enable sync for the account
    ContentResolver.setSyncAutomatically(account, getString(R.string.content_authority), true);
    SyncHelper.requestSync(account, getString(R.string.content_authority));

    // Set response intent
    Intent intent = new Intent();
    intent.putExtra(AccountManager.KEY_ACCOUNT_NAME, account.name);
    intent.putExtra(AccountManager.KEY_ACCOUNT_TYPE, account.type);
    setAccountAuthenticatorResult(intent.getExtras());
    setResult(RESULT_OK, intent);
    finish();
}

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

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

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

public static void autoSyncOn(Account account, String authority) {
    if (DEBUG) {//from  w w w.  java 2  s  .c  o  m
        Log.d(LOG_TAG, "sync on " + account + ", " + authority);
        Log.d(LOG_TAG, "previous " + ContentResolver.getSyncAutomatically(account, authority));
    }
    ContentResolver.setSyncAutomatically(account, authority, true);
    if (DEBUG) {
        Log.d("syncsettings", "now " + ContentResolver.getSyncAutomatically(account, authority));
    }
}

From source file:com.nextgis.woody.activity.MainActivity.java

@Override
public void onAddAccount(Account account, String token, boolean accountAdded) {
    Log.d(Constants.WTAG, "No account. " + Constants.ACCOUNT_NAME + " created. Run first step.");

    if (accountAdded) {
        // TODO: final SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);

        final MainApplication app = (MainApplication) getApplication();
        app.setUserData(account.name, Constants.KEY_IS_AUTHORIZED, token);

        //set sync with server
        ContentResolver.setSyncAutomatically(account, app.getAuthority(), true);
        ContentResolver.addPeriodicSync(account, app.getAuthority(), Bundle.EMPTY,
                com.nextgis.maplib.util.Constants.DEFAULT_SYNC_PERIOD);

        // goto step 2
        refreshActivityView();//from ww  w .j  a va 2 s. co  m
    } else
        Toast.makeText(this, R.string.error_init, Toast.LENGTH_SHORT).show();
}

From source file:ie.clashoftheash.timetabler.ui.SettingsActivity.java

@Override
public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) {
    if (key.equals(prefKeyProgrammeCode) || key.equals(prefKeyYear)) {
        // Update account
        String programme = sharedPreferences.getString(prefKeyProgrammeCode,
                AccountUtils.getProgrammeCode(this));
        String year = sharedPreferences.getString(prefKeyYear, AccountUtils.getYear(this));

        new AccountUtils(this).updateAccount(programme, year);
    } else if (key.equals(prefKeyFreq)) {
        long pollFrequency = getSyncFreqPref();

        Account acc = AccountUtils.getAccount(this);
        String authority = Timetable.AUTHORITY;

        if (pollFrequency > 0) {
            ContentResolver.setSyncAutomatically(acc, authority, true);

            ContentResolver.addPeriodicSync(acc, authority, new Bundle(), pollFrequency);
        } else {/*from   w w w.  j  a va2 s.  c  o  m*/
            ContentResolver.setSyncAutomatically(acc, authority, false);

            ContentResolver.removePeriodicSync(acc, authority, new Bundle());
        }
    }
}

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

public static void autoSyncOff(Account account, String authority) {
    if (DEBUG) {// www. ja va2s .c o m
        Log.d(LOG_TAG, "sync off " + account + ", " + authority);
        Log.d(LOG_TAG, "previous " + ContentResolver.getSyncAutomatically(account, authority));
    }
    ContentResolver.setSyncAutomatically(account, authority, false);
    if (DEBUG) {
        Log.d("syncsettings", "now " + ContentResolver.getSyncAutomatically(account, authority));
    }
}

From source file:com.jackie.sunshine.app.sync.SunshineSyncAdapter.java

public static void onAccountCreated(Account newAccount, Context context) {
    /*//from   w ww  .  j a  v  a2 s  . co  m
     * Since we've created an account
     */
    configurePeriodicSync(context, SYNC_INTERVAL, SYNC_FLEXTIME);

    /*
     * Without calling setSyncAutomatically, our periodic sync will not be enabled.
     */
    ContentResolver.setSyncAutomatically(newAccount, context.getString(R.string.content_authority), true);

    /**
     * Finally, let's do a sync to get things started
     */
    syncImmediately(context);
}

From source file:com.jefftharris.passwdsafe.sync.gdrive.GDriveProvider.java

@Override
public void updateSyncFreq(Account acct, int freq) {
    if (acct != null) {
        ContentResolver.removePeriodicSync(acct, PasswdSafeContract.AUTHORITY, new Bundle());
        ContentResolver.setSyncAutomatically(acct, PasswdSafeContract.AUTHORITY, false);
        if (freq > 0) {
            ContentResolver.setSyncAutomatically(acct, PasswdSafeContract.AUTHORITY, true);
            ContentResolver.addPeriodicSync(acct, PasswdSafeContract.AUTHORITY, new Bundle(), freq);
        }/* ww w.  j  a  v a  2  s.  c  o m*/
    }
}