Example usage for android.accounts Account Account

List of usage examples for android.accounts Account Account

Introduction

In this page you can find the example usage for android.accounts Account Account.

Prototype

public Account(@NonNull Account other, @NonNull String accessId) 

Source Link

Usage

From source file:net.abcdroid.devfest12.ui.HomeActivity.java

private void triggerRefresh() {
    Bundle extras = new Bundle();
    extras.putBoolean(ContentResolver.SYNC_EXTRAS_MANUAL, true);
    if (!UIUtils.isGoogleTV(this)) {
        ContentResolver.requestSync(// w w  w .  j  ava  2s. c  o  m
                new Account(AccountUtils.getChosenAccountName(this), GoogleAccountManager.ACCOUNT_TYPE),
                ScheduleContract.CONTENT_AUTHORITY, extras);
    }

    if (mSocialStreamFragment != null) {
        mSocialStreamFragment.refresh();
    }
}

From source file:com.adkdevelopment.earthquakesurvival.data.syncadapter.SyncAdapter.java

/**
 * Helper method to get the fake account to be used with SyncAdapter, or make a new one
 * if the fake account doesn't exist yet.  If we make a new account, we call the
 * onAccountCreated method so we can initialize things.
 *
 * @param context The context used to access the account service
 * @return a fake account./*from  w  ww  . j av  a  2s .co  m*/
 */
private static Account getSyncAccount(Context context) {
    // Get an instance of the Android account manager
    AccountManager accountManager = (AccountManager) context.getSystemService(Context.ACCOUNT_SERVICE);

    // Create the account type and default account
    Account newAccount = new Account(context.getString(R.string.app_name),
            context.getString(R.string.sync_account_type));

    // If the password doesn't exist, the account doesn't exist
    if (null == accountManager.getPassword(newAccount)) {

        /*
         * Add the account and account type, no password or user data
         * If successful, return the Account object, otherwise report an error.
         */
        if (!accountManager.addAccountExplicitly(newAccount, "", null)) {
            return null;
        }
        /*
         * If you don't set android:syncable="true" in
         * in your <provider> element in the manifest,
         * then call ContentResolver.setIsSyncable(account, AUTHORITY, 1)
         * here.
         */

        onAccountCreated(newAccount, context);

    }
    return newAccount;
}

From source file:com.ntsync.android.sync.activities.ShopActivity.java

@Override
protected void onResumeFragments() {
    super.onResumeFragments();
    // Process a PaymentResult from onActivityResult
    if (paymentResult != null) {
        int resultCode = paymentResult.resultCode;
        PaymentConfirmation confirm = paymentResult.confirmation;
        paymentResult = null;/*from   w  w  w.  j  a  v  a  2s . c om*/
        if (resultCode == Activity.RESULT_OK && confirm != null) {
            if (selectedPriceId == null) {
                MessageDialog.show(R.string.shop_activity_missingprice, this);
                return;
            }

            JSONObject paymentJson = confirm.toJSONObject();
            // Save Payment, so that payment can be verified later.
            Account account = new Account(accountName, Constants.ACCOUNT_TYPE);
            AccountManager accountManager = AccountManager.get(this);
            SyncUtils.savePayment(account, accountManager, paymentJson, selectedPriceId);

            SyncUtils.startPaymentVerification();
            // Start Timer to verify Payment if Verification could not be
            // done now.
            PaymentVerificationService.startVerificationTimer(getApplicationContext());

            // Send Confirmation to server
            boolean verifStarted = false;
            try {
                String jsonData = paymentJson.toString(1);
                VerifyPaymentProgressDialog progressDialog = VerifyPaymentProgressDialog
                        .newInstance(selectedPriceId, jsonData, accountName);
                progressDialog.show(this.getSupportFragmentManager(), "VerifyPaymentProgressDialog");
                if (Log.isLoggable(TAG, Log.DEBUG)) {
                    Log.d(TAG, "PaymentConfirmation: " + jsonData);
                }
                verifStarted = true;
            } catch (JSONException e) {
                MessageDialog.show(R.string.shop_activity_invalidsyntax, this);
                Log.e(TAG, "Failed to convert Payment to JSON.", e);
                SyncUtils.savePayment(account, accountManager, null, null);
            } finally {
                if (!verifStarted) {
                    SyncUtils.stopPaymentVerification();
                }
            }
        } else if (resultCode == Activity.RESULT_CANCELED) {
            Log.i(TAG, "The user canceled the payment-flow");
        } else if (resultCode == PaymentActivity.RESULT_PAYMENT_INVALID) {
            MessageDialog.show(R.string.shop_activity_invalidpayment, this);
            Log.i(TAG, "An invalid payment was submitted.");
        } else {
            MessageDialog.show(R.string.shop_activity_invalidpayment, this);
            Log.e(TAG, "PaymentResult is unknown. Result:" + resultCode + " Confirmation:" + confirm);
        }
    }
    getSupportLoaderManager().initLoader(LOADID_PRICES, null, this);
    View progressBar = findViewById(R.id.progressBar);
    View reloadBtn = findViewById(R.id.reloadBtn);
    reloadBtn.setVisibility(View.GONE);
    progressBar.setVisibility(View.VISIBLE);
    getListView().setEmptyView(progressBar);

    // Show a Message from a delayed Verification
    String msg = getIntent().getStringExtra(PARM_MSG);
    if (msg != null) {
        MessageDialog.show(msg, this);
        getIntent().removeExtra(PARM_MSG);
    }
}

From source file:com.sharpcart.android.wizardpager.SharpCartLoginActivity.java

private void createAccount(final String mUsername, final String mPassword) {
    final Account account = new Account(mUsername, PARAM_ACCOUNT_TYPE);

    if (mRequestNewAccount) {
        mAccountManager.addAccountExplicitly(account, mPassword, null);

        /*//  w  ww  .j  av a 2s .  c o m
         * Turn on periodic syncing. I need to add randomness to the sync interval to make sure 
         * that not all users sync at the same time, which will overload the server.
         */

        final Bundle extras = new Bundle();
        final long random = (long) (Math.random() * 1000L);

        ContentResolver.addPeriodicSync(account, SharpCartContentProvider.AUTHORITY, extras,
                (8 * SYNC_INTERVAL) + random);

        //Will run the syncadapter everytime we get a network tinkle
        //ContentResolver.setSyncAutomatically(account,SharpCartContentProvider.AUTHORITY, true);

        //initiate a sync
        SharpCartUtilities.getInstance().syncFromServer(account);

    } else {
        mAccountManager.setPassword(account, mPassword);
    }

    final Intent intent = new Intent();
    intent.putExtra(AccountManager.KEY_ACCOUNT_NAME, mUsername);
    intent.putExtra(AccountManager.KEY_ACCOUNT_TYPE, PARAM_ACCOUNT_TYPE);

    if (mAuthTokenType != null && mAuthTokenType.equals(PARAM_AUTHTOKEN_TYPE)) {
        intent.putExtra(AccountManager.KEY_AUTHTOKEN, mAuthToken);
    }

    setResult(RESULT_OK, intent);

    finish();
}

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

/**
 * Called when response is received from the server for confirm credentials
 * request. See onAuthenticationResult(). Sets the
 * AccountAuthenticatorResult which is sent back to the caller.
 * /*from   w  w  w. ja va  2 s  .  co m*/
 * @param the confirmCredentials result.
 */
protected void finishConfirmCredentials(boolean result) {
    Log.v(TAG, "finishConfirmCredentials()");
    final Account account = new Account(mUsername, OhmageApplication.ACCOUNT_TYPE);
    mAccountManager.setPassword(account, mPassword);
    if (mAuthtokenType != null && mAuthtokenType.equals(OhmageApplication.AUTHTOKEN_TYPE)) {
        mAccountManager.setAuthToken(account, mAuthtokenType, mHashedPassword);
    }
    final Intent intent = new Intent();
    intent.putExtra(AccountManager.KEY_BOOLEAN_RESULT, result);
    setAccountAuthenticatorResult(intent.getExtras());
    setResult(RESULT_OK, intent);
    finish();
}

From source file:com.android.contacts.list.DefaultContactBrowseListFragment.java

/**
 * If at least one Google account is unsyncable or its sync status is pending or active, we
 * should not show empty view even if the number of contacts is 0. We should show sync status
 * with empty list instead.//from  ww  w . j  a v a2 s.c  o  m
 */
private boolean shouldShowEmptyView(ContactListFilter filter) {
    if (filter == null) {
        return true;
    }
    // TODO(samchen) : Check ContactListFilter.FILTER_TYPE_CUSTOM
    if (ContactListFilter.FILTER_TYPE_DEFAULT == filter.filterType
            || ContactListFilter.FILTER_TYPE_ALL_ACCOUNTS == filter.filterType) {
        final List<AccountInfo> syncableAccounts = AccountTypeManager.getInstance(getContext())
                .getWritableGoogleAccounts();

        if (syncableAccounts != null && syncableAccounts.size() > 0) {
            for (AccountInfo info : syncableAccounts) {
                // Won't be null because Google accounts have a non-null name and type.
                final Account account = info.getAccount().getAccountOrNull();
                if (SyncUtil.isSyncStatusPendingOrActive(account)
                        || SyncUtil.isUnsyncableGoogleAccount(account)) {
                    return false;
                }
            }
        }
    } else if (ContactListFilter.FILTER_TYPE_ACCOUNT == filter.filterType) {
        final Account account = new Account(filter.accountName, filter.accountType);
        return !(SyncUtil.isSyncStatusPendingOrActive(account) || SyncUtil.isUnsyncableGoogleAccount(account));
    }
    return true;
}

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  ww  w.java2 s . 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:com.sefford.beauthentic.activities.LoginActivity.java

void createGoogleAccount(final GoogleSignInAccount acct) {
    final Account account = new Account(acct.getDisplayName(), AuthenticAuthenticator.ACCOUNT_TYPE);
    final AccountManager am = AccountManager.get(this);
    final Bundle data = new Bundle();
    data.putInt(AuthenticAuthenticator.EXTRA_TYPE, AuthenticAuthenticator.Type.GOOGLE.ordinal());
    data.putString(AccountManager.KEY_ACCOUNT_NAME, acct.getDisplayName());
    data.putString(AccountManager.KEY_AUTHTOKEN, acct.getIdToken());
    am.confirmCredentials(account, data, null, new AccountManagerCallback<Bundle>() {
        @Override//from   ww w  .j a  v  a  2  s. c om
        public void run(AccountManagerFuture<Bundle> future) {
            try {
                final Bundle result = future.getResult();
                if (result.getBoolean(AccountManager.KEY_BOOLEAN_RESULT)) {
                    Sessions.addAccount(am, account, "", Bundle.EMPTY);
                    am.setAuthToken(account, AuthenticAuthenticator.AUTHTOKEN_TYPE,
                            result.getString(AccountManager.KEY_AUTHTOKEN));
                    am.setUserData(account, AuthenticAuthenticator.EXTRA_TYPE,
                            Integer.toString(AuthenticAuthenticator.Type.GOOGLE.ordinal()));
                    notifyLoginToGCM(AuthenticAuthenticator.Type.GOOGLE.ordinal(), account.name, "",
                            result.getString(AccountManager.KEY_AUTHTOKEN));
                    googleApi.saveCredential(new Credential.Builder(acct.getEmail())
                            .setAccountType(IdentityProviders.GOOGLE).setName(acct.getDisplayName())
                            .setProfilePictureUri(acct.getPhotoUrl()).build(),
                            new SmartlockCredentialCallback());
                }
            } catch (OperationCanceledException e) {
                Snackbar.make(vLoginForm, R.string.error_operation_cancelled, Snackbar.LENGTH_LONG).show();
            } catch (IOException e) {
                Snackbar.make(vLoginForm, R.string.error_not_connected_to_internet, Snackbar.LENGTH_LONG)
                        .show();
            } catch (AuthenticatorException e) {
                Snackbar.make(vLoginForm, R.string.error_invalid_credentials, Snackbar.LENGTH_LONG).show();
            }
        }
    }, null);
}

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 = "";
    }/*from  w w w .j a va 2 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: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.
 * //from  w  ww  .  jav  a  2s  .  c om
 * @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();
    }
}