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:github.daneren2005.dsub.fragments.SettingsFragment.java

@Override
protected void onInitPreferences(PreferenceScreen preferenceScreen) {
    this.setTitle(preferenceScreen.getTitle());

    internalSSID = Util.getSSID(context);
    if (internalSSID == null) {
        internalSSID = "";
    }//from  w w w . j av  a2  s .  co  m
    internalSSIDDisplay = context.getResources().getString(R.string.settings_server_local_network_ssid_hint,
            internalSSID);

    theme = (ListPreference) this.findPreference(Constants.PREFERENCES_KEY_THEME);
    maxBitrateWifi = (ListPreference) this.findPreference(Constants.PREFERENCES_KEY_MAX_BITRATE_WIFI);
    maxBitrateMobile = (ListPreference) this.findPreference(Constants.PREFERENCES_KEY_MAX_BITRATE_MOBILE);
    maxVideoBitrateWifi = (ListPreference) this
            .findPreference(Constants.PREFERENCES_KEY_MAX_VIDEO_BITRATE_WIFI);
    maxVideoBitrateMobile = (ListPreference) this
            .findPreference(Constants.PREFERENCES_KEY_MAX_VIDEO_BITRATE_MOBILE);
    networkTimeout = (ListPreference) this.findPreference(Constants.PREFERENCES_KEY_NETWORK_TIMEOUT);
    cacheLocation = (CacheLocationPreference) this.findPreference(Constants.PREFERENCES_KEY_CACHE_LOCATION);
    preloadCountWifi = (ListPreference) this.findPreference(Constants.PREFERENCES_KEY_PRELOAD_COUNT_WIFI);
    preloadCountMobile = (ListPreference) this.findPreference(Constants.PREFERENCES_KEY_PRELOAD_COUNT_MOBILE);
    keepPlayedCount = (ListPreference) this.findPreference(Constants.PREFERENCES_KEY_KEEP_PLAYED_CNT);
    tempLoss = (ListPreference) this.findPreference(Constants.PREFERENCES_KEY_TEMP_LOSS);
    pauseDisconnect = (ListPreference) this.findPreference(Constants.PREFERENCES_KEY_PAUSE_DISCONNECT);
    serversCategory = (PreferenceCategory) this.findPreference(Constants.PREFERENCES_KEY_SERVER_KEY);
    addServerPreference = this.findPreference(Constants.PREFERENCES_KEY_SERVER_ADD);
    videoPlayer = (ListPreference) this.findPreference(Constants.PREFERENCES_KEY_VIDEO_PLAYER);
    songPressAction = (ListPreference) this.findPreference(Constants.PREFERENCES_KEY_SONG_PRESS_ACTION);
    syncInterval = (ListPreference) this.findPreference(Constants.PREFERENCES_KEY_SYNC_INTERVAL);
    syncEnabled = (CheckBoxPreference) this.findPreference(Constants.PREFERENCES_KEY_SYNC_ENABLED);
    syncWifi = (CheckBoxPreference) this.findPreference(Constants.PREFERENCES_KEY_SYNC_WIFI);
    syncNotification = (CheckBoxPreference) this.findPreference(Constants.PREFERENCES_KEY_SYNC_NOTIFICATION);
    syncStarred = (CheckBoxPreference) this.findPreference(Constants.PREFERENCES_KEY_SYNC_STARRED);
    syncMostRecent = (CheckBoxPreference) this.findPreference(Constants.PREFERENCES_KEY_SYNC_MOST_RECENT);
    replayGain = (CheckBoxPreference) this.findPreference(Constants.PREFERENCES_KEY_REPLAY_GAIN);
    replayGainType = (ListPreference) this.findPreference(Constants.PREFERENCES_KEY_REPLAY_GAIN_TYPE);
    replayGainBump = this.findPreference(Constants.PREFERENCES_KEY_REPLAY_GAIN_BUMP);
    replayGainUntagged = this.findPreference(Constants.PREFERENCES_KEY_REPLAY_GAIN_UNTAGGED);
    cacheSize = (EditTextPreference) this.findPreference(Constants.PREFERENCES_KEY_CACHE_SIZE);
    openToTab = (ListPreference) this.findPreference(Constants.PREFERENCES_KEY_OPEN_TO_TAB);

    settings = Util.getPreferences(context);
    serverCount = settings.getInt(Constants.PREFERENCES_KEY_SERVER_COUNT, 1);

    if (cacheSize != null) {
        this.findPreference("clearCache")
                .setOnPreferenceClickListener(new Preference.OnPreferenceClickListener() {
                    @Override
                    public boolean onPreferenceClick(Preference preference) {
                        Util.confirmDialog(context, R.string.common_delete,
                                R.string.common_confirm_message_cache, new DialogInterface.OnClickListener() {
                                    @Override
                                    public void onClick(DialogInterface dialog, int which) {
                                        new LoadingTask<Void>(context, false) {
                                            @Override
                                            protected Void doInBackground() throws Throwable {
                                                FileUtil.deleteMusicDirectory(context);
                                                FileUtil.deleteSerializedCache(context);
                                                FileUtil.deleteArtworkCache(context);
                                                FileUtil.deleteAvatarCache(context);
                                                return null;
                                            }

                                            @Override
                                            protected void done(Void result) {
                                                Util.toast(context, R.string.settings_cache_clear_complete);
                                            }

                                            @Override
                                            protected void error(Throwable error) {
                                                Util.toast(context, getErrorMessage(error), false);
                                            }
                                        }.execute();
                                    }
                                });
                        return false;
                    }
                });
    }

    if (syncEnabled != null) {
        this.findPreference(Constants.PREFERENCES_KEY_SYNC_ENABLED)
                .setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener() {
                    @Override
                    public boolean onPreferenceChange(Preference preference, Object newValue) {
                        Boolean syncEnabled = (Boolean) newValue;

                        Account account = new Account(Constants.SYNC_ACCOUNT_NAME, Constants.SYNC_ACCOUNT_TYPE);
                        ContentResolver.setSyncAutomatically(account, Constants.SYNC_ACCOUNT_PLAYLIST_AUTHORITY,
                                syncEnabled);
                        ContentResolver.setSyncAutomatically(account, Constants.SYNC_ACCOUNT_PODCAST_AUTHORITY,
                                syncEnabled);

                        return true;
                    }
                });
        syncInterval.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener() {
            @Override
            public boolean onPreferenceChange(Preference preference, Object newValue) {
                Integer syncInterval = Integer.parseInt(((String) newValue));

                Account account = new Account(Constants.SYNC_ACCOUNT_NAME, Constants.SYNC_ACCOUNT_TYPE);
                ContentResolver.addPeriodicSync(account, Constants.SYNC_ACCOUNT_PLAYLIST_AUTHORITY,
                        new Bundle(), 60L * syncInterval);
                ContentResolver.addPeriodicSync(account, Constants.SYNC_ACCOUNT_PODCAST_AUTHORITY, new Bundle(),
                        60L * syncInterval);

                return true;
            }
        });
    }

    if (serversCategory != null) {
        addServerPreference.setOnPreferenceClickListener(new Preference.OnPreferenceClickListener() {
            @Override
            public boolean onPreferenceClick(Preference preference) {
                serverCount++;
                int instance = serverCount;
                serversCategory.addPreference(addServer(serverCount));

                SharedPreferences.Editor editor = settings.edit();
                editor.putInt(Constants.PREFERENCES_KEY_SERVER_COUNT, serverCount);
                // Reset set folder ID
                editor.putString(Constants.PREFERENCES_KEY_MUSIC_FOLDER_ID + instance, null);
                editor.putString(Constants.PREFERENCES_KEY_SERVER_URL + instance, "http://yourhost");
                editor.putString(Constants.PREFERENCES_KEY_SERVER_NAME + instance,
                        getResources().getString(R.string.settings_server_unused));
                editor.commit();

                ServerSettings ss = new ServerSettings(instance);
                serverSettings.put(String.valueOf(instance), ss);
                ss.update();

                return true;
            }
        });

        serversCategory.setOrderingAsAdded(false);
        for (int i = 1; i <= serverCount; i++) {
            serversCategory.addPreference(addServer(i));
            serverSettings.put(String.valueOf(i), new ServerSettings(i));
        }
    }

    SharedPreferences prefs = Util.getPreferences(context);
    prefs.registerOnSharedPreferenceChangeListener(this);

    update();
}

From source file:github.popeen.dsub.fragments.SettingsFragment.java

@Override
protected void onInitPreferences(PreferenceScreen preferenceScreen) {
    this.setTitle(preferenceScreen.getTitle());

    internalSSID = Util.getSSID(context);
    if (internalSSID == null) {
        internalSSID = "";
    }//  w  w w  . j  a  v a  2s. c om
    internalSSIDDisplay = context.getResources().getString(R.string.settings_server_local_network_ssid_hint,
            internalSSID);

    theme = (ListPreference) this.findPreference(Constants.PREFERENCES_KEY_THEME);
    maxBitrateWifi = (ListPreference) this.findPreference(Constants.PREFERENCES_KEY_MAX_BITRATE_WIFI);
    maxBitrateMobile = (ListPreference) this.findPreference(Constants.PREFERENCES_KEY_MAX_BITRATE_MOBILE);
    ;
    //maxVideoBitrateWifi = (ListPreference) this.findPreference(Constants.PREFERENCES_KEY_MAX_VIDEO_BITRATE_WIFI);
    //maxVideoBitrateMobile = (ListPreference) this.findPreference(Constants.PREFERENCES_KEY_MAX_VIDEO_BITRATE_MOBILE);
    networkTimeout = (ListPreference) this.findPreference(Constants.PREFERENCES_KEY_NETWORK_TIMEOUT);
    cacheLocation = (CacheLocationPreference) this.findPreference(Constants.PREFERENCES_KEY_CACHE_LOCATION);
    preloadCountWifi = (ListPreference) this.findPreference(Constants.PREFERENCES_KEY_PRELOAD_COUNT_WIFI);
    preloadCountMobile = (ListPreference) this.findPreference(Constants.PREFERENCES_KEY_PRELOAD_COUNT_MOBILE);
    keepPlayedCount = (ListPreference) this.findPreference(Constants.PREFERENCES_KEY_KEEP_PLAYED_CNT);
    tempLoss = (ListPreference) this.findPreference(Constants.PREFERENCES_KEY_TEMP_LOSS);
    pauseDisconnect = (ListPreference) this.findPreference(Constants.PREFERENCES_KEY_PAUSE_DISCONNECT);
    serversCategory = (PreferenceCategory) this.findPreference(Constants.PREFERENCES_KEY_SERVER_KEY);
    addServerPreference = this.findPreference(Constants.PREFERENCES_KEY_SERVER_ADD);
    //videoPlayer = (ListPreference) this.findPreference(Constants.PREFERENCES_KEY_VIDEO_PLAYER);
    songPressAction = (ListPreference) this.findPreference(Constants.PREFERENCES_KEY_SONG_PRESS_ACTION);
    syncInterval = (ListPreference) this.findPreference(Constants.PREFERENCES_KEY_SYNC_INTERVAL);
    syncEnabled = (CheckBoxPreference) this.findPreference(Constants.PREFERENCES_KEY_SYNC_ENABLED);
    syncWifi = (CheckBoxPreference) this.findPreference(Constants.PREFERENCES_KEY_SYNC_WIFI);
    syncNotification = (CheckBoxPreference) this.findPreference(Constants.PREFERENCES_KEY_SYNC_NOTIFICATION);
    syncStarred = (CheckBoxPreference) this.findPreference(Constants.PREFERENCES_KEY_SYNC_STARRED);
    syncMostRecent = (CheckBoxPreference) this.findPreference(Constants.PREFERENCES_KEY_SYNC_MOST_RECENT);
    replayGain = (CheckBoxPreference) this.findPreference(Constants.PREFERENCES_KEY_REPLAY_GAIN);
    replayGainType = (ListPreference) this.findPreference(Constants.PREFERENCES_KEY_REPLAY_GAIN_TYPE);
    replayGainBump = this.findPreference(Constants.PREFERENCES_KEY_REPLAY_GAIN_BUMP);
    replayGainUntagged = this.findPreference(Constants.PREFERENCES_KEY_REPLAY_GAIN_UNTAGGED);
    cacheSize = (EditTextPreference) this.findPreference(Constants.PREFERENCES_KEY_CACHE_SIZE);
    openToTab = (ListPreference) this.findPreference(Constants.PREFERENCES_KEY_OPEN_TO_TAB);

    settings = Util.getPreferences(context);
    serverCount = settings.getInt(Constants.PREFERENCES_KEY_SERVER_COUNT, 1);

    if (cacheSize != null) {
        this.findPreference("clearCache")
                .setOnPreferenceClickListener(new Preference.OnPreferenceClickListener() {
                    @Override
                    public boolean onPreferenceClick(Preference preference) {
                        Util.confirmDialog(context, R.string.common_delete,
                                R.string.common_confirm_message_cache, new DialogInterface.OnClickListener() {
                                    @Override
                                    public void onClick(DialogInterface dialog, int which) {
                                        new LoadingTask<Void>(context, false) {
                                            @Override
                                            protected Void doInBackground() throws Throwable {
                                                FileUtil.deleteMusicDirectory(context);
                                                FileUtil.deleteSerializedCache(context);
                                                FileUtil.deleteArtworkCache(context);
                                                FileUtil.deleteAvatarCache(context);
                                                return null;
                                            }

                                            @Override
                                            protected void done(Void result) {
                                                Util.toast(context, R.string.settings_cache_clear_complete);
                                            }

                                            @Override
                                            protected void error(Throwable error) {
                                                Util.toast(context, getErrorMessage(error), false);
                                            }
                                        }.execute();
                                    }
                                });
                        return false;
                    }
                });
    }

    if (syncEnabled != null) {
        this.findPreference(Constants.PREFERENCES_KEY_SYNC_ENABLED)
                .setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener() {
                    @Override
                    public boolean onPreferenceChange(Preference preference, Object newValue) {
                        Boolean syncEnabled = (Boolean) newValue;

                        Account account = new Account(Constants.SYNC_ACCOUNT_NAME, Constants.SYNC_ACCOUNT_TYPE);
                        ContentResolver.setSyncAutomatically(account, Constants.SYNC_ACCOUNT_PLAYLIST_AUTHORITY,
                                syncEnabled);
                        ContentResolver.setSyncAutomatically(account, Constants.SYNC_ACCOUNT_PODCAST_AUTHORITY,
                                syncEnabled);

                        return true;
                    }
                });
        syncInterval.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener() {
            @Override
            public boolean onPreferenceChange(Preference preference, Object newValue) {
                Integer syncInterval = Integer.parseInt(((String) newValue));

                Account account = new Account(Constants.SYNC_ACCOUNT_NAME, Constants.SYNC_ACCOUNT_TYPE);
                ContentResolver.addPeriodicSync(account, Constants.SYNC_ACCOUNT_PLAYLIST_AUTHORITY,
                        new Bundle(), 60L * syncInterval);
                ContentResolver.addPeriodicSync(account, Constants.SYNC_ACCOUNT_PODCAST_AUTHORITY, new Bundle(),
                        60L * syncInterval);

                return true;
            }
        });
    }

    if (serversCategory != null) {
        addServerPreference.setOnPreferenceClickListener(new Preference.OnPreferenceClickListener() {
            @Override
            public boolean onPreferenceClick(Preference preference) {
                serverCount++;
                int instance = serverCount;
                serversCategory.addPreference(addServer(serverCount));

                SharedPreferences.Editor editor = settings.edit();
                editor.putInt(Constants.PREFERENCES_KEY_SERVER_COUNT, serverCount);
                // Reset set folder ID
                editor.putString(Constants.PREFERENCES_KEY_MUSIC_FOLDER_ID + instance, null);
                editor.putString(Constants.PREFERENCES_KEY_SERVER_URL + instance, "http://yourhost");
                editor.putString(Constants.PREFERENCES_KEY_SERVER_NAME + instance,
                        getResources().getString(R.string.settings_server_unused));
                editor.commit();

                ServerSettings ss = new ServerSettings(instance);
                serverSettings.put(String.valueOf(instance), ss);
                ss.update();

                return true;
            }
        });

        serversCategory.setOrderingAsAdded(false);
        for (int i = 1; i <= serverCount; i++) {
            serversCategory.addPreference(addServer(i));
            serverSettings.put(String.valueOf(i), new ServerSettings(i));
        }
    }

    SharedPreferences prefs = Util.getPreferences(context);
    prefs.registerOnSharedPreferenceChangeListener(this);

    update();
}

From source file:org.ohmage.authenticator.AuthenticatorActivity.java

/**
 * Called when response is received from the server for authentication
 * request. See onAuthenticationResult(). Sets the
 * AccountAuthenticatorResult which is sent back to the caller. Also sets
 * the authToken in AccountManager for this account.
 * // w  w w .jav  a2  s.co  m
 * @param the confirmCredentials result.
 */

protected void createAccount() {
    Log.v(TAG, "finishLogin()");
    final Account account = new Account(mUsername, OhmageApplication.ACCOUNT_TYPE);
    Bundle userData = new Bundle();
    userData.putString(KEY_OHMAGE_SERVER, ConfigHelper.serverUrl());
    mAuthtoken = mHashedPassword;

    if (TextUtils.isEmpty(mAuthtoken)) {
        Log.w(TAG, "Trying to create account with empty password");
        return;
    }

    if (mRequestNewAccount) {
        mAccountManager.addAccountExplicitly(account, mPassword, userData);
        mAccountManager.setAuthToken(account, OhmageApplication.AUTHTOKEN_TYPE, mAuthtoken);
        // Set sync for this account.
        ContentResolver.setIsSyncable(account, DbContract.CONTENT_AUTHORITY, 1);
        ContentResolver.setSyncAutomatically(account, DbContract.CONTENT_AUTHORITY, true);
        ContentResolver.addPeriodicSync(account, DbContract.CONTENT_AUTHORITY, new Bundle(), 3600);
    } else {
        mAccountManager.setPassword(account, mPassword);
    }
    final Intent intent = new Intent();
    intent.putExtra(AccountManager.KEY_ACCOUNT_NAME, mUsername);
    intent.putExtra(AccountManager.KEY_ACCOUNT_TYPE, OhmageApplication.ACCOUNT_TYPE);
    if (mAuthtokenType != null && mAuthtokenType.equals(OhmageApplication.AUTHTOKEN_TYPE)) {
        intent.putExtra(AccountManager.KEY_AUTHTOKEN, mAuthtoken);
    }
    setAccountAuthenticatorResult(intent.getExtras());
    setResult(RESULT_OK, intent);

    mPreferencesHelper.edit().putLoginTimestamp(System.currentTimeMillis()).commit();

    if (UserPreferencesHelper.isSingleCampaignMode()) {
        // Download the single campaign
        showDialog(DIALOG_DOWNLOADING_CAMPAIGNS);
        getSupportLoaderManager().restartLoader(0, null, this);
    } else {
        finishLogin();
    }
}

From source file:com.oxplot.contactphotosync.AssignContactPhotoActivity.java

@SuppressWarnings("unchecked")
@Override/*from  w  w w. jav a  2  s .c  o m*/
public boolean onMenuItemSelected(int featureId, MenuItem item) {
    switch (item.getItemId()) {

    case android.R.id.home:
        Intent upIntent = new Intent(this, SelectAccountActivity.class);
        if (NavUtils.shouldUpRecreateTask(this, upIntent)) {
            TaskStackBuilder.create(this).addNextIntent(upIntent).startActivities();
        } else {
            NavUtils.navigateUpTo(this, upIntent);
        }
        return true;

    case R.id.menu_sync_now:

        // This is a convenient way of enabling and running the contact photo
        // sync.

        Account a = new Account(account, ACCOUNT_TYPE);
        ContentResolver.setSyncAutomatically(a, CONTACT_PHOTO_AUTHORITY, true);
        ContentResolver.requestSync(a, CONTACT_PHOTO_AUTHORITY, new Bundle());
        Toast.makeText(this, getResources().getString(R.string.sync_requested), Toast.LENGTH_LONG).show();
        break;

    case R.id.menu_download_all:
    case R.id.menu_upload_all:
        new DownloadUploadTask(item.getItemId() == R.id.menu_download_all ? DownloadUploadTask.TYPE_DOWNLOAD
                : DownloadUploadTask.TYPE_UPLOAD)
                        .execute(((ContactAdapter) contactList.getAdapter()).getBackingList());

        break;

    case R.id.menu_refresh:

        // XXX This is ugly and hackish. This of course doesn't stop us from being
        // lazy and using it here.

        onPause();
        onResume();
        break;
    }
    return super.onOptionsItemSelected(item);
}

From source file:com.kiddobloom.bucketlist.AuthenticatorActivity.java

@Override
public void onCompleted(GraphUser user, Response response) {
    // TODO Auto-generated method stub
    //Log.d("tagaa", "FacebookGetMe: oncomplete me request");

    if (response != null) {

        FacebookRequestError error = response.getError();
        if (error != null) {
            // failed to get user info from facebook - TOAST
            //Log.d("tagaa", "FacebookGetMe: failed to get user info from facebook: " + error);

            Toast.makeText(getApplicationContext(),
                    "Failed to retrieve information from Facebook - OFFLINE mode", Toast.LENGTH_SHORT).show();

            saveState(StateMachine.OFFLINE_STATE);
            saveStatus(StateMachine.ERROR_STATUS);
            saveError(StateMachine.FB_GET_ME_FAILED_ERROR);
            goToBucketListActivity();//w w  w.j a v  a  2  s .  co  m
            return;
        }
    }

    if (user != null) {

        boolean registered = false;
        final Account account;

        // if we get to this point, we know that the network is OK
        // we can continue server registration

        //Log.d("tagaa", "FacebookGetMe: me = " + user);

        // check whether (com.kidobloom) type account has been created for the fb-userid
        // if account db is empty - create a new account using the fb-userid
        // else if an account already exists, check to see if it matches the current fb-userid
        // if account exists and matches the fb-userid, do nothing
        // otherwise replace the account with the new fb-userid
        AccountManager accountManager = AccountManager.get(getApplicationContext());
        Account[] accounts = accountManager.getAccountsByType("com.kiddobloom");

        if (accounts.length <= 0) {
            //Log.d("tagaa", "FacebookGetMe: no account exists");
            // create a new account
            account = new Account(user.getId(), Constants.ACCOUNT_TYPE);
            am.addAccountExplicitly(account, null, null);
            ContentResolver.setSyncAutomatically(account, MyContentProvider.AUTHORITY, true);
            registered = false;
        } else {
            // get the first account
            //Log.d("tagaa", "FacebookGetMe: account = " + accounts[0].name);

            if (accounts[0].name.equals(user.getId())) {
                registered = true;
                //Log.d("tagaa", "FacebookGetMe: account for facebookId = " + user.getId() + " already created");
            } else {
                //Log.d("tag", "FacebookGetMe: user switched account");
                // remove the account first
                am.removeAccount(accounts[0], null, null);

                // add new account with the new facebook userid
                account = new Account(user.getId(), Constants.ACCOUNT_TYPE);
                am.addAccountExplicitly(account, null, null);
                ContentResolver.setSyncAutomatically(account, MyContentProvider.AUTHORITY, true);

                // update the registered flag so facebook ID gets re-registered
                registered = false;
            }
        }

        // at this point, an account should already be created
        // store the userid and registered boolean in preferences db
        saveFbUserId(user.getId());
        saveUserIdRegistered(registered);

        saveState(StateMachine.FB_GET_FRIENDS_STATE);
        saveStatus(StateMachine.TRANSACTING_STATUS);
        saveError(StateMachine.NO_ERROR);

        // request facebook friends list
        Request.executeMyFriendsRequestAsync(response.getRequest().getSession(), this);

    } else {
        // throw an exception here - facebook does not indicate error but user is null 
        //Log.d("tagaa", "FacebookGetMe: failed to get user info from facebook - OFFLINE mode");

        Toast.makeText(getApplicationContext(), "Failed to retrieve information from Facebook",
                Toast.LENGTH_SHORT).show();

        saveState(StateMachine.OFFLINE_STATE);
        saveStatus(StateMachine.ERROR_STATUS);
        saveError(StateMachine.FB_GET_ME_FAILED_ERROR);
        goToBucketListActivity();
    }
}

From source file:com.openerp.MainActivity.java

/**
 * Sets the auto sync.//  w  w w.  j  a  v  a 2s.  c  om
 * 
 * @param authority
 *            the authority
 * @param isON
 *            the is on
 */
public void setAutoSync(String authority, boolean isON) {
    try {
        Account account = OpenERPAccountManager.getAccount(this, OEUser.current(mContext).getAndroidName());
        if (!ContentResolver.isSyncActive(account, authority)) {
            ContentResolver.setSyncAutomatically(account, authority, isON);
        }
    } catch (NullPointerException eNull) {

    }
}

From source file:com.gdgdevfest.android.apps.devfestbcn.ui.AccountActivity.java

private void finishSetup() {
    ContentResolver.setIsSyncable(mChosenAccount, ScheduleContract.CONTENT_AUTHORITY, 1);
    ContentResolver.setSyncAutomatically(mChosenAccount, ScheduleContract.CONTENT_AUTHORITY, true);
    SyncHelper.requestManualSync(mChosenAccount);
    PrefUtils.markSetupDone(this);

    if (mFinishIntent != null) {
        // Ensure the finish intent is unique within the task. Otherwise, if the task was
        // started with this intent, and it finishes like it should, then startActivity on
        // the intent again won't work.
        mFinishIntent.addCategory(POST_AUTH_CATEGORY);
        startActivity(mFinishIntent);//from   w  w  w.j  a v  a2  s. com
    }

    finish();
}

From source file:net.networksaremadeofstring.rhybudd.ViewZenossEventsListActivity.java

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);

    //Forces our onResume() function to do a DB call rather than a full HTTP request just cos we returned
    //from one of our subscreens
    //resumeOnResultPollAPI = false;
    BackupManager bm = null;// ww  w. ja va 2s  . c om
    try {
        bm = new BackupManager(this);
    } catch (Exception e) {
        BugSenseHandler.sendExceptionMessage("ViewZenossEventsListActivity", "onActivityResult BackupManager",
                e);
    }

    switch (requestCode) {
    case LAUNCHSETTINGS: {
        settings = PreferenceManager.getDefaultSharedPreferences(this);

        try {
            Intent intent = new Intent(this, ZenossPoller.class);
            intent.putExtra("settingsUpdate", true);
            startService(intent);
        } catch (Exception e) {
            BugSenseHandler.sendExceptionMessage("ViewZenossEventsListActivity",
                    "onActivityResult startService", e);
        }

        try {
            bm.dataChanged();
        } catch (Exception e) {
            BugSenseHandler.sendExceptionMessage("ViewZenossEventsListActivity",
                    "onActivityResult bm.dataChanged()", e);
        }

        //SyncAdapter stuff
        if (null != mAccount) {
            try {
                mResolver = getContentResolver();
                Bundle bndle = new Bundle();
                ContentResolver.addPeriodicSync(mAccount, AUTHORITY, bndle, 86400);

                ContentResolver.setSyncAutomatically(mAccount, AUTHORITY,
                        settings.getBoolean("refreshCache", true));

                /*bndle.putBoolean(
                        ContentResolver.SYNC_EXTRAS_MANUAL, true);
                bndle.putBoolean(
                        ContentResolver.SYNC_EXTRAS_EXPEDITED, true);
                        
                Log.e("addPeriodicSync","Requesting a full sync!");
                ContentResolver.requestSync(mAccount, AUTHORITY, bndle);*/
            } catch (Exception e) {
                BugSenseHandler.sendExceptionMessage("ViewZenossEventsListActivity",
                        "onActivityResult LAUNCHSETTINGS", e);
            }
        } else {
            //Log.e("addPeriodicSync","mAccount was null");
        }
    }
        break;

    case ZenossAPI.ACTIVITYRESULT_PUSHCONFIG: {
        try {
            GCMRegistrar.unregister(this);

            if (PreferenceManager.getDefaultSharedPreferences(ViewZenossEventsListActivity.this)
                    .getBoolean(ZenossAPI.PREFERENCE_PUSH_ENABLED, false))
                doGCMRegistration();
        } catch (Exception e) {
            BugSenseHandler.sendExceptionMessage("ViewZenossEventsListActivity",
                    "onActivityResult ACTIVITYRESULT_PUSHCONFIG", e);
        }
    }
        break;

    default: {
        if (resultCode == 1) {
            try {
                SharedPreferences.Editor editor = settings.edit();
                editor.putBoolean("FirstRun", false);
                editor.commit();
            } catch (Exception e) {
                BugSenseHandler.sendExceptionMessage("ViewZenossEventsListActivity", "onActivityResult default",
                        e);
            }

            //Also update our onResume helper bool although it should already be set
            firstRun = false;
            AlertDialog.Builder builder = null;
            AlertDialog welcomeDialog = null;
            try {
                builder = new AlertDialog.Builder(this);
                builder.setMessage(
                        "Additional settings and functionality can be found by pressing the Action bar overflow.\r\n"
                                + "\r\nIf you experience issues please email;\r\nGareth@DataSift.com before leaving negative reviews.")
                        .setTitle("Welcome to Rhybudd!").setCancelable(true)
                        .setPositiveButton("OK", new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialog, int id) {
                                finishStart();
                            }
                        });
                welcomeDialog = builder.create();
            } catch (Exception e) {
                BugSenseHandler.sendExceptionMessage("ViewZenossEventsListActivity", "onActivityResult default",
                        e);
            }

            try {
                welcomeDialog.show();
            } catch (Exception e) {
                finishStart();
                BugSenseHandler.sendExceptionMessage("ViewZenossEventsListActivity",
                        "OnActivityResult welcomedialog", e);
            }

            try {
                bm.dataChanged();
            } catch (Exception e) {
                BugSenseHandler.sendExceptionMessage("ViewZenossEventsListActivity", "onActivityResult default",
                        e);
            }
        } else if (resultCode == 2) {
            try {
                Toast.makeText(ViewZenossEventsListActivity.this,
                        getResources().getString(R.string.FirstRunNeedSettings), Toast.LENGTH_LONG).show();
            } catch (Exception e) {
                BugSenseHandler.sendExceptionMessage("ViewZenossEventsListActivity",
                        "onActivityResult resultcode 2", e);
            }
            finish();
        }
        //Who knows what happened here - quit
        else {
            //Toast.makeText(ViewZenossEventsListActivity.this, getResources().getString(R.string.FirstRunNeedSettings), Toast.LENGTH_LONG).show();
            //finish();
        }
    }
        break;
    }
}

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

public void setAuthoritiesToSyncAutomaticallyMap(Map<String, Boolean> authoritiesToSyncAutomaticallyMap) {
    if (authoritiesToSyncAutomaticallyMap == null) {
        throw new IllegalArgumentException("authoritiesToSyncAutomaticallyMap must not be null");
    }/*from   w  w  w  .  j  a v a  2s .co  m*/

    for (String authority : DEFAULT_AUTHORITIES_TO_SYNC_AUTOMATICALLY_MAP.keySet()) {
        boolean authorityEnabled = DEFAULT_AUTHORITIES_TO_SYNC_AUTOMATICALLY_MAP.get(authority);
        final Boolean enabled = authoritiesToSyncAutomaticallyMap.get(authority);
        if (enabled != null) {
            authorityEnabled = enabled.booleanValue();
        }
        // Accounts are always capable of being synced ...
        ContentResolver.setIsSyncable(account, authority, 1);
        // ... but not always automatically synced.
        ContentResolver.setSyncAutomatically(account, authority, authorityEnabled);
    }
}

From source file:org.ohmage.auth.AuthenticatorActivity.java

private Account addOrFindAccount(String email, String password) {
    Account[] accounts = am.getAccountsByType(AuthUtil.ACCOUNT_TYPE);
    Account account = accounts.length != 0 ? accounts[0] : new Account(email, AuthUtil.ACCOUNT_TYPE);

    if (accounts.length == 0) {
        am.addAccountExplicitly(account, password, null);

        // Turn on automatic syncing for this account
        ContentResolver.setSyncAutomatically(account, OhmageContract.CONTENT_AUTHORITY, true);
        ContentResolver.addPeriodicSync(account, StreamContract.CONTENT_AUTHORITY, new Bundle(),
                AuthUtil.SYNC_INTERVAL);

        ContentResolver.setSyncAutomatically(account, StreamContract.CONTENT_AUTHORITY, true);
        ContentResolver.addPeriodicSync(account, StreamContract.CONTENT_AUTHORITY, new Bundle(),
                AuthUtil.SYNC_INTERVAL);

        ContentResolver.setSyncAutomatically(account, ResponseContract.CONTENT_AUTHORITY, true);
        ContentResolver.addPeriodicSync(account, ResponseContract.CONTENT_AUTHORITY, new Bundle(),
                AuthUtil.SYNC_INTERVAL);

        ContentResolver.setSyncAutomatically(account, AppLogSyncAdapter.CONTENT_AUTHORITY, true);
        ContentResolver.addPeriodicSync(account, AppLogSyncAdapter.CONTENT_AUTHORITY, new Bundle(),
                AuthUtil.SYNC_INTERVAL);
    } else {//from w ww.j a  v a  2s .  co m
        am.setPassword(accounts[0], password);
    }
    return account;
}