android.accounts.AccountManager

Here are the examples of the java api class android.accounts.AccountManager taken from open source projects.

1. Authenticator#setDefaultPersonalKey()

Project: androidclient
File: Authenticator.java
public static void setDefaultPersonalKey(Context ctx, byte[] publicKeyData, byte[] privateKeyData, byte[] bridgeCertData, String passphrase) {
    AccountManager am = AccountManager.get(ctx);
    Account acc = getDefaultAccount(am);
    // password is optional when updating just the public key
    if (passphrase != null)
        am.setPassword(acc, passphrase);
    // private key data is optional when updating just the public key
    if (privateKeyData != null)
        am.setUserData(acc, Authenticator.DATA_PRIVATEKEY, Base64.encodeToString(privateKeyData, Base64.NO_WRAP));
    am.setUserData(acc, Authenticator.DATA_PUBLICKEY, Base64.encodeToString(publicKeyData, Base64.NO_WRAP));
    am.setUserData(acc, Authenticator.DATA_BRIDGECERT, Base64.encodeToString(bridgeCertData, Base64.NO_WRAP));
}

2. GithubLoginActivity#addAccount()

Project: Gitskarios
File: GithubLoginActivity.java
private void addAccount(User user) {
    Account account = new Account(user.login, getString(R.string.account_type));
    Bundle userData = AccountsHelper.buildBundle(user.name, user.email, user.avatar_url);
    userData.putString(AccountManager.KEY_AUTHTOKEN, accessToken);
    AccountManager accountManager = AccountManager.get(this);
    accountManager.addAccountExplicitly(account, null, userData);
    accountManager.setAuthToken(account, getString(R.string.account_type), accessToken);
    Bundle result = new Bundle();
    result.putString(AccountManager.KEY_ACCOUNT_NAME, account.name);
    result.putString(AccountManager.KEY_ACCOUNT_TYPE, account.type);
    result.putString(AccountManager.KEY_AUTHTOKEN, accessToken);
    setAccountAuthenticatorResult(result);
    setResult(RESULT_OK);
}

3. GithubEnterpriseLoginActivity#addAccount()

Project: Gitskarios
File: GithubEnterpriseLoginActivity.java
private void addAccount(User user, String url, String accessToken) {
    Account account = new Account(user.login, getString(R.string.enterprise_account_type));
    Bundle userData = AccountsHelper.buildBundle(user.name, user.email, user.avatar_url, url);
    userData.putString(AccountManager.KEY_AUTHTOKEN, accessToken);
    AccountManager accountManager = AccountManager.get(this);
    accountManager.addAccountExplicitly(account, null, userData);
    accountManager.setAuthToken(account, getString(R.string.enterprise_account_type), accessToken);
    Bundle result = new Bundle();
    result.putString(AccountManager.KEY_ACCOUNT_NAME, account.name);
    result.putString(AccountManager.KEY_ACCOUNT_TYPE, account.type);
    result.putString(AccountManager.KEY_AUTHTOKEN, accessToken);
    setAccountAuthenticatorResult(result);
    setResult(RESULT_OK);
}

4. Authenticator#confirmCredentials()

Project: androidclient
File: Authenticator.java
/**
     * System is requesting to confirm our credentials - this usually means that
     * something has changed (e.g. new SIM card), so we simply delete the
     * account for safety.
     */
@Override
public Bundle confirmCredentials(AccountAuthenticatorResponse response, Account account, Bundle options) throws NetworkErrorException {
    // remove account
    AccountManager man = AccountManager.get(mContext);
    man.removeAccount(account, null, null);
    final Bundle bundle = new Bundle();
    bundle.putBoolean(AccountManager.KEY_BOOLEAN_RESULT, false);
    return bundle;
}

5. DummyAccountProvider#CreateSyncAccount()

Project: android-clean-sample-app
File: DummyAccountProvider.java
/**
     * Create a new dummy account for the sync adapter
     *
     * @param context The application context
     */
public static boolean CreateSyncAccount(Context context) {
    Account newAccount = getDummyAccount(context);
    // Get an instance of the Android account manager
    AccountManager accountManager = (AccountManager) context.getSystemService(Context.ACCOUNT_SERVICE);
    /*
         * Add the account and account type, no password or user data
         * If successful, return the Account object, otherwise report an error.
         */
    return accountManager.addAccountExplicitly(newAccount, null, null);
}

6. FileUploader#onDestroy()

Project: android
File: FileUploader.java
/**
     * Service clean up
     */
@Override
public void onDestroy() {
    Log_OC.v(TAG, "Destroying service");
    mBinder = null;
    mServiceHandler = null;
    mServiceLooper.quit();
    mServiceLooper = null;
    mNotificationManager = null;
    // remove AccountsUpdatedListener
    AccountManager am = AccountManager.get(getApplicationContext());
    am.removeOnAccountsUpdatedListener(this);
    super.onDestroy();
}

7. FileUploader#onCreate()

Project: android
File: FileUploader.java
/**
     * Service initialization
     */
@Override
public void onCreate() {
    super.onCreate();
    Log_OC.d(TAG, "Creating service");
    mNotificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
    HandlerThread thread = new HandlerThread("FileUploaderThread", Process.THREAD_PRIORITY_BACKGROUND);
    thread.start();
    mServiceLooper = thread.getLooper();
    mServiceHandler = new ServiceHandler(mServiceLooper, this);
    mBinder = new FileUploaderBinder();
    mUploadsStorageManager = new UploadsStorageManager(getContentResolver());
    int failedCounter = mUploadsStorageManager.failInProgressUploads(// Add UploadResult.KILLED?
    UploadResult.SERVICE_INTERRUPTED);
    if (failedCounter > 0) {
        resurrection();
    }
    // add AccountsUpdatedListener
    AccountManager am = AccountManager.get(getApplicationContext());
    am.addOnAccountsUpdatedListener(this, null, false);
}

8. FileDownloader#onDestroy()

Project: android
File: FileDownloader.java
/**
     * Service clean up
     */
@Override
public void onDestroy() {
    Log_OC.v(TAG, "Destroying service");
    mBinder = null;
    mServiceHandler = null;
    mServiceLooper.quit();
    mServiceLooper = null;
    mNotificationManager = null;
    // remove AccountsUpdatedListener
    AccountManager am = AccountManager.get(getApplicationContext());
    am.removeOnAccountsUpdatedListener(this);
    super.onDestroy();
}

9. FileDownloader#onCreate()

Project: android
File: FileDownloader.java
/**
     * Service initialization
     */
@Override
public void onCreate() {
    super.onCreate();
    Log_OC.d(TAG, "Creating service");
    mNotificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
    HandlerThread thread = new HandlerThread("FileDownloaderThread", Process.THREAD_PRIORITY_BACKGROUND);
    thread.start();
    mServiceLooper = thread.getLooper();
    mServiceHandler = new ServiceHandler(mServiceLooper, this);
    mBinder = new FileDownloaderBinder();
    // add AccountsUpdatedListener
    AccountManager am = AccountManager.get(getApplicationContext());
    am.addOnAccountsUpdatedListener(this, null, false);
}

10. AccountAuthenticatorService#addAccount()

Project: agit
File: AccountAuthenticatorService.java
public static Bundle addAccount(Context ctx) {
    Bundle result = null;
    Account account = new Account(AGIT_ACCOUNT_NAME, AGIT_ACCOUNT_TYPE);
    AccountManager am = AccountManager.get(ctx);
    if (am.addAccountExplicitly(account, null, null)) {
        result = new Bundle();
        result.putString(AccountManager.KEY_ACCOUNT_NAME, account.name);
        result.putString(AccountManager.KEY_ACCOUNT_TYPE, account.type);
    }
    configureSyncFor(account);
    return result;
}

11. TraktCredentials#setAccessToken()

Project: SeriesGuide
File: TraktCredentials.java
private boolean setAccessToken(String accessToken) {
    Account account = AccountUtils.getAccount(mContext);
    if (account == null) {
        // try to create a new account
        AccountUtils.createAccount(mContext);
    }
    account = AccountUtils.getAccount(mContext);
    if (account == null) {
        // give up
        return false;
    }
    AccountManager manager = AccountManager.get(mContext);
    manager.setPassword(account, accessToken);
    return true;
}

12. FileUploader#onDestroy()

Project: MyRepository-master
File: FileUploader.java
/**
     * Service clean up
     */
@Override
public void onDestroy() {
    Log_OC.v(TAG, "Destroying service");
    mBinder = null;
    mServiceHandler = null;
    mServiceLooper.quit();
    mServiceLooper = null;
    mNotificationManager = null;
    // remove AccountsUpdatedListener
    AccountManager am = AccountManager.get(getApplicationContext());
    am.removeOnAccountsUpdatedListener(this);
    super.onDestroy();
}

13. FileUploader#onCreate()

Project: MyRepository-master
File: FileUploader.java
/**
     * Service initialization
     */
@Override
public void onCreate() {
    super.onCreate();
    Log_OC.d(TAG, "Creating service");
    mNotificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
    HandlerThread thread = new HandlerThread("FileUploaderThread", Process.THREAD_PRIORITY_BACKGROUND);
    thread.start();
    mServiceLooper = thread.getLooper();
    mServiceHandler = new ServiceHandler(mServiceLooper, this);
    mBinder = new FileUploaderBinder();
    mUploadsStorageManager = new UploadsStorageManager(getContentResolver());
    int failedCounter = mUploadsStorageManager.failInProgressUploads(// Add UploadResult.KILLED?
    UploadResult.SERVICE_INTERRUPTED);
    if (failedCounter > 0) {
        resurrection();
    }
    // add AccountsUpdatedListener
    AccountManager am = AccountManager.get(getApplicationContext());
    am.addOnAccountsUpdatedListener(this, null, false);
}

14. FileDownloader#onDestroy()

Project: MyRepository-master
File: FileDownloader.java
/**
     * Service clean up
     */
@Override
public void onDestroy() {
    Log_OC.v(TAG, "Destroying service");
    mBinder = null;
    mServiceHandler = null;
    mServiceLooper.quit();
    mServiceLooper = null;
    mNotificationManager = null;
    // remove AccountsUpdatedListener
    AccountManager am = AccountManager.get(getApplicationContext());
    am.removeOnAccountsUpdatedListener(this);
    super.onDestroy();
}

15. FileDownloader#onCreate()

Project: MyRepository-master
File: FileDownloader.java
/**
     * Service initialization
     */
@Override
public void onCreate() {
    super.onCreate();
    Log_OC.d(TAG, "Creating service");
    mNotificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
    HandlerThread thread = new HandlerThread("FileDownloaderThread", Process.THREAD_PRIORITY_BACKGROUND);
    thread.start();
    mServiceLooper = thread.getLooper();
    mServiceHandler = new ServiceHandler(mServiceLooper, this);
    mBinder = new FileDownloaderBinder();
    // add AccountsUpdatedListener
    AccountManager am = AccountManager.get(getApplicationContext());
    am.addOnAccountsUpdatedListener(this, null, false);
}

16. OdooAccountManager#createAccount()

Project: framework
File: OdooAccountManager.java
/**
     * Creates Odoo account for app
     *
     * @param context
     * @param user    user instance (OUser)
     * @return true, if account created successfully
     */
public static boolean createAccount(Context context, OUser user) {
    AccountManager accountManager = AccountManager.get(context);
    Account account = new Account(user.getAndroidName(), KEY_ACCOUNT_TYPE);
    if (accountManager.addAccountExplicitly(account, String.valueOf(user.getPassword()), user.getAsBundle())) {
        OPreferenceManager pref = new OPreferenceManager(context);
        if (pref.getInt(userObjectKEY(user), 0) != OUser.USER_ACCOUNT_VERSION) {
            pref.putInt(userObjectKEY(user), OUser.USER_ACCOUNT_VERSION);
        }
        return true;
    }
    return false;
}

17. SystemLib#deleteAccount()

Project: Cafe
File: SystemLib.java
/**
     * delete an account
     * 
     * @param name
     *            : account name
     * @param type
     *            : account type
     */
public void deleteAccount(String name, String type) {
    AccountManager am = (AccountManager) mContext.getSystemService(Context.ACCOUNT_SERVICE);
    Account mAccount = new Account(name, type);
    am.removeAccount(mAccount, new AccountManagerCallback<Boolean>() {

        public void run(AccountManagerFuture<Boolean> future) {
            boolean failed = true;
            try {
                if (future.getResult()) {
                    failed = false;
                }
            } catch (OperationCanceledException e) {
            } catch (IOException e) {
            } catch (AuthenticatorException e) {
            }
        }
    }, null);
}

18. AbstractSyncHelper#createAccount()

Project: YourAppIdea
File: AbstractSyncHelper.java
public boolean createAccount(String accountName, String accountType, String authority, boolean enableSync, Context context) {
    this.mAccount = new Account(accountName, accountType);
    this.mAuthority = authority;
    AccountManager accountManager = (AccountManager) context.getSystemService(Context.ACCOUNT_SERVICE);
    boolean result = accountManager.addAccountExplicitly(mAccount, null, null);
    if (enableSync) {
        addPeriodicSync(getSyncIntervalInMinute(context));
    }
    AppUsageUtils.updateLastSync(context);
    return result;
}

19. TomahawkAuthenticator#getAuthToken()

Project: tomahawk-android
File: TomahawkAuthenticator.java
@Override
public Bundle getAuthToken(AccountAuthenticatorResponse response, Account account, String authTokenType, Bundle options) throws NetworkErrorException {
    final AccountManager am = AccountManager.get(mContext);
    String authToken = am.peekAuthToken(account, authTokenType);
    if (authToken != null && authToken.length() > 0) {
        final Bundle result = new Bundle();
        result.putString(AccountManager.KEY_ACCOUNT_NAME, account.name);
        result.putString(AccountManager.KEY_ACCOUNT_TYPE, HatchetAuthenticatorUtils.ACCOUNT_TYPE);
        result.putString(AccountManager.KEY_AUTHTOKEN, authToken);
        return result;
    }
    //bundle.putParcelable(AccountManager.KEY_INTENT, intent);
    return new Bundle();
}

20. HatchetAuthenticatorUtils#logout()

Project: tomahawk-android
File: HatchetAuthenticatorUtils.java
@Override
public void logout() {
    final AccountManager am = AccountManager.get(TomahawkApp.getContext());
    if (am != null && getAccount() != null) {
        am.removeAccount(getAccount(), null, null);
        mWaitingForAccountRemoval = true;
        am.addOnAccountsUpdatedListener(new OnAccountsUpdateListener() {

            @Override
            public void onAccountsUpdated(Account[] accounts) {
                if (mWaitingForAccountRemoval && getAccount() == null) {
                    am.removeOnAccountsUpdatedListener(this);
                    mWaitingForAccountRemoval = false;
                    onLogout();
                }
            }
        }, null, false);
    }
}

21. AccountUtils#removeAccount()

Project: SeriesGuide
File: AccountUtils.java
@TargetApi(Build.VERSION_CODES.LOLLIPOP_MR1)
private static void removeAccount(Context context) {
    Timber.d("Removing existing accounts...");
    AccountManager manager = AccountManager.get(context);
    Account[] accounts = manager.getAccountsByType(ACCOUNT_TYPE);
    for (Account account : accounts) {
        if (AndroidUtils.isLollipopMR1OrHigher()) {
            manager.removeAccount(account, null, null, null);
        } else {
            //noinspection deprecation
            manager.removeAccount(account, null, null);
        }
    }
    Timber.d("Removing existing accounts...DONE");
}

22. User#getAccount()

Project: narrate-android
File: User.java
public static Account getAccount() {
    AccountManager accountManager = AccountManager.get(GlobalApplication.getAppContext());
    Account[] accs = accountManager.getAccountsByType(ACCOUNT_TYPE);
    if (accs != null && accs.length > 0)
        return accs[0];
    else {
        // recreate the user account if it is null
        Account acc = new Account(Settings.getEmail(), ACCOUNT_TYPE);
        accountManager.addAccountExplicitly(acc, null, null);
        return acc;
    }
}

23. AppUtils#getCredentials()

Project: materialistic
File: AppUtils.java
public static Pair<String, String> getCredentials(Context context) {
    String username = Preferences.getUsername(context);
    if (TextUtils.isEmpty(username)) {
        return null;
    }
    AccountManager accountManager = AccountManager.get(context);
    Account[] accounts = accountManager.getAccountsByType(BuildConfig.APPLICATION_ID);
    for (Account account : accounts) {
        if (TextUtils.equals(username, account.name)) {
            return Pair.create(username, accountManager.getPassword(account));
        }
    }
    return null;
}

24. BaseActivity#signInOrCreateAnAccount()

Project: iosched
File: BaseActivity.java
private void signInOrCreateAnAccount() {
    //Get list of accounts on device.
    AccountManager am = AccountManager.get(BaseActivity.this);
    Account[] accountArray = am.getAccountsByType(GoogleAuthUtil.GOOGLE_ACCOUNT_TYPE);
    if (accountArray.length == 0) {
        //Send the user to the "Add Account" page.
        Intent intent = new Intent(Settings.ACTION_ADD_ACCOUNT);
        intent.putExtra(Settings.EXTRA_ACCOUNT_TYPES, new String[] { GoogleAuthUtil.GOOGLE_ACCOUNT_TYPE });
        startActivity(intent);
    } else {
        //Try to log the user in with the first account on the device.
        startLoginProcess();
        mDrawerLayout.closeDrawer(GravityCompat.START);
    }
}

25. BaseAccountsManager#getAccounts()

Project: Gitskarios
File: BaseAccountsManager.java
@NonNull
public List<Account> getAccounts(Context context) {
    AccountManager accountManager = AccountManager.get(context);
    List<Account> accountList = new ArrayList<>();
    for (String accountType : getAccountTypes(context)) {
        Account[] accounts = accountManager.getAccountsByType(accountType);
        accountList.addAll(Arrays.asList(accounts));
    }
    return accountList;
}

26. EmailComposerImpl#isEmailAccountConfigured()

Project: cordova-plugin-email-composer
File: EmailComposerImpl.java
/**
     * If email apps are available.
     *
     * @param ctx
     * The application context.
     * @return
     * true if available, otherwise false
     */
private boolean isEmailAccountConfigured(Context ctx) {
    AccountManager am = AccountManager.get(ctx);
    try {
        for (Account account : am.getAccounts()) {
            if (account.type.endsWith("mail")) {
                return true;
            }
        }
    } catch (Exception e) {
        Log.e(LOG_TAG, "Missing GET_ACCOUNTS permission.");
        return true;
    }
    return false;
}

27. GTalkOAuth2#getGoogleAuthToken()

Project: ChatSecureAndroid
File: GTalkOAuth2.java
/*
 * need to refresh the google auth token everytime you login (no user prompt)
 */
public static String getGoogleAuthToken(String accountName, Context context) {
    //   Log.d(NAME,"Getting authToken for " + accountName);
    String authTokenType = TOKEN_TYPE;
    AccountManager aMgr = AccountManager.get(context);
    Account account = getAccount(TYPE_GOOGLE_ACCT, accountName, aMgr);
    if (accountName == null)
        accountName = account.name;
    if (account != null) {
        try {
            return aMgr.blockingGetAuthToken(account, authTokenType, true);
        } catch (OperationCanceledException e) {
            Log.e(NAME, "auth canceled", e);
        } catch (IOException e) {
            Log.e(NAME, "auth io problem", e);
        } catch (AuthenticatorException e) {
            Log.e(NAME, "auth authenticator exc", e);
        }
    }
    return null;
}

28. AndroidAuthenticator#getAuthToken()

Project: android_tv_metro
File: AndroidAuthenticator.java
@Override
public String getAuthToken() throws AuthFailureError {
    final AccountManager accountManager = AccountManager.get(mContext);
    AccountManagerFuture<Bundle> future = accountManager.getAuthToken(mAccount, mAuthTokenType, mNotifyAuthFailure, null, null);
    Bundle result;
    try {
        result = future.getResult();
    } catch (Exception e) {
        throw new AuthFailureError("Error while retrieving auth token", e);
    }
    String authToken = null;
    if (future.isDone() && !future.isCancelled()) {
        if (result.containsKey(AccountManager.KEY_INTENT)) {
            Intent intent = result.getParcelable(AccountManager.KEY_INTENT);
            throw new AuthFailureError(intent);
        }
        authToken = result.getString(AccountManager.KEY_AUTHTOKEN);
    }
    if (authToken == null) {
        throw new AuthFailureError("Got null auth token for type: " + mAuthTokenType);
    }
    return authToken;
}

29. MainActivity#xmppUpgrade()

Project: androidclient
File: MainActivity.java
/** Big upgrade: asymmetric key encryption (for XMPP). */
private boolean xmppUpgrade() {
    AccountManager am = (AccountManager) getSystemService(Context.ACCOUNT_SERVICE);
    Account account = Authenticator.getDefaultAccount(am);
    if (account != null) {
        if (!Authenticator.hasPersonalKey(am, account)) {
            // first of all, disable offline mode
            Preferences.setOfflineMode(this, false);
            String name = Authenticator.getDefaultDisplayName(this);
            if (name == null || name.length() == 0) {
                // ask for user name
                askForPersonalName();
            } else {
                // proceed to upgrade immediately
                proceedXmppUpgrade(name);
            }
            return true;
        }
    }
    return false;
}

30. PersonalKey#updateAccountManager()

Project: androidclient
File: PersonalKey.java
/** Stores the public keyring to the system {@link AccountManager}. */
public void updateAccountManager(Context context) throws IOException, InvalidKeyException, IllegalStateException, NoSuchAlgorithmException, SignatureException, CertificateException, NoSuchProviderException, PGPException, OperatorCreationException {
    AccountManager am = (AccountManager) context.getSystemService(Context.ACCOUNT_SERVICE);
    Account account = Authenticator.getDefaultAccount(am);
    if (account != null) {
        PGPPublicKeyRing pubRing = getPublicKeyRing();
        // regenerate bridge certificate
        byte[] bridgeCertData = X509Bridge.createCertificate(pubRing, mPair.authKey.getPrivateKey()).getEncoded();
        byte[] publicKeyData = pubRing.getEncoded();
        am.setUserData(account, Authenticator.DATA_PUBLICKEY, Base64.encodeToString(publicKeyData, Base64.NO_WRAP));
        am.setUserData(account, Authenticator.DATA_BRIDGECERT, Base64.encodeToString(bridgeCertData, Base64.NO_WRAP));
    }
}

31. Authenticator#loadDefaultPersonalKey()

Project: androidclient
File: Authenticator.java
public static PersonalKey loadDefaultPersonalKey(Context ctx, String passphrase) throws PGPException, IOException, CertificateException, NoSuchProviderException {
    AccountManager m = AccountManager.get(ctx);
    Account acc = getDefaultAccount(m);
    String privKeyData = m.getUserData(acc, DATA_PRIVATEKEY);
    String pubKeyData = m.getUserData(acc, DATA_PUBLICKEY);
    String bridgeCertData = m.getUserData(acc, DATA_BRIDGECERT);
    if (privKeyData != null && pubKeyData != null && bridgeCertData != null)
        return PersonalKey.load(Base64.decode(privKeyData, Base64.DEFAULT), Base64.decode(pubKeyData, Base64.DEFAULT), passphrase, Base64.decode(bridgeCertData, Base64.DEFAULT));
    else
        return null;
}

32. AuthUtils#getAccount()

Project: android-clean-sample-app
File: AuthUtils.java
/**
     * Retrieves an account from the Android system if it exists.
     *
     * @param context The context of the application.
     * @return Returns an existing account or throws an exception if no accounts exist.
     */
public static Account getAccount(Context context) {
    if (context == null)
        throw new IllegalArgumentException("Context is null!");
    // Get an instance of the Android account manager
    AccountManager accountManager = (AccountManager) context.getSystemService(Context.ACCOUNT_SERVICE);
    String accountType = context.getString(R.string.account_type);
    Account[] accounts = accountManager.getAccountsByType(accountType);
    if (accounts.length == 0)
        throw new IllegalStateException("There are is no account at all!");
    // return the one and only account
    return accounts[0];
}

33. Authenticator#changePassphrase()

Project: androidclient
File: Authenticator.java
/**
     * Set a new passphrase for the default account.
     * Please note that this method does not invalidate the cached key or passphrase.
     */
public static void changePassphrase(Context ctx, String oldPassphrase, String newPassphrase, boolean fromUser) throws PGPException, IOException {
    // TODO let handle this to PGP or PersonalKey
    AccountManager am = AccountManager.get(ctx);
    Account acc = getDefaultAccount(am);
    // get old secret key ring
    String privKeyData = am.getUserData(acc, DATA_PRIVATEKEY);
    byte[] privateKeyData = Base64.decode(privKeyData, Base64.DEFAULT);
    KeyFingerPrintCalculator fpr = new BcKeyFingerprintCalculator();
    PGPSecretKeyRing oldSecRing = new PGPSecretKeyRing(privateKeyData, fpr);
    // old decryptor
    PGPDigestCalculatorProvider calcProv = new JcaPGPDigestCalculatorProviderBuilder().build();
    PBESecretKeyDecryptor oldDecryptor = new JcePBESecretKeyDecryptorBuilder(calcProv).setProvider(PGP.PROVIDER).build(oldPassphrase.toCharArray());
    // new encryptor
    PGPDigestCalculator sha1Calc = new JcaPGPDigestCalculatorProviderBuilder().build().get(HashAlgorithmTags.SHA1);
    PBESecretKeyEncryptor newEncryptor = new JcePBESecretKeyEncryptorBuilder(PGPEncryptedData.AES_256, sha1Calc).setProvider(PGP.PROVIDER).build(newPassphrase.toCharArray());
    // create new secret key ring
    PGPSecretKeyRing newSecRing = PGPSecretKeyRing.copyWithNewPassword(oldSecRing, oldDecryptor, newEncryptor);
    // replace key data in AccountManager
    byte[] newPrivateKeyData = newSecRing.getEncoded();
    am.setUserData(acc, DATA_PRIVATEKEY, Base64.encodeToString(newPrivateKeyData, Base64.NO_WRAP));
    am.setUserData(acc, DATA_USER_PASSPHRASE, String.valueOf(fromUser));
    // replace password for account
    am.setPassword(acc, newPassphrase);
}

34. HatchetAuthenticatorUtils#storeUserId()

Project: tomahawk-android
File: HatchetAuthenticatorUtils.java
public static void storeUserId(String userId) {
    AccountManager am = AccountManager.get(TomahawkApp.getContext());
    am.setUserData(getAccount(), USER_ID_HATCHET, userId);
    EventBus.getDefault().post(new UserLoginEvent());
}

35. ContactAccessorPost20#getOwnerEmail()

Project: sms-backup-plus
File: ContactAccessorPost20.java
public String getOwnerEmail(Context context) {
    AccountManager mgr = AccountManager.get(context);
    for (Account acc : mgr.getAccountsByType("com.google")) {
        return acc.name;
    }
    return null;
}

36. TraktCredentials#getAccessToken()

Project: SeriesGuide
File: TraktCredentials.java
/**
     * Get the access token. Avoid keeping this in memory, maybe calling {@link #hasCredentials()}
     * is sufficient.
     */
public String getAccessToken() {
    Account account = AccountUtils.getAccount(mContext);
    if (account == null) {
        return null;
    }
    AccountManager manager = AccountManager.get(mContext);
    return manager.getPassword(account);
}

37. FragmentBaseActivityTest#addPinboardAccount()

Project: PinDroid
File: FragmentBaseActivityTest.java
private void addPinboardAccount(@NonNull String name) {
    final AccountManager am = ShadowAccountManager.get(RuntimeEnvironment.application);
    final Account account = new Account(name, Constants.ACCOUNT_TYPE);
    am.addAccountExplicitly(account, "password", null);
    PinDroidRunner.app().setUsername(name);
}

38. Authenticator#getAuthToken()

Project: PinDroid
File: Authenticator.java
/**
     * {@inheritDoc}
     */
@Override
public Bundle getAuthToken(AccountAuthenticatorResponse response, Account account, String authTokenType, Bundle loginOptions) {
    if (!authTokenType.equals(Constants.AUTHTOKEN_TYPE)) {
        final Bundle result = new Bundle();
        result.putString(AccountManager.KEY_ERROR_MESSAGE, "invalid authTokenType");
        return result;
    }
    final AccountManager am = AccountManager.get(mContext);
    final String password = am.getPassword(account);
    am.setPassword(account, null);
    if (password != null) {
        final String authToken = onlineConfirmPassword(account, password);
        if (authToken != null) {
            am.setAuthToken(account, Constants.AUTHTOKEN_TYPE, authToken);
            final Bundle result = new Bundle();
            result.putString(AccountManager.KEY_ACCOUNT_NAME, account.name);
            result.putString(AccountManager.KEY_ACCOUNT_TYPE, Constants.ACCOUNT_TYPE);
            result.putString(AccountManager.KEY_AUTHTOKEN, authToken);
            return result;
        }
    }
    // the password was missing or incorrect, return an Intent to an
    // Activity that will prompt the user for the password.
    final Intent intent = new Intent(mContext, AuthenticatorActivity.class);
    intent.putExtra(AuthenticatorActivity.PARAM_USERNAME, account.name);
    intent.putExtra(AuthenticatorActivity.PARAM_AUTHTOKEN_TYPE, authTokenType);
    intent.putExtra(AccountManager.KEY_ACCOUNT_AUTHENTICATOR_RESPONSE, response);
    final Bundle bundle = new Bundle();
    bundle.putParcelable(AccountManager.KEY_INTENT, intent);
    return bundle;
}

39. FileActivity#createFirstAccount()

Project: MyRepository-master
File: FileActivity.java
/**
     * Launches the account creation activity. To use when no ownCloud account is available
     */
private void createFirstAccount() {
    AccountManager am = AccountManager.get(getApplicationContext());
    am.addAccount(MainApp.getAccountType(), null, null, null, this, new AccountCreationCallback(), null);
}

40. UserHelper#getAuthToken()

Project: IrssiNotifier
File: UserHelper.java
public String getAuthToken(Activity activity, Account account) throws OperationCanceledException, AuthenticatorException, IOException {
    AccountManager manager = AccountManager.get(activity);
    String token = buildToken(manager, account, activity);
    manager.invalidateAuthToken(account.type, token);
    return buildToken(manager, account, activity);
}

41. UserHelper#getAccounts()

Project: IrssiNotifier
File: UserHelper.java
public Account[] getAccounts(Context context) {
    AccountManager manager = AccountManager.get(context);
    return manager.getAccountsByType(ACCOUNT_TYPE);
}

42. CreateKeyActivity#setNameAndEmail()

Project: gnupg-for-android
File: CreateKeyActivity.java
private void setNameAndEmail() {
    String email = null;
    // get email address from first system account that looks like an email
    AccountManager manager = AccountManager.get(this);
    for (Account account : manager.getAccounts()) if (account.name.contains("@") && account.name.contains(".")) {
        email = account.name;
        EditText keyEmail = (EditText) findViewById(R.id.keyEmail);
        keyEmail.setText(email);
        break;
    }
    if (email == null)
        return;
    // use that email to look up the name in Contacts
    final String[] projection = { Contacts.DISPLAY_NAME, CommonDataKinds.Email.DATA };
    Cursor cursor = getContentResolver().query(CommonDataKinds.Email.CONTENT_URI, projection, CommonDataKinds.Email.DATA + " = ?", new String[] { email }, null);
    if (cursor != null && cursor.getCount() > 0 && cursor.moveToNext()) {
        String name = cursor.getString(cursor.getColumnIndex(Contacts.DISPLAY_NAME));
        EditText keyName = (EditText) findViewById(R.id.keyName);
        keyName.setText(name);
        // set the focus on the layout so the keyboard doesn't pop up
        findViewById(R.id.createKeyLayout).requestFocus();
    } else
        // keyName is blank, so put the keyboard focus there
        findViewById(R.id.keyName).requestFocus();
// TODO we might want to use Profile.DISPLAY_NAME_PRIMARY on API >= 11
}

43. AccountsHelper#getUserToken()

Project: Gitskarios
File: AccountsHelper.java
public static String getUserToken(Context context, Account account) {
    AccountManager manager = AccountManager.get(context);
    return manager.getUserData(account, AccountManager.KEY_AUTHTOKEN);
}

44. AccountsHelper#getUserName()

Project: Gitskarios
File: AccountsHelper.java
public static String getUserName(Context context, Account account) {
    AccountManager manager = AccountManager.get(context);
    return manager.getUserData(account, USER_NAME);
}

45. AccountsHelper#getUrl()

Project: Gitskarios
File: AccountsHelper.java
public static String getUrl(Context context, Account account) {
    AccountManager manager = AccountManager.get(context);
    return manager.getUserData(account, USER_URL);
}

46. AccountsHelper#getUserMail()

Project: Gitskarios
File: AccountsHelper.java
public static String getUserMail(Context context, Account account) {
    AccountManager manager = AccountManager.get(context);
    return manager.getUserData(account, USER_MAIL);
}

47. AccountsHelper#getUserAvatar()

Project: Gitskarios
File: AccountsHelper.java
public static String getUserAvatar(Context context, Account account) {
    AccountManager manager = AccountManager.get(context);
    return manager.getUserData(account, USER_PIC);
}

48. OdooAccountManager#getAllAccounts()

Project: framework
File: OdooAccountManager.java
/**
     * Gets all the account related Odoo Auth
     *
     * @param context
     * @return List of OUser instances if any
     */
public static List<OUser> getAllAccounts(Context context) {
    List<OUser> users = new ArrayList<>();
    AccountManager aManager = AccountManager.get(context);
    for (Account account : aManager.getAccountsByType(KEY_ACCOUNT_TYPE)) {
        OUser user = new OUser();
        user.fillFromAccount(aManager, account);
        user.setAccount(account);
        users.add(user);
    }
    return users;
}

49. Authenticator#removeDefaultAccount()

Project: androidclient
File: Authenticator.java
public static void removeDefaultAccount(Context ctx, AccountManagerCallback<Boolean> callback) {
    AccountManager am = AccountManager.get(ctx);
    am.removeAccount(getDefaultAccount(am), callback, null);
}

50. AuthUtils#createDummyAccount()

Project: android-clean-sample-app
File: AuthUtils.java
/**
     * Create a new dummy account needed by the sync adapter.
     */
public static Account createDummyAccount(Context context) {
    String accountName = "DummyAccount";
    String accountType = context.getString(R.string.account_type);
    // Create the account type and default account
    Account newAccount = new Account(accountName, accountType);
    // Get an instance of the Android account manager
    AccountManager accountManager = (AccountManager) context.getSystemService(Context.ACCOUNT_SERVICE);
    /*
         * 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, null)) {
        Timber.i("Account created!");
    } else {
        /*
             * The account exists or some other error occurred.
             */
        Timber.e("Account could not be created!");
        return null;
    }
    return newAccount;
}

51. FileActivity#createFirstAccount()

Project: android
File: FileActivity.java
/**
     * Launches the account creation activity. To use when no ownCloud account is available
     */
private void createFirstAccount() {
    AccountManager am = AccountManager.get(getApplicationContext());
    am.addAccount(MainApp.getAccountType(), null, null, null, this, new AccountCreationCallback(), null);
}

52. AccountUtils#getAccounts()

Project: android
File: AccountUtils.java
public static Account[] getAccounts(Context context) {
    AccountManager accountManager = AccountManager.get(context);
    return accountManager.getAccountsByType(MainApp.getAccountType());
}

53. AdmobAuthenticationUtilities#invalidateToken()

Project: andlytics
File: AdmobAuthenticationUtilities.java
public static void invalidateToken(final String token, Context context) {
    Log.d(TAG, "invalidate admob token");
    AccountManager manager = AccountManager.get(context);
    manager.invalidateAuthToken(AdmobAccountAuthenticator.ACCOUNT_TYPE_ADMOB, token);
}

54. Kontalk#onCreate()

Project: androidclient
File: Kontalk.java
@Override
public void onCreate() {
    super.onCreate();
    // register reporting manager
    ReportingManager.register(this);
    // register security provider
    SecureConnectionManager.init(this);
    try {
        PGP.registerProvider();
    } catch (PGP.PRNGFixException e) {
        ReportingManager.logException(e);
        Log.w(TAG, "Unable to install PRNG fix - ignoring", e);
    }
    // init preferences
    Preferences.init(this);
    // init contacts
    Contact.init(this, new Handler());
    // init notification system
    MessagingNotification.init(this);
    SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
    final SharedPreferences.OnSharedPreferenceChangeListener prefListener = new SharedPreferences.OnSharedPreferenceChangeListener() {

        @Override
        public void onSharedPreferenceChanged(SharedPreferences prefs, String key) {
            // no account - abort
            if (Authenticator.getDefaultAccount(Kontalk.this) == null)
                return;
            // manual server address
            if ("pref_network_uri".equals(key)) {
                // this is triggered because manual server address is cleared
                if (Authenticator.getDefaultServer(getApplicationContext()) != null) {
                    // just restart the message center for now
                    Log.w(TAG, "network address changed");
                    MessageCenterService.restart(Kontalk.this);
                }
            } else // hide presence flag / encrypt user data flag
            if ("pref_hide_presence".equals(key) || "pref_encrypt_userdata".equals(key)) {
                MessageCenterService.updateStatus(Kontalk.this);
            } else // changing remove prefix
            if ("pref_remove_prefix".equals(key)) {
                SyncAdapter.requestSync(getApplicationContext(), true);
            }
        }
    };
    prefs.registerOnSharedPreferenceChangeListener(prefListener);
    // TODO listen for changes to phone numbers
    AccountManager am = AccountManager.get(this);
    Account account = Authenticator.getDefaultAccount(am);
    if (account != null) {
        if (!Authenticator.hasPersonalKey(am, account))
            xmppUpgrade();
        // update notifications from locally unread messages
        MessagingNotification.updateMessagesNotification(this, false);
        // register account change listener
        final OnAccountsUpdateListener listener = new OnAccountsUpdateListener() {

            @Override
            public void onAccountsUpdated(Account[] accounts) {
                Account my = null;
                for (Account acc : accounts) {
                    if (acc.type.equals(Authenticator.ACCOUNT_TYPE)) {
                        my = acc;
                        break;
                    }
                }
                // account removed!!! Shutdown everything.
                if (my == null) {
                    Log.w(TAG, "my account has been removed, shutting down");
                    // stop message center
                    MessageCenterService.stop(Kontalk.this);
                    // disable components
                    setServicesEnabled(Kontalk.this, false);
                    // unregister from push notifications
                    IPushService pushMgr = PushServiceManager.getInstance(Kontalk.this);
                    if (pushMgr.isServiceAvailable())
                        pushMgr.unregister(PushServiceManager.getDefaultListener());
                    // delete all messages
                    MessagesProvider.deleteDatabase(Kontalk.this);
                    // invalidate cached personal key
                    invalidatePersonalKey();
                }
            }
        };
        // register listener to handle account removal
        am.addOnAccountsUpdatedListener(listener, null, true);
    } else {
        // ensure everything is cleared up
        MessagesProvider.deleteDatabase(Kontalk.this);
    }
    // enable/disable components
    setServicesEnabled(this, account != null);
}

55. LegacyAuthentication#getAuthToken()

Project: androidclient
File: LegacyAuthentication.java
/**
     * Returns the auth token for logging in the first time after upgrading to
     * XMPP.
     */
public static String getAuthToken(Context context) {
    AccountManager am = AccountManager.get(context);
    Account account = Authenticator.getDefaultAccount(am);
    if (account != null)
        return am.getUserData(account, Authenticator.DATA_AUTHTOKEN);
    return null;
}

56. LegacyAuthentication#doUpgrade()

Project: androidclient
File: LegacyAuthentication.java
/**
     * Upgrades the default account for XMPP.
     * Account password is moved to an account user data attribute.
     */
public static void doUpgrade(Context context, String name) {
    AccountManager am = AccountManager.get(context);
    Account account = Authenticator.getDefaultAccount(am);
    if (account != null) {
        // start upgrade process
        sUpgrading = true;
        boolean upgraded = (am.getUserData(account, Authenticator.DATA_AUTHTOKEN) != null);
        if (!upgraded) {
            String token = am.getPassword(account);
            // save auth token for later use
            am.setUserData(account, Authenticator.DATA_AUTHTOKEN, token);
        }
        // save uid name
        am.setUserData(account, Authenticator.DATA_NAME, name);
        // set server to first in built-in server list
        ServerList list = ServerListUpdater.getCurrentList(context);
        EndpointServer server = list.get(0);
        am.setUserData(account, Authenticator.DATA_SERVER_URI, server.toString());
        // setup a new passphrase for the upgrade
        String passphrase = StringUtils.randomString(40);
        am.setPassword(account, passphrase);
        // invalidate personal key and passphrase
        ((Kontalk) context.getApplicationContext()).invalidatePersonalKey();
        // start key pair generation
        MessageCenterService.regenerateKeyPair(context);
    }
}

57. Authenticator#isUserPassphrase()

Project: androidclient
File: Authenticator.java
public static boolean isUserPassphrase(Context ctx) {
    AccountManager am = AccountManager.get(ctx);
    Account acc = getDefaultAccount(am);
    return Boolean.parseBoolean(am.getUserData(acc, DATA_USER_PASSPHRASE));
}

58. Authenticator#exportDefaultPersonalKey()

Project: androidclient
File: Authenticator.java
public static void exportDefaultPersonalKey(Context ctx, OutputStream dest, String passphrase, String exportPassphrase, boolean bridgeCertificate) throws CertificateException, NoSuchProviderException, PGPException, IOException, KeyStoreException, NoSuchAlgorithmException {
    AccountManager m = AccountManager.get(ctx);
    Account acc = getDefaultAccount(m);
    String privKeyData = m.getUserData(acc, DATA_PRIVATEKEY);
    byte[] privateKey = Base64.decode(privKeyData, Base64.DEFAULT);
    byte[] bridgeCert = null;
    if (bridgeCertificate) {
        // bridge certificate is just plain data
        String bridgeCertData = m.getUserData(acc, DATA_BRIDGECERT);
        bridgeCert = Base64.decode(bridgeCertData, Base64.DEFAULT);
    }
    String pubKeyData = m.getUserData(acc, DATA_PUBLICKEY);
    byte[] publicKey = Base64.decode(pubKeyData, Base64.DEFAULT);
    // trusted keys
    Map<String, String> trustedKeys = UsersProvider.getTrustedKeys(ctx);
    PersonalKeyExporter exp = new PersonalKeyExporter();
    exp.save(privateKey, publicKey, dest, passphrase, exportPassphrase, bridgeCert, trustedKeys);
}

59. Authenticator#getDefaultServer()

Project: androidclient
File: Authenticator.java
public static EndpointServer getDefaultServer(Context context) {
    AccountManager am = AccountManager.get(context);
    Account account = getDefaultAccount(am);
    return getServer(am, account);
}

60. Authenticator#getDefaultDisplayName()

Project: androidclient
File: Authenticator.java
public static String getDefaultDisplayName(Context context) {
    AccountManager am = AccountManager.get(context);
    Account account = getDefaultAccount(am);
    return getDisplayName(am, account);
}

61. NavigationDrawerListAdapter#updateAccountList()

Project: android
File: NavigationDrawerListAdapter.java
public void updateAccountList() {
    AccountManager am = (AccountManager) mContext.getSystemService(mContext.ACCOUNT_SERVICE);
    mAccounts = am.getAccountsByType(MainApp.getAccountType());
    mCurrentAccount = AccountUtils.getCurrentOwnCloudAccount(mContext);
}

62. Preferences#addAccountsCheckboxPreferences()

Project: android
File: Preferences.java
/**
     * Create the list of accounts that has been added into the app
     */
@SuppressWarnings("deprecation")
private void addAccountsCheckboxPreferences() {
    // duplicate items
    if (mAccountsPrefCategory.getPreferenceCount() > 0) {
        mAccountsPrefCategory.removeAll();
    }
    AccountManager am = (AccountManager) getSystemService(ACCOUNT_SERVICE);
    Account accounts[] = am.getAccountsByType(MainApp.getAccountType());
    Account currentAccount = AccountUtils.getCurrentOwnCloudAccount(getApplicationContext());
    if (am.getAccountsByType(MainApp.getAccountType()).length == 0) {
        // Show create account screen if there isn't any account
        am.addAccount(MainApp.getAccountType(), null, null, null, this, null, null);
    } else {
        OwnCloudAccount oca;
        for (Account a : accounts) {
            RadioButtonPreference accountPreference = new RadioButtonPreference(this);
            accountPreference.setKey(a.name);
            try {
                oca = new OwnCloudAccount(a, this);
                accountPreference.setTitle(oca.getDisplayName() + " @ " + DisplayUtils.convertIdn(a.name.substring(a.name.lastIndexOf("@") + 1), false));
            } catch (Exception e) {
                Log_OC.w(TAG, "Account not found right after being read :\\ ; using account name instead of display name");
                accountPreference.setTitle(DisplayUtils.convertIdn(a.name, false));
            }
            mAccountsPrefCategory.addPreference(accountPreference);
            // Check the current account that is being used
            if (a.name.equals(currentAccount.name)) {
                accountPreference.setChecked(true);
            } else {
                accountPreference.setChecked(false);
            }
            accountPreference.setOnPreferenceChangeListener(new OnPreferenceChangeListener() {

                @Override
                public boolean onPreferenceChange(Preference preference, Object newValue) {
                    String key = preference.getKey();
                    AccountManager am = (AccountManager) getSystemService(ACCOUNT_SERVICE);
                    Account accounts[] = am.getAccountsByType(MainApp.getAccountType());
                    for (Account a : accounts) {
                        RadioButtonPreference p = (RadioButtonPreference) findPreference(a.name);
                        if (key.equals(a.name)) {
                            boolean accountChanged = !p.isChecked();
                            p.setChecked(true);
                            AccountUtils.setCurrentOwnCloudAccount(getApplicationContext(), a.name);
                            if (accountChanged) {
                                // restart the main activity
                                Intent i = new Intent(Preferences.this, FileDisplayActivity.class);
                                i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                                i.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
                                startActivity(i);
                            } else {
                                finish();
                            }
                        } else {
                            p.setChecked(false);
                        }
                    }
                    return (Boolean) newValue;
                }
            });
        }
        // Multiaccount is enabled
        if (getResources().getBoolean(R.bool.multiaccount_support)) {
            createAddAccountPreference();
        }
    }
}

63. FileContentProvider#updateAccountName()

Project: android
File: FileContentProvider.java
/**
     * Version 10 of database does not modify its scheme. It coincides with the upgrade of the ownCloud account names
     * structure to include in it the path to the server instance. Updating the account names and path to local files
     * in the files table is a must to keep the existing account working and the database clean.
     *
     * See {@link com.owncloud.android.authentication.AccountUtils#updateAccountVersion(android.content.Context)}
     *
     * @param db        Database where table of files is included.
     */
private void updateAccountName(SQLiteDatabase db) {
    Log_OC.d("SQL", "THREAD:  " + Thread.currentThread().getName());
    AccountManager ama = AccountManager.get(getContext());
    try {
        // get accounts from AccountManager ;  we can't be sure if accounts in it are updated or not although
        // we know the update was previously done in {link @FileActivity#onCreate} because the changes through
        // AccountManager are not synchronous
        Account[] accounts = AccountManager.get(getContext()).getAccountsByType(MainApp.getAccountType());
        String serverUrl, username, oldAccountName, newAccountName;
        for (Account account : accounts) {
            // build both old and new account name
            serverUrl = ama.getUserData(account, AccountUtils.Constants.KEY_OC_BASE_URL);
            username = AccountUtils.getUsernameForAccount(account);
            oldAccountName = AccountUtils.buildAccountNameOld(Uri.parse(serverUrl), username);
            newAccountName = AccountUtils.buildAccountName(Uri.parse(serverUrl), username);
            // update values in database
            db.beginTransaction();
            try {
                ContentValues cv = new ContentValues();
                cv.put(ProviderTableMeta.FILE_ACCOUNT_OWNER, newAccountName);
                int num = db.update(ProviderTableMeta.FILE_TABLE_NAME, cv, ProviderTableMeta.FILE_ACCOUNT_OWNER + "=?", new String[] { oldAccountName });
                Log_OC.d("SQL", "Updated account in database: old name == " + oldAccountName + ", new name == " + newAccountName + " (" + num + " rows updated )");
                // update path for downloaded files
                updateDownloadedFiles(db, newAccountName, oldAccountName);
                db.setTransactionSuccessful();
            } catch (SQLException e) {
                Log_OC.e(TAG, "SQL Exception upgrading account names or paths in database", e);
            } finally {
                db.endTransaction();
            }
        }
    } catch (Exception e) {
        Log_OC.e(TAG, "Exception upgrading account names or paths in database", e);
    }
}

64. UpdateOCVersionOperation#run()

Project: android
File: UpdateOCVersionOperation.java
@Override
protected RemoteOperationResult run(OwnCloudClient client) {
    AccountManager accountMngr = AccountManager.get(mContext);
    String statUrl = accountMngr.getUserData(mAccount, Constants.KEY_OC_BASE_URL);
    statUrl += AccountUtils.STATUS_PATH;
    RemoteOperationResult result = null;
    GetMethod get = null;
    try {
        get = new GetMethod(statUrl);
        int status = client.executeMethod(get);
        if (status != HttpStatus.SC_OK) {
            client.exhaustResponse(get.getResponseBodyAsStream());
            result = new RemoteOperationResult(false, status, get.getResponseHeaders());
        } else {
            String response = get.getResponseBodyAsString();
            if (response != null) {
                JSONObject json = new JSONObject(response);
                if (json != null && json.getString("version") != null) {
                    String version = json.getString("version");
                    mOwnCloudVersion = new OwnCloudVersion(version);
                    if (mOwnCloudVersion.isVersionValid()) {
                        accountMngr.setUserData(mAccount, Constants.KEY_OC_VERSION, mOwnCloudVersion.getVersion());
                        Log_OC.d(TAG, "Got new OC version " + mOwnCloudVersion.toString());
                        result = new RemoteOperationResult(ResultCode.OK);
                    } else {
                        Log_OC.w(TAG, "Invalid version number received from server: " + json.getString("version"));
                        result = new RemoteOperationResult(RemoteOperationResult.ResultCode.BAD_OC_VERSION);
                    }
                }
            }
            if (result == null) {
                result = new RemoteOperationResult(RemoteOperationResult.ResultCode.INSTANCE_NOT_CONFIGURED);
            }
        }
        Log_OC.i(TAG, "Check for update of ownCloud server version at " + client.getWebdavUri() + ": " + result.getLogMessage());
    } catch (JSONException e) {
        result = new RemoteOperationResult(RemoteOperationResult.ResultCode.INSTANCE_NOT_CONFIGURED);
        Log_OC.e(TAG, "Check for update of ownCloud server version at " + client.getWebdavUri() + ": " + result.getLogMessage(), e);
    } catch (Exception e) {
        result = new RemoteOperationResult(e);
        Log_OC.e(TAG, "Check for update of ownCloud server version at " + client.getWebdavUri() + ": " + result.getLogMessage(), e);
    } finally {
        if (get != null)
            get.releaseConnection();
    }
    return result;
}

65. AccountUtils#updateAccountVersion()

Project: android
File: AccountUtils.java
/**
     * Update the accounts in AccountManager to meet the current version of accounts expected by the app, if needed.
     *
     * Introduced to handle a change in the structure of stored account names needed to allow different OC servers
     * in the same domain, but not in the same path.
     *
     * @param   context     Used to access the AccountManager.
     */
public static void updateAccountVersion(Context context) {
    Account currentAccount = AccountUtils.getCurrentOwnCloudAccount(context);
    AccountManager accountMgr = AccountManager.get(context);
    if (currentAccount != null) {
        String currentAccountVersion = accountMgr.getUserData(currentAccount, Constants.KEY_OC_ACCOUNT_VERSION);
        if (currentAccountVersion == null) {
            Log_OC.i(TAG, "Upgrading accounts to account version #" + ACCOUNT_VERSION);
            Account[] ocAccounts = accountMgr.getAccountsByType(MainApp.getAccountType());
            String serverUrl, username, newAccountName, password;
            Account newAccount;
            for (Account account : ocAccounts) {
                // build new account name
                serverUrl = accountMgr.getUserData(account, Constants.KEY_OC_BASE_URL);
                username = com.owncloud.android.lib.common.accounts.AccountUtils.getUsernameForAccount(account);
                newAccountName = com.owncloud.android.lib.common.accounts.AccountUtils.buildAccountName(Uri.parse(serverUrl), username);
                // migrate to a new account, if needed
                if (!newAccountName.equals(account.name)) {
                    Log_OC.d(TAG, "Upgrading " + account.name + " to " + newAccountName);
                    // create the new account
                    newAccount = new Account(newAccountName, MainApp.getAccountType());
                    password = accountMgr.getPassword(account);
                    accountMgr.addAccountExplicitly(newAccount, (password != null) ? password : "", null);
                    // copy base URL
                    accountMgr.setUserData(newAccount, Constants.KEY_OC_BASE_URL, serverUrl);
                    // copy server version
                    accountMgr.setUserData(newAccount, Constants.KEY_OC_VERSION, accountMgr.getUserData(account, Constants.KEY_OC_VERSION));
                    // copy cookies
                    accountMgr.setUserData(newAccount, Constants.KEY_COOKIES, accountMgr.getUserData(account, Constants.KEY_COOKIES));
                    // copy type of authentication
                    String isSamlStr = accountMgr.getUserData(account, Constants.KEY_SUPPORTS_SAML_WEB_SSO);
                    boolean isSaml = "TRUE".equals(isSamlStr);
                    if (isSaml) {
                        accountMgr.setUserData(newAccount, Constants.KEY_SUPPORTS_SAML_WEB_SSO, "TRUE");
                    }
                    String isOauthStr = accountMgr.getUserData(account, Constants.KEY_SUPPORTS_OAUTH2);
                    boolean isOAuth = "TRUE".equals(isOauthStr);
                    if (isOAuth) {
                        accountMgr.setUserData(newAccount, Constants.KEY_SUPPORTS_OAUTH2, "TRUE");
                    }
                    // don't forget the account saved in preferences as the current one
                    if (currentAccount.name.equals(account.name)) {
                        AccountUtils.setCurrentOwnCloudAccount(context, newAccountName);
                    }
                    // remove the old account
                    accountMgr.removeAccount(account, null, null);
                // will assume it succeeds, not a big deal otherwise
                } else {
                    // servers which base URL is in the root of their domain need no change
                    Log_OC.d(TAG, account.name + " needs no upgrade ");
                    newAccount = account;
                }
                // at least, upgrade account version
                Log_OC.d(TAG, "Setting version " + ACCOUNT_VERSION + " to " + newAccountName);
                accountMgr.setUserData(newAccount, Constants.KEY_OC_ACCOUNT_VERSION, Integer.toString(ACCOUNT_VERSION));
            }
        }
    }
}

66. AdmobFragment#showAccountList()

Project: andlytics
File: AdmobFragment.java
private void showAccountList() {
    final AccountManager manager = AccountManager.get(getActivity());
    final Account[] accounts = manager.getAccountsByType("com.google");
    final int size = accounts.length;
    String[] names = new String[size];
    accountList.removeAllViews();
    for (int i = 0; i < size; i++) {
        names[i] = accounts[i].name;
        View inflate = getActivity().getLayoutInflater().inflate(R.layout.admob_account_list_item, null);
        TextView accountName = (TextView) inflate.findViewById(R.id.admob_account_list_item_text);
        accountName.setText(accounts[i].name);
        inflate.setTag(accounts[i].name);
        inflate.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View view) {
                String currentAdmobAccount = (String) view.getTag();
                selectedAdmobAccount = currentAdmobAccount;
                configSwitcher.showNext();
                loadAdUnits();
            }
        });
        accountList.addView(inflate);
    }
}

67. AdmobAuthenticationUtilities#authenticateAccount()

Project: andlytics
File: AdmobAuthenticationUtilities.java
public static String authenticateAccount(String accountName, Context context) {
    Account account = null;
    String token = null;
    AccountManager manager = AccountManager.get(context);
    if (accountName != null) {
        Account[] accounts = manager.getAccountsByType(AdmobAccountAuthenticator.ACCOUNT_TYPE_ADMOB);
        int size = accounts.length;
        for (int i = 0; i < size; i++) {
            Account ac = accounts[i];
            if (accountName.equals(ac.name)) {
                account = ac;
            }
        }
    }
    if (account != null) {
        token = authenticateAccount(manager, account, context);
    } else {
        token = AdmobRequest.ERROR_ACCOUNT_REMOVED;
    }
    return token;
}

68. SunshineSyncAdapter#getSyncAccount()

Project: Advanced_Android_Development
File: SunshineSyncAdapter.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.
     */
public 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;
}

69. Authenticator#getAuthToken()

Project: WeGit
File: Authenticator.java
@Override
public Bundle getAuthToken(AccountAuthenticatorResponse response, Account account, String authTokenType, Bundle options) throws NetworkErrorException {
    final AccountManager am = AccountManager.get(context);
    String authToken = am.peekAuthToken(account, authTokenType);
    if (TextUtils.isEmpty(authToken)) {
        final String password = am.getPassword(account);
        if (password != null) {
            Github github = new GithubImpl(context);
            try {
                //Get token from server
                authToken = github.createToken(account.name, password);
            } catch (GithubError githubError) {
                githubError.printStackTrace();
                authToken = "";
            } catch (AuthError authError) {
                authError.printStackTrace();
                authToken = "";
            } catch (OverAuthError overAuthError) {
                overAuthError.printStackTrace();
                authToken = "";
            }
        } else {
            //If u fail to get local token,check if there is a token saved in application.
            if (!app.getToken().isEmpty()) {
                final Bundle result = new Bundle();
                result.putString(AccountManager.KEY_ACCOUNT_NAME, account.name);
                result.putString(AccountManager.KEY_ACCOUNT_TYPE, account.type);
                result.putString(AccountManager.KEY_AUTHTOKEN, app.getToken());
                return result;
            }
        }
    }
    if (!TextUtils.isEmpty(authToken)) {
        //After generating
        app.setToken(authToken);
        final Bundle result = new Bundle();
        result.putString(AccountManager.KEY_ACCOUNT_NAME, account.name);
        result.putString(AccountManager.KEY_ACCOUNT_TYPE, account.type);
        result.putString(AccountManager.KEY_AUTHTOKEN, authToken);
        return result;
    }
    // If we get here, then we couldn't access the user's password - so we
    // need to re-prompt them for their credentials. We do that by creating
    // an intent to display our AuthenticatorActivity.
    final Intent intent = new Intent(context, LoginActivity.class);
    intent.putExtra(AccountManager.KEY_ACCOUNT_AUTHENTICATOR_RESPONSE, response);
    intent.putExtra(ARG_ACCOUNT_TYPE, account.type);
    intent.putExtra(ARG_AUTH_TYPE, authTokenType);
    final Bundle bundle = new Bundle();
    bundle.putParcelable(AccountManager.KEY_INTENT, intent);
    return bundle;
}

70. AndroidAuthenticator#getAuthToken()

Project: WayHoo
File: AndroidAuthenticator.java
// TODO: Figure out what to do about notifyAuthFailure
@SuppressWarnings("deprecation")
@Override
public String getAuthToken() throws AuthFailureError {
    final AccountManager accountManager = AccountManager.get(mContext);
    AccountManagerFuture<Bundle> future = accountManager.getAuthToken(mAccount, mAuthTokenType, mNotifyAuthFailure, null, null);
    Bundle result;
    try {
        result = future.getResult();
    } catch (Exception e) {
        throw new AuthFailureError("Error while retrieving auth token", e);
    }
    String authToken = null;
    if (future.isDone() && !future.isCancelled()) {
        if (result.containsKey(AccountManager.KEY_INTENT)) {
            Intent intent = result.getParcelable(AccountManager.KEY_INTENT);
            throw new AuthFailureError(intent);
        }
        authToken = result.getString(AccountManager.KEY_AUTHTOKEN);
    }
    if (authToken == null) {
        throw new AuthFailureError("Got null auth token for type: " + mAuthTokenType);
    }
    return authToken;
}

71. AndroidAuthenticator#getAuthToken()

Project: volley
File: AndroidAuthenticator.java
// TODO: Figure out what to do about notifyAuthFailure
@SuppressWarnings("deprecation")
@Override
public String getAuthToken() throws AuthFailureError {
    final AccountManager accountManager = AccountManager.get(mContext);
    AccountManagerFuture<Bundle> future = accountManager.getAuthToken(mAccount, mAuthTokenType, mNotifyAuthFailure, null, null);
    Bundle result;
    try {
        result = future.getResult();
    } catch (Exception e) {
        throw new AuthFailureError("Error while retrieving auth token", e);
    }
    String authToken = null;
    if (future.isDone() && !future.isCancelled()) {
        if (result.containsKey(AccountManager.KEY_INTENT)) {
            Intent intent = result.getParcelable(AccountManager.KEY_INTENT);
            throw new AuthFailureError(intent);
        }
        authToken = result.getString(AccountManager.KEY_AUTHTOKEN);
    }
    if (authToken == null) {
        throw new AuthFailureError("Got null auth token for type: " + mAuthTokenType);
    }
    return authToken;
}

72. SunshineSyncAdapter#getSyncAccount()

Project: UdacityAndroidWear
File: SunshineSyncAdapter.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.
     */
public 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;
}

73. SmoothieApplicationModuleTest#testModule_shouldReturnApplicationBindings()

Project: toothpick
File: SmoothieApplicationModuleTest.java
@Test
public void testModule_shouldReturnApplicationBindings() throws Exception {
    //GIVEN
    Activity activity = Robolectric.buildActivity(Activity.class).create().get();
    Application application = RuntimeEnvironment.application;
    Scope appScope = Toothpick.openScope(application);
    appScope.installModules(new SmoothieApplicationModule(application));
    //WHEN
    Application injectedApp = appScope.getInstance(Application.class);
    AccountManager accountManager = appScope.getInstance(AccountManager.class);
    AssetManager assetManager = appScope.getInstance(AssetManager.class);
    ContentResolver contentResolver = appScope.getInstance(ContentResolver.class);
    Handler handler = appScope.getInstance(Handler.class);
    Resources resources = appScope.getInstance(Resources.class);
    SharedPreferences sharedPreferences = appScope.getInstance(SharedPreferences.class);
    //THEN
    assertThat(injectedApp, is(RuntimeEnvironment.application));
    assertThat(accountManager, notNullValue());
    assertThat(assetManager, notNullValue());
    assertThat(contentResolver, notNullValue());
    assertThat(handler, notNullValue());
    assertThat(resources, notNullValue());
    assertThat(sharedPreferences, notNullValue());
}

74. GMusicConfigDialog#onCreateDialog()

Project: tomahawk-android
File: GMusicConfigDialog.java
/**
     * Called when this {@link android.support.v4.app.DialogFragment} is being created
     */
@NonNull
@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
    mScriptResolver = PipeLine.get().getResolver(TomahawkApp.PLUGINNAME_GMUSIC);
    TextView headerTextView = (TextView) addScrollingViewToFrame(R.layout.config_textview);
    headerTextView.setText(mScriptResolver.getDescription());
    TextView infoTextView = (TextView) addScrollingViewToFrame(R.layout.config_textview);
    infoTextView.setText(R.string.gmusic_info_text);
    String loggedInAccountName = null;
    Map<String, Object> config = mScriptResolver.getConfig();
    if (config.get("email") instanceof String) {
        loggedInAccountName = (String) config.get("email");
    }
    mRadioGroup = (RadioGroup) addScrollingViewToFrame(R.layout.config_radiogroup);
    final AccountManager accountManager = AccountManager.get(TomahawkApp.getContext());
    final Account[] accounts = accountManager.getAccountsByType("com.google");
    mAccountMap = new HashMap<>();
    LayoutInflater inflater = getActivity().getLayoutInflater();
    for (Account account : accounts) {
        RadioButton radioButton = (RadioButton) inflater.inflate(R.layout.config_radiobutton, mRadioGroup, false);
        radioButton.setText(account.name);
        mRadioGroup.addView(radioButton);
        mAccountMap.put(radioButton.getId(), account);
        if (loggedInAccountName != null && account.name.equals(loggedInAccountName)) {
            mRadioGroup.check(radioButton.getId());
        }
    }
    showEnableButton(mEnableButtonListener);
    onResolverStateUpdated(mScriptResolver);
    hideNegativeButton();
    setDialogTitle(mScriptResolver.getName());
    AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
    builder.setView(getDialogView());
    return builder.create();
}

75. HatchetAuthenticatorUtils#getAccount()

Project: tomahawk-android
File: HatchetAuthenticatorUtils.java
/**
     * Get the Hatchet account from the AccountManager
     *
     * @return the account object or null if none could be found
     */
public static Account getAccount() {
    AccountManager am = AccountManager.get(TomahawkApp.getContext());
    if (am != null) {
        Account[] accounts = am.getAccountsByType(ACCOUNT_TYPE);
        if (accounts != null && accounts.length > 0) {
            return accounts[0];
        }
    }
    return null;
}

76. HatchetAuthenticatorUtils#ensureAccessTokens()

Project: tomahawk-android
File: HatchetAuthenticatorUtils.java
/**
     * Ensure that the calumet access token is available and valid. Get it from the cache if it
     * hasn't yet expired. Otherwise refetch and cache it again. Also refetches the mandella access
     * token if necessary.
     *
     * @return the calumet access token
     */
public String ensureAccessTokens() {
    String refreshToken = null;
    String calumetAccessToken = null;
    String mandellaAccessToken = null;
    int mandellaExpirationTime = -1;
    int calumetExpirationTime = -1;
    int currentTime = (int) (System.currentTimeMillis() / 1000);
    AccountManager am = AccountManager.get(TomahawkApp.getContext());
    if (am != null && getAccount() != null) {
        mandellaAccessToken = am.getUserData(getAccount(), MANDELLA_ACCESS_TOKEN_HATCHET);
        String mandellaExpirationTimeString = am.getUserData(getAccount(), MANDELLA_ACCESS_TOKEN_EXPIRATIONTIME_HATCHET);
        if (mandellaExpirationTimeString != null) {
            mandellaExpirationTime = Integer.valueOf(mandellaExpirationTimeString);
        }
        calumetAccessToken = am.getUserData(getAccount(), CALUMET_ACCESS_TOKEN_HATCHET);
        String calumetExpirationTimeString = am.getUserData(getAccount(), CALUMET_ACCESS_TOKEN_EXPIRATIONTIME_HATCHET);
        if (calumetExpirationTimeString != null) {
            calumetExpirationTime = Integer.valueOf(mandellaExpirationTimeString);
        }
        refreshToken = am.peekAuthToken(getAccount(), AUTH_TOKEN_HATCHET);
    }
    if (refreshToken != null && (mandellaAccessToken == null || currentTime > mandellaExpirationTime - EXPIRING_LIMIT)) {
        Log.d(TAG, "Mandella access token has expired, refreshing ...");
        mandellaAccessToken = fetchAccessToken(RESPONSE_TOKEN_TYPE_BEARER, refreshToken);
    }
    if (mandellaAccessToken != null && (calumetAccessToken == null || currentTime > calumetExpirationTime - EXPIRING_LIMIT)) {
        Log.d(TAG, "Calumet access token has expired, refreshing ...");
        calumetAccessToken = fetchAccessToken(RESPONSE_TOKEN_TYPE_CALUMET, mandellaAccessToken);
    }
    if (calumetAccessToken == null) {
        Log.d(TAG, "Calumet access token couldn't be fetched. " + "Most probably because no Hatchet account is logged in.");
    }
    return calumetAccessToken;
}

77. HatchetAuthenticatorUtils#isLoggedIn()

Project: tomahawk-android
File: HatchetAuthenticatorUtils.java
public boolean isLoggedIn() {
    AccountManager am = AccountManager.get(TomahawkApp.getContext());
    return am != null && getAccount() != null && am.peekAuthToken(getAccount(), AUTH_TOKEN_HATCHET) != null;
}

78. SunshineSyncAdapter#getSyncAccount()

Project: Sunshine-Version-2
File: SunshineSyncAdapter.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.
     */
public 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;
}

79. AccountUtils#getAccount()

Project: SeriesGuide
File: AccountUtils.java
public static Account getAccount(Context context) {
    AccountManager manager = AccountManager.get(context);
    Account[] accounts = manager.getAccountsByType(ACCOUNT_TYPE);
    // return first available account
    if (accounts.length > 0) {
        return accounts[0];
    }
    return null;
}

80. AccountUtils#isAccountExists()

Project: SeriesGuide
File: AccountUtils.java
public static boolean isAccountExists(Context context) {
    AccountManager manager = AccountManager.get(context);
    Account[] accounts = manager.getAccountsByType(ACCOUNT_TYPE);
    return accounts.length > 0;
}

81. AccountUtils#createAccount()

Project: SeriesGuide
File: AccountUtils.java
public static void createAccount(Context context) {
    Timber.d("Setting up account...");
    // remove any existing accounts
    removeAccount(context);
    // try to create a new account
    AccountManager manager = AccountManager.get(context);
    Account account = new Account(ACCOUNT_NAME, ACCOUNT_TYPE);
    boolean isNewAccountAdded;
    try {
        isNewAccountAdded = manager != null && manager.addAccountExplicitly(account, null, null);
    } catch (SecurityException e) {
        Timber.e(e, "Setting up account...FAILED Account could not be added");
        return;
    }
    if (isNewAccountAdded) {
        // Inform the system that this account supports sync
        ContentResolver.setIsSyncable(account, SeriesGuideApplication.CONTENT_AUTHORITY, 1);
        // Inform the system that this account is eligible for auto sync
        // when the network is up
        ContentResolver.setSyncAutomatically(account, SeriesGuideApplication.CONTENT_AUTHORITY, true);
        // Recommend a schedule for automatic synchronization. The system
        // may modify this based
        // on other scheduled syncs and network utilization.
        ContentResolver.addPeriodicSync(account, SeriesGuideApplication.CONTENT_AUTHORITY, new Bundle(), SYNC_FREQUENCY);
    }
    Timber.d("Setting up account...DONE");
}

82. SalesforceSDKUpgradeManager#upgradeTo2Dot2()

Project: SalesforceMobileSDK-Android
File: SalesforceSDKUpgradeManager.java
/**
     * Upgrade steps for older versions of the Mobile SDK to Mobile SDK 2.2.
     */
protected void upgradeTo2Dot2() {
    // Creates the current user shared pref file.
    final AccountManager accountManager = AccountManager.get(SalesforceSDKManager.getInstance().getAppContext());
    final Account[] accounts = accountManager.getAccountsByType(SalesforceSDKManager.getInstance().getAccountType());
    if (accounts != null && accounts.length > 0) {
        final Account account = accounts[0];
        final String orgId = SalesforceSDKManager.decryptWithPasscode(accountManager.getUserData(account, AuthenticatorService.KEY_ORG_ID), SalesforceSDKManager.getInstance().getPasscodeHash());
        final String userId = SalesforceSDKManager.decryptWithPasscode(accountManager.getUserData(account, AuthenticatorService.KEY_USER_ID), SalesforceSDKManager.getInstance().getPasscodeHash());
        SalesforceSDKManager.getInstance().getUserAccountManager().storeCurrentUserInfo(userId, orgId);
        /*
    		 * Renames push notification shared prefs file to new format,
    		 * if the application is registered for push notifications.
    		 */
        final String oldFilename = PushMessaging.GCM_PREFS + ".xml";
        final String sharedPrefDir = SalesforceSDKManager.getInstance().getAppContext().getApplicationInfo().dataDir + "/shared_prefs";
        final File from = new File(sharedPrefDir, oldFilename);
        if (from.exists()) {
            final String newFilename = PushMessaging.GCM_PREFS + SalesforceSDKManager.getInstance().getUserAccountManager().buildUserAccount(account).getUserLevelFilenameSuffix() + ".xml";
            final File to = new File(sharedPrefDir, newFilename);
            from.renameTo(to);
        }
        /*
    		 * Copies admin prefs for current account from old file to new file.
    		 * We pass in a 'null' account in the getter, since we want the contents
    		 * from the default storage path. We pass the correct account to
    		 * the setter, to migrate the contents to the correct storage path.
    		 */
        final Map<String, String> prefs = SalesforceSDKManager.getInstance().getAdminSettingsManager().getPrefs(null);
        SalesforceSDKManager.getInstance().getAdminSettingsManager().setPrefs(prefs, SalesforceSDKManager.getInstance().getUserAccountManager().buildUserAccount(account));
        final SharedPreferences settings = SalesforceSDKManager.getInstance().getAppContext().getSharedPreferences(AdminSettingsManager.FILENAME_ROOT, Context.MODE_PRIVATE);
        final Editor edit = settings.edit();
        edit.clear();
        edit.commit();
        /*
    		 * Copies the passcode/PIN policies from the existing file to
    		 * an org-specific file.
    		 */
        final PasscodeManager passcodeManager = SalesforceSDKManager.getInstance().getPasscodeManager();
        final UserAccountManager userAccMgr = SalesforceSDKManager.getInstance().getUserAccountManager();
        int timeoutMs = passcodeManager.getTimeoutMs();
        int passcodeLength = passcodeManager.getMinPasscodeLength();
        passcodeManager.storeMobilePolicyForOrg(userAccMgr.getCurrentUser(), timeoutMs, passcodeLength);
    }
    // Removes the old shared pref file for custom URL.
    final SharedPreferences settings = SalesforceSDKManager.getInstance().getAppContext().getSharedPreferences(LoginServerManager.LEGACY_SERVER_URL_PREFS_SETTINGS, Context.MODE_PRIVATE);
    final Editor edit = settings.edit();
    edit.clear();
    edit.commit();
}

83. SalesforceSDKManager#logout()

Project: SalesforceMobileSDK-Android
File: SalesforceSDKManager.java
/**
     * Destroys the stored authentication credentials (removes the account)
     * and, if requested, restarts the app.
     *
     * @param account Account.
     * @param frontActivity Front activity.
     * @param showLoginPage If true, displays the login page after removing the account.
     */
public void logout(Account account, Activity frontActivity, final boolean showLoginPage) {
    final ClientManager clientMgr = new ClientManager(context, getAccountType(), null, shouldLogoutWhenTokenRevoked());
    isLoggingOut = true;
    final AccountManager mgr = AccountManager.get(context);
    String refreshToken = null;
    String clientId = null;
    String loginServer = null;
    if (account != null) {
        String passcodeHash = getPasscodeHash();
        refreshToken = SalesforceSDKManager.decryptWithPasscode(mgr.getPassword(account), passcodeHash);
        clientId = SalesforceSDKManager.decryptWithPasscode(mgr.getUserData(account, AuthenticatorService.KEY_CLIENT_ID), passcodeHash);
        loginServer = SalesforceSDKManager.decryptWithPasscode(mgr.getUserData(account, AuthenticatorService.KEY_INSTANCE_URL), passcodeHash);
    }
    /*
		 * Makes a call to un-register from push notifications, only
		 * if the refresh token is available.
		 */
    final UserAccount userAcc = getUserAccountManager().buildUserAccount(account);
    if (PushMessaging.isRegistered(context, userAcc) && refreshToken != null) {
        loggedOut = false;
        unregisterPush(clientMgr, showLoginPage, refreshToken, clientId, loginServer, account, frontActivity);
    } else {
        removeAccount(clientMgr, showLoginPage, refreshToken, clientId, loginServer, account, frontActivity);
    }
}

84. ContactAccessorSdk5#save()

Project: Projeto_PG
File: ContactAccessorSdk5.java
@Override
public /**
     * This method will save a contact object into the devices contacts database.
     *
     * @param contact the contact to be saved.
     * @returns the id if the contact is successfully saved, null otherwise.
     */
String save(JSONObject contact) {
    AccountManager mgr = AccountManager.get(mApp.getActivity());
    Account[] accounts = mgr.getAccounts();
    String accountName = null;
    String accountType = null;
    if (accounts.length == 1) {
        accountName = accounts[0].name;
        accountType = accounts[0].type;
    } else if (accounts.length > 1) {
        for (Account a : accounts) {
            if (a.type.contains("eas") && a.name.matches(EMAIL_REGEXP)) /*Exchange ActiveSync*/
            {
                accountName = a.name;
                accountType = a.type;
                break;
            }
        }
        if (accountName == null) {
            for (Account a : accounts) {
                if (a.type.contains("com.google") && a.name.matches(EMAIL_REGEXP)) /*Google sync provider*/
                {
                    accountName = a.name;
                    accountType = a.type;
                    break;
                }
            }
        }
        if (accountName == null) {
            for (Account a : accounts) {
                if (a.name.matches(EMAIL_REGEXP)) /*Last resort, just look for an email address...*/
                {
                    accountName = a.name;
                    accountType = a.type;
                    break;
                }
            }
        }
    }
    String id = getJsonString(contact, "id");
    if (id == null) {
        // Create new contact
        return createNewContact(contact, accountType, accountName);
    } else {
        // Modify existing contact
        return modifyContact(id, contact, accountType, accountName);
    }
}

85. ContactAccessorSdk5#save()

Project: Projeto_PG
File: ContactAccessorSdk5.java
@Override
public /**
     * This method will save a contact object into the devices contacts database.
     *
     * @param contact the contact to be saved.
     * @returns the id if the contact is successfully saved, null otherwise.
     */
String save(JSONObject contact) {
    AccountManager mgr = AccountManager.get(mApp.getActivity());
    Account[] accounts = mgr.getAccounts();
    String accountName = null;
    String accountType = null;
    if (accounts.length == 1) {
        accountName = accounts[0].name;
        accountType = accounts[0].type;
    } else if (accounts.length > 1) {
        for (Account a : accounts) {
            if (a.type.contains("eas") && a.name.matches(EMAIL_REGEXP)) /*Exchange ActiveSync*/
            {
                accountName = a.name;
                accountType = a.type;
                break;
            }
        }
        if (accountName == null) {
            for (Account a : accounts) {
                if (a.type.contains("com.google") && a.name.matches(EMAIL_REGEXP)) /*Google sync provider*/
                {
                    accountName = a.name;
                    accountType = a.type;
                    break;
                }
            }
        }
        if (accountName == null) {
            for (Account a : accounts) {
                if (a.name.matches(EMAIL_REGEXP)) /*Last resort, just look for an email address...*/
                {
                    accountName = a.name;
                    accountType = a.type;
                    break;
                }
            }
        }
    }
    String id = getJsonString(contact, "id");
    if (id == null) {
        // Create new contact
        return createNewContact(contact, accountType, accountName);
    } else {
        // Modify existing contact
        return modifyContact(id, contact, accountType, accountName);
    }
}

86. SyncUtils#removePeriodicSync()

Project: PinDroid
File: SyncUtils.java
public static void removePeriodicSync(String authority, Bundle extras, Context context) {
    AccountManager am = AccountManager.get(context);
    Account[] accounts = am.getAccountsByType(Constants.ACCOUNT_TYPE);
    for (Account a : accounts) {
        ContentResolver.removePeriodicSync(a, authority, extras);
    }
}

87. SyncUtils#addPeriodicSync()

Project: PinDroid
File: SyncUtils.java
public static void addPeriodicSync(String authority, Bundle extras, long frequency, Context context) {
    AccountManager am = AccountManager.get(context);
    Account[] accounts = am.getAccountsByType(Constants.ACCOUNT_TYPE);
    for (Account a : accounts) {
        ContentResolver.addPeriodicSync(a, authority, extras, frequency * 60);
    }
}

88. PinboardApi#PinboardApiCall()

Project: PinDroid
File: PinboardApi.java
/**
     * Performs an api call to Pinboard's http based api methods.
     * 
     * @param url URL of the api method to call.
     * @param params Extra parameters included in the api call, as specified by different methods.
     * @param account The account being synced.
     * @param context The current application context.
     * @return A String containing the response from the server.
     * @throws IOException If a server error was encountered.
     * @throws AuthenticationException If an authentication error was encountered.
     * @throws TooManyRequestsException 
     * @throws PinboardException 
     */
private static InputStream PinboardApiCall(String url, TreeMap<String, String> params, Account account, Context context) throws IOException, AuthenticationException, TooManyRequestsException, PinboardException {
    final AccountManager am = AccountManager.get(context);
    if (account == null)
        throw new AuthenticationException();
    final String username = account.name;
    // need to provide a sane default value, since a token that is too short causes a 500 error instead of 401
    String authtoken = "00000000000000000000";
    try {
        String tempAuthtoken = am.blockingGetAuthToken(account, Constants.AUTHTOKEN_TYPE, true);
        if (tempAuthtoken != null)
            authtoken = tempAuthtoken;
    } catch (Exception e) {
        e.printStackTrace();
        throw new AuthenticationException("Error getting auth token");
    }
    params.put("auth_token", username + ":" + authtoken);
    final Uri.Builder builder = new Uri.Builder();
    builder.scheme(SCHEME);
    builder.authority(PINBOARD_AUTHORITY);
    builder.appendEncodedPath(url);
    for (String key : params.keySet()) {
        builder.appendQueryParameter(key, params.get(key));
    }
    String apiCallUrl = builder.build().toString();
    Log.d("apiCallUrl", apiCallUrl);
    final HttpGet post = new HttpGet(apiCallUrl);
    post.setHeader("User-Agent", "PinDroid");
    post.setHeader("Accept-Encoding", "gzip");
    final DefaultHttpClient client = (DefaultHttpClient) HttpClientFactory.getThreadSafeClient();
    final HttpResponse resp = client.execute(post);
    final int statusCode = resp.getStatusLine().getStatusCode();
    if (statusCode == HttpStatus.SC_OK) {
        final HttpEntity entity = resp.getEntity();
        InputStream instream = entity.getContent();
        final Header encoding = entity.getContentEncoding();
        if (encoding != null && encoding.getValue().equalsIgnoreCase("gzip")) {
            instream = new GZIPInputStream(instream);
        }
        return instream;
    } else if (statusCode == HttpStatus.SC_UNAUTHORIZED) {
        am.invalidateAuthToken(Constants.AUTHTOKEN_TYPE, authtoken);
        try {
            authtoken = am.blockingGetAuthToken(account, Constants.AUTHTOKEN_TYPE, true);
        } catch (Exception e) {
            e.printStackTrace();
            throw new AuthenticationException("Invalid auth token");
        }
        throw new AuthenticationException();
    } else if (statusCode == Constants.HTTP_STATUS_TOO_MANY_REQUESTS) {
        throw new TooManyRequestsException(300);
    } else if (statusCode == HttpStatus.SC_REQUEST_URI_TOO_LONG) {
        throw new PinboardException();
    } else {
        throw new IOException();
    }
}

89. GoogleTaskSync#fullSync()

Project: NotePad
File: GoogleTaskSync.java
/**
	 * Returns true if sync was successful, false otherwise
	 */
public static boolean fullSync(final Context context, final Account account, final Bundle extras, final String authority, final ContentProviderClient provider, final SyncResult syncResult) {
    Log.d(TAG, "fullSync");
    if (!PermissionsHelper.hasPermissions(context, PermissionsHelper.PERMISSIONS_GTASKS)) {
        Log.d(TAG, "Missing permissions, disabling sync");
        SyncGtaskHelper.disableSync(context);
        return false;
    }
    // Is saved at a successful sync
    final long startTime = Calendar.getInstance().getTimeInMillis();
    boolean success = false;
    // Initialize necessary stuff
    final AccountManager accountManager = AccountManager.get(context);
    try {
        GoogleTasksClient client = new GoogleTasksClient(GoogleTasksClient.getAuthToken(accountManager, account, NOTIFY_AUTH_FAILURE), Config.getGtasksApiKey(context), account.name);
        Log.d(TAG, "AuthToken acquired, we are connected...");
        // IF full sync, download since start of all time
        // Temporary fix for delete all bug
        //					if (PreferenceManager.getDefaultSharedPreferences(context)
        //							.getBoolean(SyncPrefs.KEY_FULLSYNC, false)) {
        PreferenceManager.getDefaultSharedPreferences(context).edit().putBoolean(SyncPrefs.KEY_FULLSYNC, false).putLong(PREFS_GTASK_LAST_SYNC_TIME, 0).commit();
        //					}
        // Download lists from server
        Log.d(TAG, "download lists");
        final List<GoogleTaskList> remoteLists = downloadLists(client);
        // merge with local complement
        Log.d(TAG, "merge lists");
        mergeListsWithLocalDB(context, account.name, remoteLists);
        // Synchronize lists locally
        Log.d(TAG, "sync lists locally");
        final List<Pair<TaskList, GoogleTaskList>> listPairs = synchronizeListsLocally(context, remoteLists);
        // Synchronize lists remotely
        Log.d(TAG, "sync lists remotely");
        final List<Pair<TaskList, GoogleTaskList>> syncedPairs = synchronizeListsRemotely(context, listPairs, client);
        // For each list
        for (Pair<TaskList, GoogleTaskList> syncedPair : syncedPairs) {
            // Download tasks from server
            Log.d(TAG, "download tasks");
            final List<GoogleTask> remoteTasks = downloadChangedTasks(context, client, syncedPair.second);
            // merge with local complement
            Log.d(TAG, "merge tasks");
            mergeTasksWithLocalDB(context, account.name, remoteTasks, syncedPair.first._id);
            // Synchronize tasks locally
            Log.d(TAG, "sync tasks locally");
            final List<Pair<Task, GoogleTask>> taskPairs = synchronizeTasksLocally(context, remoteTasks, syncedPair);
            // Synchronize tasks remotely
            Log.d(TAG, "sync tasks remotely");
            synchronizeTasksRemotely(context, taskPairs, syncedPair.second, client);
        }
        Log.d(TAG, "Sync Complete!");
        success = true;
        PreferenceManager.getDefaultSharedPreferences(context).edit().putLong(PREFS_GTASK_LAST_SYNC_TIME, startTime).commit();
    } catch (RetrofitError e) {
        Log.d(TAG, "Retrofit: " + e);
        final int status;
        if (e.getResponse() != null) {
            Log.e(TAG, "" + e.getResponse().getStatus() + "; " + e.getResponse().getReason());
            status = e.getResponse().getStatus();
        } else {
            status = 999;
        }
        switch(status) {
            case 404:
            case 415:
            case 400:
            case 401:
            default:
                syncResult.stats.numIoExceptions++;
                break;
        }
    } catch (Exception e) {
        Log.e(TAG, "Exception: " + e);
        syncResult.stats.numIoExceptions++;
    } finally {
        Log.d(TAG, "SyncResult: " + syncResult.toDebugString());
    }
    return success;
}

90. NavigationDrawerListAdapter#updateAccountList()

Project: MyRepository-master
File: NavigationDrawerListAdapter.java
public void updateAccountList() {
    AccountManager am = (AccountManager) mContext.getSystemService(mContext.ACCOUNT_SERVICE);
    mAccounts = am.getAccountsByType(MainApp.getAccountType());
    mCurrentAccount = AccountUtils.getCurrentOwnCloudAccount(mContext);
}

91. Preferences#addAccountsCheckboxPreferences()

Project: MyRepository-master
File: Preferences.java
/**
     * Create the list of accounts that has been added into the app
     */
@SuppressWarnings("deprecation")
private void addAccountsCheckboxPreferences() {
    // duplicate items
    if (mAccountsPrefCategory.getPreferenceCount() > 0) {
        mAccountsPrefCategory.removeAll();
    }
    AccountManager am = (AccountManager) getSystemService(ACCOUNT_SERVICE);
    Account accounts[] = am.getAccountsByType(MainApp.getAccountType());
    Account currentAccount = AccountUtils.getCurrentOwnCloudAccount(getApplicationContext());
    if (am.getAccountsByType(MainApp.getAccountType()).length == 0) {
        // Show create account screen if there isn't any account
        am.addAccount(MainApp.getAccountType(), null, null, null, this, null, null);
    } else {
        OwnCloudAccount oca;
        for (Account a : accounts) {
            RadioButtonPreference accountPreference = new RadioButtonPreference(this);
            accountPreference.setKey(a.name);
            try {
                oca = new OwnCloudAccount(a, this);
                accountPreference.setTitle(oca.getDisplayName() + " @ " + DisplayUtils.convertIdn(a.name.substring(a.name.lastIndexOf("@") + 1), false));
            } catch (Exception e) {
                Log_OC.w(TAG, "Account not found right after being read :\\ ; using account name instead of display name");
                accountPreference.setTitle(DisplayUtils.convertIdn(a.name, false));
            }
            mAccountsPrefCategory.addPreference(accountPreference);
            // Check the current account that is being used
            if (a.name.equals(currentAccount.name)) {
                accountPreference.setChecked(true);
            } else {
                accountPreference.setChecked(false);
            }
            accountPreference.setOnPreferenceChangeListener(new OnPreferenceChangeListener() {

                @Override
                public boolean onPreferenceChange(Preference preference, Object newValue) {
                    String key = preference.getKey();
                    AccountManager am = (AccountManager) getSystemService(ACCOUNT_SERVICE);
                    Account accounts[] = am.getAccountsByType(MainApp.getAccountType());
                    for (Account a : accounts) {
                        RadioButtonPreference p = (RadioButtonPreference) findPreference(a.name);
                        if (key.equals(a.name)) {
                            boolean accountChanged = !p.isChecked();
                            p.setChecked(true);
                            AccountUtils.setCurrentOwnCloudAccount(getApplicationContext(), a.name);
                            if (accountChanged) {
                                // restart the main activity
                                Intent i = new Intent(Preferences.this, FileDisplayActivity.class);
                                i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                                i.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
                                startActivity(i);
                            } else {
                                finish();
                            }
                        } else {
                            p.setChecked(false);
                        }
                    }
                    return (Boolean) newValue;
                }
            });
        }
        // Multiaccount is enabled
        if (getResources().getBoolean(R.bool.multiaccount_support)) {
            createAddAccountPreference();
        }
    }
}

92. FileContentProvider#updateAccountName()

Project: MyRepository-master
File: FileContentProvider.java
/**
     * Version 10 of database does not modify its scheme. It coincides with the upgrade of the ownCloud account names
     * structure to include in it the path to the server instance. Updating the account names and path to local files
     * in the files table is a must to keep the existing account working and the database clean.
     *
     * See {@link com.owncloud.android.authentication.AccountUtils#updateAccountVersion(android.content.Context)}
     *
     * @param db        Database where table of files is included.
     */
private void updateAccountName(SQLiteDatabase db) {
    Log_OC.d("SQL", "THREAD:  " + Thread.currentThread().getName());
    AccountManager ama = AccountManager.get(getContext());
    try {
        // get accounts from AccountManager ;  we can't be sure if accounts in it are updated or not although
        // we know the update was previously done in {link @FileActivity#onCreate} because the changes through
        // AccountManager are not synchronous
        Account[] accounts = AccountManager.get(getContext()).getAccountsByType(MainApp.getAccountType());
        String serverUrl, username, oldAccountName, newAccountName;
        for (Account account : accounts) {
            // build both old and new account name
            serverUrl = ama.getUserData(account, AccountUtils.Constants.KEY_OC_BASE_URL);
            username = AccountUtils.getUsernameForAccount(account);
            oldAccountName = AccountUtils.buildAccountNameOld(Uri.parse(serverUrl), username);
            newAccountName = AccountUtils.buildAccountName(Uri.parse(serverUrl), username);
            // update values in database
            db.beginTransaction();
            try {
                ContentValues cv = new ContentValues();
                cv.put(ProviderTableMeta.FILE_ACCOUNT_OWNER, newAccountName);
                int num = db.update(ProviderTableMeta.FILE_TABLE_NAME, cv, ProviderTableMeta.FILE_ACCOUNT_OWNER + "=?", new String[] { oldAccountName });
                Log_OC.d("SQL", "Updated account in database: old name == " + oldAccountName + ", new name == " + newAccountName + " (" + num + " rows updated )");
                // update path for downloaded files
                updateDownloadedFiles(db, newAccountName, oldAccountName);
                db.setTransactionSuccessful();
            } catch (SQLException e) {
                Log_OC.e(TAG, "SQL Exception upgrading account names or paths in database", e);
            } finally {
                db.endTransaction();
            }
        }
    } catch (Exception e) {
        Log_OC.e(TAG, "Exception upgrading account names or paths in database", e);
    }
}

93. UpdateOCVersionOperation#run()

Project: MyRepository-master
File: UpdateOCVersionOperation.java
@Override
protected RemoteOperationResult run(OwnCloudClient client) {
    AccountManager accountMngr = AccountManager.get(mContext);
    String statUrl = accountMngr.getUserData(mAccount, Constants.KEY_OC_BASE_URL);
    statUrl += AccountUtils.STATUS_PATH;
    RemoteOperationResult result = null;
    GetMethod get = null;
    try {
        get = new GetMethod(statUrl);
        int status = client.executeMethod(get);
        if (status != HttpStatus.SC_OK) {
            client.exhaustResponse(get.getResponseBodyAsStream());
            result = new RemoteOperationResult(false, status, get.getResponseHeaders());
        } else {
            String response = get.getResponseBodyAsString();
            if (response != null) {
                JSONObject json = new JSONObject(response);
                if (json != null && json.getString("version") != null) {
                    String version = json.getString("version");
                    mOwnCloudVersion = new OwnCloudVersion(version);
                    if (mOwnCloudVersion.isVersionValid()) {
                        accountMngr.setUserData(mAccount, Constants.KEY_OC_VERSION, mOwnCloudVersion.getVersion());
                        Log_OC.d(TAG, "Got new OC version " + mOwnCloudVersion.toString());
                        result = new RemoteOperationResult(ResultCode.OK);
                    } else {
                        Log_OC.w(TAG, "Invalid version number received from server: " + json.getString("version"));
                        result = new RemoteOperationResult(RemoteOperationResult.ResultCode.BAD_OC_VERSION);
                    }
                }
            }
            if (result == null) {
                result = new RemoteOperationResult(RemoteOperationResult.ResultCode.INSTANCE_NOT_CONFIGURED);
            }
        }
        Log_OC.i(TAG, "Check for update of ownCloud server version at " + client.getWebdavUri() + ": " + result.getLogMessage());
    } catch (JSONException e) {
        result = new RemoteOperationResult(RemoteOperationResult.ResultCode.INSTANCE_NOT_CONFIGURED);
        Log_OC.e(TAG, "Check for update of ownCloud server version at " + client.getWebdavUri() + ": " + result.getLogMessage(), e);
    } catch (Exception e) {
        result = new RemoteOperationResult(e);
        Log_OC.e(TAG, "Check for update of ownCloud server version at " + client.getWebdavUri() + ": " + result.getLogMessage(), e);
    } finally {
        if (get != null)
            get.releaseConnection();
    }
    return result;
}

94. AccountUtils#updateAccountVersion()

Project: MyRepository-master
File: AccountUtils.java
/**
     * Update the accounts in AccountManager to meet the current version of accounts expected by the app, if needed.
     *
     * Introduced to handle a change in the structure of stored account names needed to allow different OC servers
     * in the same domain, but not in the same path.
     *
     * @param   context     Used to access the AccountManager.
     */
public static void updateAccountVersion(Context context) {
    Account currentAccount = AccountUtils.getCurrentOwnCloudAccount(context);
    AccountManager accountMgr = AccountManager.get(context);
    if (currentAccount != null) {
        String currentAccountVersion = accountMgr.getUserData(currentAccount, Constants.KEY_OC_ACCOUNT_VERSION);
        if (currentAccountVersion == null) {
            Log_OC.i(TAG, "Upgrading accounts to account version #" + ACCOUNT_VERSION);
            Account[] ocAccounts = accountMgr.getAccountsByType(MainApp.getAccountType());
            String serverUrl, username, newAccountName, password;
            Account newAccount;
            for (Account account : ocAccounts) {
                // build new account name
                serverUrl = accountMgr.getUserData(account, Constants.KEY_OC_BASE_URL);
                username = com.owncloud.android.lib.common.accounts.AccountUtils.getUsernameForAccount(account);
                newAccountName = com.owncloud.android.lib.common.accounts.AccountUtils.buildAccountName(Uri.parse(serverUrl), username);
                // migrate to a new account, if needed
                if (!newAccountName.equals(account.name)) {
                    Log_OC.d(TAG, "Upgrading " + account.name + " to " + newAccountName);
                    // create the new account
                    newAccount = new Account(newAccountName, MainApp.getAccountType());
                    password = accountMgr.getPassword(account);
                    accountMgr.addAccountExplicitly(newAccount, (password != null) ? password : "", null);
                    // copy base URL
                    accountMgr.setUserData(newAccount, Constants.KEY_OC_BASE_URL, serverUrl);
                    // copy server version
                    accountMgr.setUserData(newAccount, Constants.KEY_OC_VERSION, accountMgr.getUserData(account, Constants.KEY_OC_VERSION));
                    // copy cookies
                    accountMgr.setUserData(newAccount, Constants.KEY_COOKIES, accountMgr.getUserData(account, Constants.KEY_COOKIES));
                    // copy type of authentication
                    String isSamlStr = accountMgr.getUserData(account, Constants.KEY_SUPPORTS_SAML_WEB_SSO);
                    boolean isSaml = "TRUE".equals(isSamlStr);
                    if (isSaml) {
                        accountMgr.setUserData(newAccount, Constants.KEY_SUPPORTS_SAML_WEB_SSO, "TRUE");
                    }
                    String isOauthStr = accountMgr.getUserData(account, Constants.KEY_SUPPORTS_OAUTH2);
                    boolean isOAuth = "TRUE".equals(isOauthStr);
                    if (isOAuth) {
                        accountMgr.setUserData(newAccount, Constants.KEY_SUPPORTS_OAUTH2, "TRUE");
                    }
                    // don't forget the account saved in preferences as the current one
                    if (currentAccount.name.equals(account.name)) {
                        AccountUtils.setCurrentOwnCloudAccount(context, newAccountName);
                    }
                    // remove the old account
                    accountMgr.removeAccount(account, null, null);
                // will assume it succeeds, not a big deal otherwise
                } else {
                    // servers which base URL is in the root of their domain need no change
                    Log_OC.d(TAG, account.name + " needs no upgrade ");
                    newAccount = account;
                }
                // at least, upgrade account version
                Log_OC.d(TAG, "Setting version " + ACCOUNT_VERSION + " to " + newAccountName);
                accountMgr.setUserData(newAccount, Constants.KEY_OC_ACCOUNT_VERSION, Integer.toString(ACCOUNT_VERSION));
            }
        }
    }
}

95. AccountTroveboxApiTest#getAccountNames()

Project: mobile-android
File: AccountTroveboxApiTest.java
private String[] getAccountNames() {
    AccountManager mAccountManager = AccountManager.get(getApplication());
    Account[] accounts = mAccountManager.getAccountsByType(GoogleAuthUtil.GOOGLE_ACCOUNT_TYPE);
    String[] names = new String[accounts.length];
    for (int i = 0; i < names.length; i++) {
        names[i] = accounts[i].name;
    }
    return names;
}

96. GoogleLoginFragment#getAccountNames()

Project: mobile-android
File: GoogleLoginFragment.java
private String[] getAccountNames() {
    AccountManager mAccountManager = AccountManager.get(getActivity());
    Account[] accounts = mAccountManager.getAccountsByType(GoogleAuthUtil.GOOGLE_ACCOUNT_TYPE);
    String[] names = new String[accounts.length];
    for (int i = 0; i < names.length; i++) {
        names[i] = accounts[i].name;
    }
    return names;
}

97. AccountLoginFragment#storeAndroidAccount()

Project: jitsi-android
File: AccountLoginFragment.java
/**
     * Stores the given <tt>protocolProvider</tt> data in the android system
     * accounts.
     *
     * @param protocolProvider the <tt>ProtocolProviderService</tt>,
     * corresponding to the account to store
     */
private void storeAndroidAccount(ProtocolProviderService protocolProvider) {
    Map<String, String> accountProps = protocolProvider.getAccountID().getAccountProperties();
    String username = accountProps.get(ProtocolProviderFactory.USER_ID);
    Account account = new Account(username, getString(R.string.ACCOUNT_TYPE));
    final Bundle extraData = new Bundle();
    for (String key : accountProps.keySet()) {
        extraData.putString(key, accountProps.get(key));
    }
    AccountManager am = AccountManager.get(getActivity());
    boolean accountCreated = am.addAccountExplicitly(account, accountProps.get(ProtocolProviderFactory.PASSWORD), extraData);
    Bundle extras = getArguments();
    if (extras != null) {
        if (accountCreated) {
            //Pass the new account back to the account manager
            AccountAuthenticatorResponse response = extras.getParcelable(AccountManager.KEY_ACCOUNT_AUTHENTICATOR_RESPONSE);
            Bundle result = new Bundle();
            result.putString(AccountManager.KEY_ACCOUNT_NAME, username);
            result.putString(AccountManager.KEY_ACCOUNT_TYPE, getString(R.string.ACCOUNT_TYPE));
            result.putAll(extraData);
            response.onResult(result);
        }
    // TODO: notify about account authentication
    //finish();
    }
}

98. AndroidAuthenticator#getAuthToken()

Project: iosched
File: AndroidAuthenticator.java
// TODO: Figure out what to do about notifyAuthFailure
@SuppressWarnings("deprecation")
@Override
public String getAuthToken() throws AuthFailureError {
    final AccountManager accountManager = AccountManager.get(mContext);
    AccountManagerFuture<Bundle> future = accountManager.getAuthToken(mAccount, mAuthTokenType, mNotifyAuthFailure, null, null);
    Bundle result;
    try {
        result = future.getResult();
    } catch (Exception e) {
        throw new AuthFailureError("Error while retrieving auth token", e);
    }
    String authToken = null;
    if (future.isDone() && !future.isCancelled()) {
        if (result.containsKey(AccountManager.KEY_INTENT)) {
            Intent intent = result.getParcelable(AccountManager.KEY_INTENT);
            throw new AuthFailureError(intent);
        }
        authToken = result.getString(AccountManager.KEY_AUTHTOKEN);
    }
    if (authToken == null) {
        throw new AuthFailureError("Got null auth token for type: " + mAuthTokenType);
    }
    return authToken;
}

99. BaseActivity#setupAccountBox()

Project: iosched
File: BaseActivity.java
/**
     * Sets up the account box. The account box is the area at the top of the nav drawer that
     * shows which account the user is logged in as, and lets them switch accounts. It also
     * shows the user's Google+ cover photo as background.
     */
private void setupAccountBox() {
    mAccountListContainer = (LinearLayout) findViewById(R.id.account_list);
    if (mAccountListContainer == null) {
        //This activity does not have an account box
        return;
    }
    final View chosenAccountView = findViewById(R.id.chosen_account_view);
    Account chosenAccount = AccountUtils.getActiveAccount(this);
    if (chosenAccount == null) {
        // No account logged in; hide account box
        chosenAccountView.setVisibility(View.GONE);
        mAccountListContainer.setVisibility(View.GONE);
        return;
    } else {
        chosenAccountView.setVisibility(View.VISIBLE);
        mAccountListContainer.setVisibility(View.INVISIBLE);
    }
    AccountManager am = AccountManager.get(this);
    Account[] accountArray = am.getAccountsByType(GoogleAuthUtil.GOOGLE_ACCOUNT_TYPE);
    List<Account> accounts = new ArrayList<Account>(Arrays.asList(accountArray));
    accounts.remove(chosenAccount);
    ImageView coverImageView = (ImageView) chosenAccountView.findViewById(R.id.profile_cover_image);
    ImageView profileImageView = (ImageView) chosenAccountView.findViewById(R.id.profile_image);
    TextView nameTextView = (TextView) chosenAccountView.findViewById(R.id.profile_name_text);
    TextView email = (TextView) chosenAccountView.findViewById(R.id.profile_email_text);
    mExpandAccountBoxIndicator = (ImageView) findViewById(R.id.expand_account_box_indicator);
    String name = AccountUtils.getPlusName(this);
    if (name == null) {
        nameTextView.setVisibility(View.GONE);
    } else {
        nameTextView.setVisibility(View.VISIBLE);
        nameTextView.setText(name);
    }
    String imageUrl = AccountUtils.getPlusImageUrl(this);
    if (imageUrl != null) {
        mImageLoader.loadImage(imageUrl, profileImageView);
    }
    String coverImageUrl = AccountUtils.getPlusCoverUrl(this);
    if (coverImageUrl != null) {
        findViewById(R.id.profile_cover_image_placeholder).setVisibility(View.GONE);
        coverImageView.setVisibility(View.VISIBLE);
        coverImageView.setContentDescription(getResources().getString(R.string.navview_header_user_image_content_description));
        mImageLoader.loadImage(coverImageUrl, coverImageView);
        coverImageView.setColorFilter(getResources().getColor(R.color.light_content_scrim));
    }
    email.setText(chosenAccount.name);
    if (accounts.isEmpty()) {
        // There's only one account on the device, so no need for a switcher.
        mExpandAccountBoxIndicator.setVisibility(View.GONE);
        mAccountListContainer.setVisibility(View.GONE);
        chosenAccountView.setEnabled(false);
        return;
    }
    chosenAccountView.setEnabled(true);
    mExpandAccountBoxIndicator.setVisibility(View.VISIBLE);
    chosenAccountView.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View view) {
            mAccountBoxExpanded = !mAccountBoxExpanded;
            setupAccountBoxToggle();
        }
    });
    setupAccountBoxToggle();
    populateAccountList(accounts);
}

100. ForecastSyncAdapter#getSyncAccount()

Project: forecast
File: ForecastSyncAdapter.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.
     */
public 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;
}