android.accounts.Account

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

1. AuthenticationActivity#createOrGetAccount()

Project: retroauth
File: AuthenticationActivity.java
/**
     * Tries finding an existing account with the given name.
     * It creates a new Account if it couldn't find it
     *
     * @return The account if found, or a newly created one
     */
@NonNull
@SuppressWarnings("unused")
protected Account createOrGetAccount(@NonNull String accountName) {
    // if this is a relogin
    Account[] accountList = accountManager.getAccountsByType(accountType);
    for (Account account : accountList) {
        if (account.name.equals(accountName))
            return account;
    }
    Account account = new Account(accountName, accountType);
    accountManager.addAccountExplicitly(account, null, null);
    return account;
}

2. 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");
}

3. ClientManagerTest#testRemoveOneOfSeveralAccounts()

Project: SalesforceMobileSDK-Android
File: ClientManagerTest.java
/**
     * Test removeAccounts - removing one account where there are several
     */
public void testRemoveOneOfSeveralAccounts() {
    // Make sure we have no accounts initially
    assertNoAccounts();
    // Create two accounts
    createTestAccount();
    createOtherTestAccount();
    // Check that the accounts did get created
    Account[] accounts = clientManager.getAccounts();
    assertEquals("Two accounts should have been returned", 2, accounts.length);
    // Remove one of them
    clientManager.removeAccounts(new Account[] { accounts[0] });
    // Make sure the other account is still there
    Account[] accountsLeft = clientManager.getAccounts();
    assertEquals("One account should have been returned", 1, accountsLeft.length);
    assertEquals("Wrong account name", accounts[1].name, accountsLeft[0].name);
}

4. ClientManagerTest#testGetAccountByName()

Project: SalesforceMobileSDK-Android
File: ClientManagerTest.java
/**
     * Test getAccountByName
     */
public void testGetAccountByName() {
    // Make sure we have no accounts initially
    assertNoAccounts();
    // Create two accounts
    createTestAccount();
    createOtherTestAccount();
    // Check that the accounts did get created
    Account[] accounts = clientManager.getAccounts();
    assertEquals("Two accounts should have been returned", 2, accounts.length);
    // Get the first one by name
    Account account = clientManager.getAccountByName(TEST_ACCOUNT_NAME);
    assertNotNull("An account should have been returned", account);
    assertEquals("Wrong account name", TEST_ACCOUNT_NAME, account.name);
    assertEquals("Wrong account type", TEST_ACCOUNT_TYPE, account.type);
    // Get the second one by name
    account = clientManager.getAccountByName(TEST_OTHER_ACCOUNT_NAME);
    assertNotNull("An account should have been returned", account);
    assertEquals("Wrong account name", TEST_OTHER_ACCOUNT_NAME, account.name);
    assertEquals("Wrong account type", TEST_ACCOUNT_TYPE, account.type);
}

5. UserAccountManager#getAuthenticatedUsers()

Project: SalesforceMobileSDK-Android
File: UserAccountManager.java
/**
	 * Returns a list of authenticated users.
	 *
	 * @return List of authenticated users.
	 */
public List<UserAccount> getAuthenticatedUsers() {
    final Account[] accounts = accountManager.getAccountsByType(accountType);
    if (accounts == null || accounts.length == 0) {
        return null;
    }
    final List<UserAccount> userAccounts = new ArrayList<UserAccount>();
    for (final Account account : accounts) {
        final UserAccount userAccount = buildUserAccount(account);
        if (userAccount != null) {
            userAccounts.add(userAccount);
        }
    }
    if (userAccounts.size() == 0) {
        return null;
    }
    return userAccounts;
}

6. 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;
}

7. FeedbackFragment#setupEmailAutocomplete()

Project: frisbee
File: FeedbackFragment.java
private void setupEmailAutocomplete() {
    //Set email AutoCompleteTextView
    ArrayAdapter<String> adapter = new ArrayAdapter<>(getActivity(), android.R.layout.select_dialog_item);
    Set<String> accountsSet = new HashSet<>();
    Account[] deviceAccounts = AccountManager.get(getActivity()).getAccounts();
    for (Account account : deviceAccounts) {
        if (Utils.isEmailAddress(account.name)) {
            accountsSet.add(account.name);
        }
    }
    adapter.addAll(accountsSet);
    mEmailField.setAdapter(adapter);
}

8. EmailAutoCompleteLayout#createEmailAddressAdapter()

Project: EmailAutoCompleteTextView
File: EmailAutoCompleteLayout.java
private ArrayAdapter<String> createEmailAddressAdapter() {
    Account[] deviceAccounts = AccountManager.get(getContext()).getAccounts();
    for (Account account : deviceAccounts) {
        if (isEmailAddress(account.name)) {
            accounts.add(account.name);
        }
    }
    return new ArrayAdapter<>(getContext(), android.R.layout.select_dialog_item, new ArrayList<>(accounts));
}

9. EarthSharedState#getAccount()

Project: earth
File: EarthSharedState.java
public Account getAccount() {
    final Account[] accounts = am.getAccountsByType(StubAuthenticator.ACCOUNT_TYPE);
    if (accounts.length > 0) {
        return accounts[0];
    }
    final Account account = new Account(context.getString(R.string.free_account), StubAuthenticator.ACCOUNT_TYPE);
    am.addAccountExplicitly(account, null, Bundle.EMPTY);
    return account;
}

10. GTalkOAuth2#getAccount()

Project: ChatSecureAndroid
File: GTalkOAuth2.java
//help method for getting proper account
public static Account getAccount(String type, String name, AccountManager aMgr) {
    Account[] accounts = aMgr.getAccountsByType(type);
    if (name == null)
        return accounts[0];
    for (Account account : accounts) {
        if (account.name.equals(name)) {
            return account;
        }
    }
    return null;
}

11. AccountUtil#account()

Project: apps-android-wikipedia
File: AccountUtil.java
@Nullable
private static Account account(@NonNull String username) {
    Account[] accounts = accountManager().getAccountsByType(accountType());
    for (Account account : accounts) {
        if (username.equalsIgnoreCase(account.name)) {
            return account;
        }
    }
    return null;
}

12. 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);
}

13. FileActivity#swapToDefaultAccount()

Project: android
File: FileActivity.java
/**
     *  Tries to swap the current ownCloud {@link Account} for other valid and existing.
     *
     *  If no valid ownCloud {@link Account} exists, the the user is requested
     *  to create a new ownCloud {@link Account}.
     *
     *  POSTCONDITION: updates {@link #mAccountWasSet} and {@link #mAccountWasRestored}.
     */
private void swapToDefaultAccount() {
    // default to the most recently used account
    Account newAccount = AccountUtils.getCurrentOwnCloudAccount(getApplicationContext());
    if (newAccount == null) {
        /// no account available: force account creation
        createFirstAccount();
        mRedirectingToSetupAccount = true;
        mAccountWasSet = false;
        mAccountWasRestored = false;
    } else {
        mAccountWasSet = true;
        mAccountWasRestored = (newAccount.equals(mAccount));
        mAccount = newAccount;
    }
}

14. FileActivity#setAccount()

Project: android
File: FileActivity.java
/**
     *  Sets and validates the ownCloud {@link Account} associated to the Activity.
     *
     *  If not valid, tries to swap it for other valid and existing ownCloud {@link Account}.
     *
     *  POSTCONDITION: updates {@link #mAccountWasSet} and {@link #mAccountWasRestored}.
     *
     *  @param account          New {@link Account} to set.
     *  @param savedAccount     When 'true', account was retrieved from a saved instance state.
     */
protected void setAccount(Account account, boolean savedAccount) {
    Account oldAccount = mAccount;
    boolean validAccount = (account != null && AccountUtils.setCurrentOwnCloudAccount(getApplicationContext(), account.name));
    if (validAccount) {
        mAccount = account;
        mAccountWasSet = true;
        mAccountWasRestored = (savedAccount || mAccount.equals(oldAccount));
    } else {
        swapToDefaultAccount();
    }
}

15. DocumentsStorageProvider#initiateStorageMap()

Project: android
File: DocumentsStorageProvider.java
private void initiateStorageMap() {
    mRootIdToStorageManager = new HashMap<Long, FileDataStorageManager>();
    ContentResolver contentResolver = getContext().getContentResolver();
    for (Account account : AccountUtils.getAccounts(getContext())) {
        final FileDataStorageManager storageManager = new FileDataStorageManager(account, contentResolver);
        final OCFile rootDir = storageManager.getFileByPath("/");
        mRootIdToStorageManager.put(rootDir.getFileId(), storageManager);
    }
}

16. FileOperationsHelper#cancelTransference()

Project: android
File: FileOperationsHelper.java
/**
     * Cancel the transference in downloads (files/folders) and file uploads
     * @param file OCFile
     */
public void cancelTransference(OCFile file) {
    Account account = mFileActivity.getAccount();
    if (file.isFolder()) {
        OperationsService.OperationsServiceBinder opsBinder = mFileActivity.getOperationsServiceBinder();
        if (opsBinder != null) {
            opsBinder.cancel(account, file);
        }
    }
    // for both files and folders
    FileDownloaderBinder downloaderBinder = mFileActivity.getFileDownloaderBinder();
    if (downloaderBinder != null && downloaderBinder.isDownloading(account, file)) {
        downloaderBinder.cancel(account, file);
    }
    FileUploaderBinder uploaderBinder = mFileActivity.getFileUploaderBinder();
    if (uploaderBinder != null && uploaderBinder.isUploading(account, file)) {
        uploaderBinder.cancel(account, file);
    }
}

17. AccountUtils#exists()

Project: android
File: AccountUtils.java
public static boolean exists(Account account, Context context) {
    Account[] ocAccounts = getAccounts(context);
    if (account != null && account.name != null) {
        int lastAtPos = account.name.lastIndexOf("@");
        String hostAndPort = account.name.substring(lastAtPos + 1);
        String username = account.name.substring(0, lastAtPos);
        String otherHostAndPort, otherUsername;
        Locale currentLocale = context.getResources().getConfiguration().locale;
        for (Account otherAccount : ocAccounts) {
            lastAtPos = otherAccount.name.lastIndexOf("@");
            otherHostAndPort = otherAccount.name.substring(lastAtPos + 1);
            otherUsername = otherAccount.name.substring(0, lastAtPos);
            if (otherHostAndPort.equals(hostAndPort) && otherUsername.toLowerCase(currentLocale).equals(username.toLowerCase(currentLocale))) {
                return true;
            }
        }
    }
    return false;
}

18. SyncDeveloperAccountsService#addNewGoogleAccounts()

Project: andlytics
File: SyncDeveloperAccountsService.java
private void addNewGoogleAccounts(Account[] googleAccounts) {
    // add new accounts as hidden
    int added = 0;
    List<DeveloperAccount> developerAccounts = developerAccountManager.getAllDeveloperAccounts();
    for (Account googleAccount : googleAccounts) {
        DeveloperAccount account = DeveloperAccount.createHidden(googleAccount.name);
        if (!developerAccounts.contains(account)) {
            Log.d(TAG, "Adding  " + account);
            developerAccountManager.addDeveloperAccount(account);
            added++;
        }
    }
    Log.d(TAG, String.format("Added %d new Google accounts.", added));
}

19. SyncDeveloperAccountsService#onHandleIntent()

Project: andlytics
File: SyncDeveloperAccountsService.java
@Override
protected void onHandleIntent(Intent intent) {
    developerAccountManager = DeveloperAccountManager.getInstance(this);
    Account[] googleAccounts = AccountManager.get(this).getAccountsByType(AutosyncHandler.ACCOUNT_TYPE_GOOGLE);
    Log.d(TAG, "Synchornizing Andlytics developer accounts and Google accounts...");
    addNewGoogleAccounts(googleAccounts);
    removeStaleGoogleAccounts(googleAccounts);
    syncData();
}

20. AutosyncHandler#setAutosyncPeriod()

Project: andlytics
File: AutosyncHandler.java
/**
	 * Sets the sync period in minutes for the given account
	 * @param accountName
	 * @param periodInMins
	 */
public void setAutosyncPeriod(String accountName, Integer periodInMins) {
    Bundle extras = new Bundle();
    Account account = new Account(accountName, AutosyncHandler.ACCOUNT_TYPE_GOOGLE);
    if (periodInMins == 0) {
        ContentResolver.setSyncAutomatically(account, AutosyncHandler.ACCOUNT_AUTHORITY, false);
    } else {
        ContentResolver.setSyncAutomatically(account, AutosyncHandler.ACCOUNT_AUTHORITY, true);
        ContentResolver.addPeriodicSync(account, AutosyncHandler.ACCOUNT_AUTHORITY, extras, periodInMins * 60);
    }
}

21. AutosyncHandler#getAutosyncPeriod()

Project: andlytics
File: AutosyncHandler.java
/**
	 * Gets the sync period in minutes for the given account
	 * @param accountName
	 * @return The sync period in minutes
	 */
public int getAutosyncPeriod(String accountName) {
    int result = 0;
    Account account = new Account(accountName, AutosyncHandler.ACCOUNT_TYPE_GOOGLE);
    if (ContentResolver.getSyncAutomatically(account, AutosyncHandler.ACCOUNT_AUTHORITY)) {
        List<PeriodicSync> periodicSyncs = ContentResolver.getPeriodicSyncs(account, AutosyncHandler.ACCOUNT_AUTHORITY);
        for (PeriodicSync periodicSync : periodicSyncs) {
            result = 60 * (int) periodicSync.period;
            break;
        }
    }
    return result;
}

22. AdmobAuthenticatorActivity#finishLogin()

Project: andlytics
File: AdmobAuthenticatorActivity.java
private void finishLogin() {
    Account account = new Account(mUsername, AdmobAccountAuthenticator.ACCOUNT_TYPE_ADMOB);
    if (mRequestNewAccount) {
        mAccountManager.addAccountExplicitly(account, mPassword, null);
        ContentResolver.setSyncAutomatically(account, ContactsContract.AUTHORITY, true);
    } else {
        mAccountManager.setPassword(account, mPassword);
    }
    Intent intent = new Intent();
    mAuthtoken = mPassword;
    intent.putExtra(AccountManager.KEY_ACCOUNT_NAME, mUsername);
    intent.putExtra(AccountManager.KEY_ACCOUNT_TYPE, AdmobAccountAuthenticator.ACCOUNT_TYPE_ADMOB);
    if (mAuthtokenType != null && mAuthtokenType.equals(AdmobAccountAuthenticator.AUTHTOKEN_TYPE_ADMOB)) {
        intent.putExtra(AccountManager.KEY_AUTHTOKEN, mAuthtoken);
    }
    setAccountAuthenticatorResult(intent.getExtras());
    setResult(RESULT_OK, intent);
    finish();
}

23. 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;
}

24. SunshineSyncAdapter#configurePeriodicSync()

Project: Advanced_Android_Development
File: SunshineSyncAdapter.java
/**
     * Helper method to schedule the sync adapter periodic execution
     */
public static void configurePeriodicSync(Context context, int syncInterval, int flexTime) {
    Account account = getSyncAccount(context);
    String authority = context.getString(R.string.content_authority);
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
        // we can enable inexact timers in our periodic sync
        SyncRequest request = new SyncRequest.Builder().syncPeriodic(syncInterval, flexTime).setSyncAdapter(account, authority).setExtras(new Bundle()).build();
        ContentResolver.requestSync(request);
    } else {
        ContentResolver.addPeriodicSync(account, authority, new Bundle(), syncInterval);
    }
}

25. LoginActivity#tokenCreated()

Project: WeGit
File: LoginActivity.java
@Override
public void tokenCreated(String token) {
    String accountName = username.getText().toString();
    String accountPassword = password.getText().toString();
    PreferenceUtils.putString(this, PreferenceUtils.Key.ACCOUNT, accountName);
    final Account account = new Account(accountName, accountType);
    if (getIntent().getBooleanExtra(Authenticator.ARG_IS_ADDING_NEW_ACCOUNT, true)) {
        mAccountManager.addAccountExplicitly(account, accountPassword, null);
        mAccountManager.setAuthToken(account, mAuthTokenType, token);
    } else {
        mAccountManager.setPassword(account, accountPassword);
    }
    //Save token created from loginActivity
    ((GithubApplication) this.getApplication()).setToken(token);
    Bundle bundle = new Bundle();
    bundle.putString(AccountManager.KEY_ACCOUNT_NAME, accountName);
    bundle.putString(AccountManager.KEY_ACCOUNT_TYPE, accountType);
    bundle.putString(AccountManager.KEY_AUTHTOKEN, token);
    bundle.putString(Authenticator.PARAM_USER_PASS, accountPassword);
    setAccountAuthenticatorResult(bundle);
    setResult(RESULT_OK, new Intent().putExtras(bundle));
    finish();
}

26. SunshineSyncAdapter#configurePeriodicSync()

Project: UdacityAndroidWear
File: SunshineSyncAdapter.java
/**
     * Helper method to schedule the sync adapter periodic execution
     */
public static void configurePeriodicSync(Context context, int syncInterval, int flexTime) {
    Account account = getSyncAccount(context);
    String authority = context.getString(R.string.content_authority);
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
        // we can enable inexact timers in our periodic sync
        SyncRequest request = new SyncRequest.Builder().syncPeriodic(syncInterval, flexTime).setSyncAdapter(account, authority).setExtras(new Bundle()).build();
        ContentResolver.requestSync(request);
    } else {
        ContentResolver.addPeriodicSync(account, authority, new Bundle(), syncInterval);
    }
}

27. SunshineSyncAdapter#configurePeriodicSync()

Project: Sunshine-Version-2
File: SunshineSyncAdapter.java
/**
     * Helper method to schedule the sync adapter periodic execution
     */
public static void configurePeriodicSync(Context context, int syncInterval, int flexTime) {
    Account account = getSyncAccount(context);
    String authority = context.getString(R.string.content_authority);
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
        // we can enable inexact timers in our periodic sync
        SyncRequest request = new SyncRequest.Builder().syncPeriodic(syncInterval, flexTime).setSyncAdapter(account, authority).setExtras(new Bundle()).build();
        ContentResolver.requestSync(request);
    } else {
        ContentResolver.addPeriodicSync(account, authority, new Bundle(), syncInterval);
    }
}

28. SgSyncAdapter#isSyncActive()

Project: SeriesGuide
File: SgSyncAdapter.java
/**
     * Returns true if there is currently a sync operation for the given account or authority in the
     * pending list, or actively being processed.
     */
public static boolean isSyncActive(Context context, boolean isDisplayWarning) {
    Account account = AccountUtils.getAccount(context);
    if (account == null) {
        return false;
    }
    boolean isSyncActive = ContentResolver.isSyncActive(account, SeriesGuideApplication.CONTENT_AUTHORITY);
    if (isSyncActive && isDisplayWarning) {
        Toast.makeText(context, R.string.update_inprogress, Toast.LENGTH_LONG).show();
    }
    return isSyncActive;
}

29. SgSyncAdapter#requestSyncIfTime()

Project: SeriesGuide
File: SgSyncAdapter.java
/**
     * Calls {@link ContentResolver} {@code .requestSyncIfConnected()} if there is no pending sync
     * already.
     */
public static void requestSyncIfTime(Context context) {
    // guard against scheduling too many sync requests
    Account account = AccountUtils.getAccount(context);
    if (account == null || ContentResolver.isSyncPending(account, SeriesGuideApplication.CONTENT_AUTHORITY)) {
        return;
    }
    if (!isTimeForSync(context, System.currentTimeMillis())) {
        return;
    }
    SgSyncAdapter.requestSyncIfConnected(context, SyncType.DELTA, 0);
}

30. 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;
}

31. ClientManagerTest#testRemoveSeveralAccounts()

Project: SalesforceMobileSDK-Android
File: ClientManagerTest.java
/**
     * Test removeAccounts - removing two accounts
     */
public void testRemoveSeveralAccounts() {
    // Make sure we have no accounts initially
    assertNoAccounts();
    // Create two accounts
    createTestAccount();
    createOtherTestAccount();
    // Check that the accounts did get created
    Account[] accounts = clientManager.getAccounts();
    assertEquals("Two accounts should have been returned", 2, accounts.length);
    // Remove one of them
    clientManager.removeAccounts(accounts);
    // Make sure there are no accounts left
    assertNoAccounts();
}

32. ClientManagerTest#testRemoveOnlyAccount()

Project: SalesforceMobileSDK-Android
File: ClientManagerTest.java
/**
     * Test removeAccounts when there is only one
     */
public void testRemoveOnlyAccount() {
    // Make sure we have no accounts initially
    assertNoAccounts();
    // Create an account
    createTestAccount();
    // Check that the account did get created
    Account[] accounts = clientManager.getAccounts();
    assertEquals("One account should have been returned", 1, accounts.length);
    assertEquals("Wrong account name", TEST_ACCOUNT_NAME, accounts[0].name);
    // Remove the account
    clientManager.removeAccounts(accounts);
    // Make sure there are no accounts left
    assertNoAccounts();
}

33. ClientManagerTest#testGetAccountsWithSeveralAccounts()

Project: SalesforceMobileSDK-Android
File: ClientManagerTest.java
/**
     * Test getAccounts - when there are several accounts
     */
public void testGetAccountsWithSeveralAccounts() {
    // Make sure we have no accounts initially
    assertNoAccounts();
    // Call two accounts
    createTestAccount();
    createOtherTestAccount();
    // Call getAccounts
    Account[] accounts = clientManager.getAccounts();
    assertEquals("Two accounts should have been returned", 2, accounts.length);
    // Sorting
    Arrays.sort(accounts, new Comparator<Account>() {

        @Override
        public int compare(Account account1, Account account2) {
            return account1.name.compareTo(account2.name);
        }
    });
    assertEquals("Wrong account name", TEST_ACCOUNT_NAME, accounts[0].name);
    assertEquals("Wrong account name", TEST_OTHER_ACCOUNT_NAME, accounts[1].name);
}

34. ClientManagerTest#testGetAccountsWithSingleAccount()

Project: SalesforceMobileSDK-Android
File: ClientManagerTest.java
/**
     * Test getAccounts - when there is only one
     */
public void testGetAccountsWithSingleAccount() {
    // Make sure we have no accounts initially
    assertNoAccounts();
    // Call createNewAccount
    createTestAccount();
    // Call getAccounts
    Account[] accounts = clientManager.getAccounts();
    assertEquals("One account should have been returned", 1, accounts.length);
    assertEquals("Wrong account name", TEST_ACCOUNT_NAME, accounts[0].name);
    assertEquals("Wrong account type", TEST_ACCOUNT_TYPE, accounts[0].type);
}

35. ClientManagerTest#testCreateAccount()

Project: SalesforceMobileSDK-Android
File: ClientManagerTest.java
/**
     * Test createNewAccount
     */
public void testCreateAccount() {
    // Make sure we have no accounts initially
    assertNoAccounts();
    // Call createNewAccount
    createTestAccount();
    // Check that the account did get created
    Account[] accounts = clientManager.getAccounts();
    assertEquals("One account should have been returned", 1, accounts.length);
    assertEquals("Wrong account name", TEST_ACCOUNT_NAME, accounts[0].name);
    assertEquals("Wrong account type", TEST_ACCOUNT_TYPE, accounts[0].type);
}

36. ClientManager#removeAccounts()

Project: SalesforceMobileSDK-Android
File: ClientManager.java
/**
     * Remove all of the accounts passed in.
     *
     * @param accounts The array of accounts to remove.
     */
public void removeAccounts(Account[] accounts) {
    List<AccountManagerFuture<Boolean>> removalFutures = new ArrayList<AccountManagerFuture<Boolean>>();
    for (Account a : accounts) {
        removalFutures.add(accountManager.removeAccount(a, null, null));
    }
    for (AccountManagerFuture<Boolean> f : removalFutures) {
        try {
            f.getResult();
        } catch (Exception ex) {
            Log.w("ClientManager:removeAccounts", "Exception removing old account", ex);
        }
    }
}

37. ClientManager#getRestClient()

Project: SalesforceMobileSDK-Android
File: ClientManager.java
/**
     * Method to create a RestClient asynchronously. It is intended to be used by code on the UI thread.
     *
     * If no accounts are found, it will kick off the login flow which will create a new account if successful.
     * After the account is created or if an account already existed, it creates a RestClient and returns it through restClientCallback.
     *
     * Note: The work is actually being done by the service registered to handle authentication for this application account type.
     * @see AuthenticatorService
     *
     * @param activityContext        current activity
     * @param restClientCallback     callback invoked once the RestClient is ready
     */
public void getRestClient(Activity activityContext, RestClientCallback restClientCallback) {
    Account acc = getAccount();
    // Passing the passcodeHash to the authenticator service to that it can encrypt/decrypt oauth tokens
    Bundle options = loginOptions.asBundle();
    // No account found - let's add one - the AuthenticatorService add account method will start the login activity
    if (acc == null) {
        Log.i("ClientManager:getRestClient", "No account of type " + accountType + " found");
        accountManager.addAccount(getAccountType(), AccountManager.KEY_AUTHTOKEN, null, /*required features*/
        options, activityContext, new AccMgrCallback(restClientCallback), null);
    } else // Account found
    {
        Log.i("ClientManager:getRestClient", "Found account of type " + accountType);
        accountManager.getAuthToken(acc, AccountManager.KEY_AUTHTOKEN, options, activityContext, new AccMgrCallback(restClientCallback), null);
    }
}

38. UserAccountManager#switchToUser()

Project: SalesforceMobileSDK-Android
File: UserAccountManager.java
/**
	 * Switches to the specified user account. If the specified user account
	 * is invalid/doesn't exist, this method kicks off the login flow
	 * for a new user. When the user account switch is complete, it is
	 * imperative for the app to update its cached references to RestClient,
	 * to avoid holding on to a RestClient from the previous user.
	 *
	 * @param user User account to switch to.
	 */
public void switchToUser(UserAccount user) {
    if (user == null || !doesUserAccountExist(user)) {
        switchToNewUser();
        return;
    }
    final UserAccount curUser = getCurrentUser();
    /*
		 * Checks if we are attempting to switch to the current user.
		 * In this case, there's nothing to be done.
		 */
    if (user.equals(curUser)) {
        return;
    }
    final ClientManager cm = new ClientManager(context, accountType, SalesforceSDKManager.getInstance().getLoginOptions(), true);
    final Account account = cm.getAccountByName(user.getAccountName());
    storeCurrentUserInfo(user.getUserId(), user.getOrgId());
    cm.peekRestClient(account);
    sendUserSwitchIntent();
}

39. DataManagerTest#signInSuccessful()

Project: ribot-app-android
File: DataManagerTest.java
@Test
public void signInSuccessful() {
    // Stub GoogleAuthHelper and RibotService mocks
    RibotService.SignInResponse signInResponse = new RibotService.SignInResponse();
    signInResponse.ribot = MockModelFabric.newRibot();
    signInResponse.accessToken = MockModelFabric.randomString();
    Account account = new Account("[email protected]", "google.com");
    String googleAccessCode = MockModelFabric.randomString();
    doReturn(Observable.just(googleAccessCode)).when(mMockGoogleAuthHelper).retrieveAuthTokenAsObservable(account);
    doReturn(Observable.just(signInResponse)).when(mMockRibotsService).signIn(any(RibotService.SignInRequest.class));
    // Test the sign in Observable
    TestSubscriber<Ribot> testSubscriber = new TestSubscriber<>();
    mDataManager.signIn(account).subscribe(testSubscriber);
    testSubscriber.assertValue(signInResponse.ribot);
    testSubscriber.assertCompleted();
    testSubscriber.assertNoErrors();
    verify(mMockPreferencesHelper).putAccessToken(signInResponse.accessToken);
    verify(mMockPreferencesHelper).putSignedInRibot(signInResponse.ribot);
}

40. Preferences#getKeyserverSyncEnabled()

Project: open-keychain
File: Preferences.java
/**
     * @return true if a periodic sync exists and is set to run automatically, false otherwise
     */
public static boolean getKeyserverSyncEnabled(Context context) {
    Account account = KeychainApplication.createAccountIfNecessary(context);
    if (account == null) {
        // if the account could not be created for some reason, we can't have a sync
        return false;
    }
    String authority = Constants.PROVIDER_AUTHORITY;
    return ContentResolver.getSyncAutomatically(account, authority) && !ContentResolver.getPeriodicSyncs(account, authority).isEmpty();
}

41. ContactSyncAdapterService#deleteIfSyncDisabled()

Project: open-keychain
File: ContactSyncAdapterService.java
public static void deleteIfSyncDisabled(Context context) {
    if (!(ContextCompat.checkSelfPermission(context, Manifest.permission.READ_CONTACTS) == PackageManager.PERMISSION_GRANTED)) {
        return;
    }
    Account account = KeychainApplication.createAccountIfNecessary(context);
    if (account == null) {
        return;
    }
    // if user has disabled automatic sync, delete linked OpenKeychain contacts
    if (!ContentResolver.getSyncAutomatically(account, ContactsContract.AUTHORITY)) {
        new ContactHelper(context).deleteAllContacts();
    }
}

42. AccountDialog4#onCreateDialog()

Project: NotePad
File: AccountDialog4.java
@Override
public Dialog onCreateDialog(Bundle args) {
    AlertDialog.Builder builder = new AlertDialog.Builder(activity);
    builder.setTitle(R.string.select_account);
    final Account[] accounts = AccountManager.get(activity).getAccountsByType("com.google");
    final int size = accounts.length;
    String[] names = new String[size];
    for (int i = 0; i < size; i++) {
        names[i] = accounts[i].name;
    }
    // TODO
    // Could add a clear alternative here
    builder.setItems(names, new DialogInterface.OnClickListener() {

        public void onClick(DialogInterface dialog, int which) {
            // Stuff to do when the account is selected by the user
            accountSelected(accounts[which]);
        }
    });
    return builder.create();
}

43. DialogGoogleAccount#onCreateDialog()

Project: NotePad
File: DialogGoogleAccount.java
@Override
public Dialog onCreateDialog(Bundle args) {
    AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
    builder.setTitle(R.string.select_account);
    final Account[] accounts = AccountManager.get(getActivity()).getAccountsByType("com.google");
    final int size = accounts.length;
    String[] names = new String[size];
    for (int i = 0; i < size; i++) {
        names[i] = accounts[i].name;
    }
    builder.setItems(names, new DialogInterface.OnClickListener() {

        public void onClick(DialogInterface dialog, int which) {
            // Stuff to do when the account is selected by the user
            accountSelected(accounts[which]);
        }
    });
    return builder.create();
}

44. SyncCard#enableSync()

Project: narrate-android
File: SyncCard.java
private void enableSync() {
    Account acc = User.getAccount();
    ContentResolver.setIsSyncable(acc, Contract.AUTHORITY, 1);
    ContentResolver.setSyncAutomatically(acc, Contract.AUTHORITY, true);
    ContentResolver.removePeriodicSync(acc, Contract.AUTHORITY, Bundle.EMPTY);
    long interval = Settings.getAutoSyncInterval();
    if (interval > 0) {
        ContentResolver.addPeriodicSync(acc, Contract.AUTHORITY, Bundle.EMPTY, interval);
    }
    Bundle b = new Bundle();
    b.putBoolean("resync_files", true);
    SyncHelper.requestManualSync(acc, b);
    Toast.makeText(GlobalApplication.getAppContext(), GlobalApplication.getAppContext().getString(R.string.data_resyncing), Toast.LENGTH_SHORT).show();
}

45. 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;
    }
}

46. FileActivity#swapToDefaultAccount()

Project: MyRepository-master
File: FileActivity.java
/**
     *  Tries to swap the current ownCloud {@link Account} for other valid and existing.
     *
     *  If no valid ownCloud {@link Account} exists, the the user is requested
     *  to create a new ownCloud {@link Account}.
     *
     *  POSTCONDITION: updates {@link #mAccountWasSet} and {@link #mAccountWasRestored}.
     */
private void swapToDefaultAccount() {
    // default to the most recently used account
    Account newAccount = AccountUtils.getCurrentOwnCloudAccount(getApplicationContext());
    if (newAccount == null) {
        /// no account available: force account creation
        createFirstAccount();
        mRedirectingToSetupAccount = true;
        mAccountWasSet = false;
        mAccountWasRestored = false;
    } else {
        mAccountWasSet = true;
        mAccountWasRestored = (newAccount.equals(mAccount));
        mAccount = newAccount;
    }
}

47. FileActivity#setAccount()

Project: MyRepository-master
File: FileActivity.java
/**
     *  Sets and validates the ownCloud {@link Account} associated to the Activity.
     *
     *  If not valid, tries to swap it for other valid and existing ownCloud {@link Account}.
     *
     *  POSTCONDITION: updates {@link #mAccountWasSet} and {@link #mAccountWasRestored}.
     *
     *  @param account          New {@link Account} to set.
     *  @param savedAccount     When 'true', account was retrieved from a saved instance state.
     */
protected void setAccount(Account account, boolean savedAccount) {
    Account oldAccount = mAccount;
    boolean validAccount = (account != null && AccountUtils.setCurrentOwnCloudAccount(getApplicationContext(), account.name));
    if (validAccount) {
        mAccount = account;
        mAccountWasSet = true;
        mAccountWasRestored = (savedAccount || mAccount.equals(oldAccount));
    } else {
        swapToDefaultAccount();
    }
}

48. FileOperationsHelper#cancelTransference()

Project: MyRepository-master
File: FileOperationsHelper.java
/**
     * Cancel the transference in downloads (files/folders) and file uploads
     * @param file OCFile
     */
public void cancelTransference(OCFile file) {
    Account account = mFileActivity.getAccount();
    if (file.isFolder()) {
        OperationsService.OperationsServiceBinder opsBinder = mFileActivity.getOperationsServiceBinder();
        if (opsBinder != null) {
            opsBinder.cancel(account, file);
        }
    }
    // for both files and folders
    FileDownloaderBinder downloaderBinder = mFileActivity.getFileDownloaderBinder();
    if (downloaderBinder != null && downloaderBinder.isDownloading(account, file)) {
        downloaderBinder.cancel(account, file);
    }
    FileUploaderBinder uploaderBinder = mFileActivity.getFileUploaderBinder();
    if (uploaderBinder != null && uploaderBinder.isUploading(account, file)) {
        uploaderBinder.cancel(account, file);
    }
}

49. AccountUtils#exists()

Project: MyRepository-master
File: AccountUtils.java
public static boolean exists(Account account, Context context) {
    Account[] ocAccounts = AccountManager.get(context).getAccountsByType(MainApp.getAccountType());
    if (account != null && account.name != null) {
        int lastAtPos = account.name.lastIndexOf("@");
        String hostAndPort = account.name.substring(lastAtPos + 1);
        String username = account.name.substring(0, lastAtPos);
        String otherHostAndPort, otherUsername;
        Locale currentLocale = context.getResources().getConfiguration().locale;
        for (Account otherAccount : ocAccounts) {
            lastAtPos = otherAccount.name.lastIndexOf("@");
            otherHostAndPort = otherAccount.name.substring(lastAtPos + 1);
            otherUsername = otherAccount.name.substring(0, lastAtPos);
            if (otherHostAndPort.equals(hostAndPort) && otherUsername.toLowerCase(currentLocale).equals(username.toLowerCase(currentLocale))) {
                return true;
            }
        }
    }
    return false;
}

50. UserServicesClientTest#setUp()

Project: materialistic
File: UserServicesClientTest.java
@Before
public void setUp() {
    MockitoAnnotations.initMocks(this);
    call = mock(Call.class);
    Call.Factory callFactory = mock(Call.Factory.class);
    when(callFactory.newCall(any(Request.class))).thenReturn(call);
    userServices = new UserServicesClient(callFactory);
    Preferences.setUsername(RuntimeEnvironment.application, "username");
    account = new Account("username", BuildConfig.APPLICATION_ID);
    ShadowAccountManager.get(RuntimeEnvironment.application).addAccountExplicitly(account, "password", null);
}

51. BaseActivity#onAuthSuccess()

Project: iosched
File: BaseActivity.java
/**
     * Called when authentication succeeds. This may either happen because the user just
     * authenticated for the first time (and went through the sign in flow), or because it's
     * a returning user.
     *
     * @param accountName        name of the account that just authenticated successfully.
     * @param newlyAuthenticated If true, this user just authenticated for the first time.
     *                           If false, it's a returning user.
     */
@Override
public void onAuthSuccess(String accountName, boolean newlyAuthenticated) {
    Account account = new Account(accountName, GoogleAuthUtil.GOOGLE_ACCOUNT_TYPE);
    LOGD(TAG, "onAuthSuccess, account " + accountName + ", newlyAuthenticated=" + newlyAuthenticated);
    refreshAccountDependantData();
    if (newlyAuthenticated) {
        LOGD(TAG, "Enabling auto sync on content provider for account " + accountName);
        SyncHelper.updateSyncInterval(this, account);
        SyncHelper.requestManualSync(account);
    }
    setupAccountBox();
    populateNavDrawer();
    registerGCMClient();
}

52. 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);
    }
}

53. TriggerSyncReceiver#onReceive()

Project: iosched
File: TriggerSyncReceiver.java
@Override
public void onReceive(Context context, Intent intent) {
    String accountName = AccountUtils.getActiveAccountName(context);
    if (TextUtils.isEmpty(accountName)) {
        return;
    }
    Account account = AccountUtils.getActiveAccount(context);
    if (account != null) {
        if (intent.getBooleanExtra(EXTRA_USER_DATA_SYNC_ONLY, false)) {
            // this is a request to sync user data only, so do a manual sync right now
            // with the userDataOnly == true.
            SyncHelper.requestManualSync(account, true);
        } else {
            // this is a request to sync everything
            ContentResolver.requestSync(account, ScheduleContract.CONTENT_AUTHORITY, new Bundle());
        }
    }
}

54. GitHubAuthenticatorActivity#finishLogin()

Project: hubroid
File: GitHubAuthenticatorActivity.java
/**
     * Called when response is received from the server for authentication request. See
     * onAuthenticationResult(). Sets the AccountAuthenticatorResult which is sent back to the
     * caller. Also sets the mAuthToken in AccountManager for this account.
     */
protected void finishLogin() {
    final Account account = new Account(mLogin, GITHUB_ACCOUNT_TYPE);
    if (mRequestNewAccount) {
        mAccountManager.addAccountExplicitly(account, mPassword, null);
    } else {
        mAccountManager.setPassword(account, mPassword);
    }
    final Intent intent = new Intent();
    mAuthToken = mPassword;
    intent.putExtra(KEY_ACCOUNT_NAME, mLogin);
    intent.putExtra(KEY_ACCOUNT_TYPE, GITHUB_ACCOUNT_TYPE);
    if (mAuthTokenType != null && mAuthTokenType.equals(AuthConstants.AUTHTOKEN_TYPE)) {
        intent.putExtra(KEY_AUTHTOKEN, mAuthToken);
    }
    setAccountAuthenticatorResult(intent.getExtras());
    setResult(RESULT_OK, intent);
    finish();
}

55. AccountsAdapter#onBindViewHolder()

Project: Gitskarios
File: AccountsAdapter.java
@Override
public void onBindViewHolder(Holder holder, int position) {
    Account account = accounts[position];
    String userAvatar = AccountsHelper.getUserAvatar(context, account);
    String userName = AccountsHelper.getUserName(context, account);
    String userMail = AccountsHelper.getUserMail(context, account);
    ImageLoader.getInstance().displayImage(userAvatar, holder.profileIcon);
    holder.name.setText(userName);
    holder.email.setText(userMail);
}

56. 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);
}

57. 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);
}

58. SyncUtils#setSyncPeriodic()

Project: framework
File: SyncUtils.java
public void setSyncPeriodic(String authority, long interval_in_minute, long seconds_per_minute, long milliseconds_per_second) {
    Account account = mUser.getAccount();
    Bundle extras = new Bundle();
    this.setAutoSync(authority, true);
    ContentResolver.setIsSyncable(account, authority, 1);
    final long sync_interval = interval_in_minute * seconds_per_minute * milliseconds_per_second;
    ContentResolver.addPeriodicSync(account, authority, extras, sync_interval);
}

59. 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;
}

60. ForecastSyncAdapter#configurePeriodicSync()

Project: forecast
File: ForecastSyncAdapter.java
/**
     * Helper method to schedule the sync adapter periodic execution
     */
public static void configurePeriodicSync(Context context, int syncInterval, int flexTime) {
    Account account = getSyncAccount(context);
    String authority = context.getString(R.string.content_authority);
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
        // we can enable inexact timers in our periodic sync
        SyncRequest request = new SyncRequest.Builder().syncPeriodic(syncInterval, flexTime).setSyncAdapter(account, authority).setExtras(new Bundle()).build();
        ContentResolver.requestSync(request);
    } else {
        ContentResolver.addPeriodicSync(account, authority, new Bundle(), syncInterval);
    }
}

61. 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;
}

62. 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);
}

63. AccountUtil#removeAccount()

Project: apps-android-wikipedia
File: AccountUtil.java
@TargetApi(Build.VERSION_CODES.LOLLIPOP_MR1)
public static void removeAccount() {
    Account account = account();
    if (account != null) {
        if (ApiUtil.hasLollipopMr1()) {
            accountManager().removeAccountExplicitly(account);
        } else {
            //noinspection deprecation
            accountManager().removeAccount(account, null, null);
        }
    }
}

64. AccountUtil#createAccount()

Project: apps-android-wikipedia
File: AccountUtil.java
public static void createAccount(@Nullable AccountAuthenticatorResponse response, String username, String password) {
    Account account = new Account(username, accountType());
    boolean created = accountManager().addAccountExplicitly(account, password, null);
    L.i("account creation " + (created ? "successful" : "failure"));
    if (created) {
        if (response != null) {
            Bundle bundle = new Bundle();
            bundle.putString(AccountManager.KEY_ACCOUNT_NAME, username);
            bundle.putString(AccountManager.KEY_ACCOUNT_TYPE, accountType());
            response.onResult(bundle);
        }
        UserOptionContentResolver.requestManualSync();
    } else {
        if (response != null) {
            response.onError(AccountManager.ERROR_CODE_REMOTE_EXCEPTION, "");
        }
        L.d("account creation failure");
    }
}

65. SunshineSyncAdapter#configurePeriodicSync()

Project: Angani
File: SunshineSyncAdapter.java
/**
     * Helper method to schedule the sync adapter periodic execution
     */
public static void configurePeriodicSync(Context context, int syncInterval, int flexTime) {
    Account account = getSyncAccount(context);
    String authority = context.getString(R.string.content_authority);
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
        // we can enable inexact timers in our periodic sync
        SyncRequest request = new SyncRequest.Builder().syncPeriodic(syncInterval, flexTime).setSyncAdapter(account, authority).setExtras(new Bundle()).build();
        ContentResolver.requestSync(request);
    } else {
        ContentResolver.addPeriodicSync(account, authority, new Bundle(), syncInterval);
    }
}

66. NumberValidation#completeLogin()

Project: androidclient
File: NumberValidation.java
private void completeLogin(String serverUri, byte[] privateKeyData, byte[] publicKeyData, Map<String, String> trustedKeys) {
    // generate the bridge certificate
    byte[] bridgeCertData;
    try {
        bridgeCertData = X509Bridge.createCertificate(privateKeyData, publicKeyData, mPassphrase).getEncoded();
    } catch (Exception e) {
        throw new RuntimeException("unable to build X.509 bridge certificate", e);
    }
    final Account account = new Account(mPhoneNumber, Authenticator.ACCOUNT_TYPE);
    // workaround for bug in AccountManager (http://stackoverflow.com/a/11698139/1045199)
    // procedure will continue in removeAccount callback
    mAccountManager.removeAccount(account, new AccountRemovalCallback(this, account, mPassphrase, privateKeyData, publicKeyData, bridgeCertData, mName, serverUri, trustedKeys), mHandler);
}

67. 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;
}

68. SyncAdapter#requestSync()

Project: androidclient
File: SyncAdapter.java
/**
     * Requests a manual sync to the system.
     * @return true if the sync has been actually requested to the system.
     */
public static boolean requestSync(Context context, boolean force) {
    if (!force && isThrottling(context)) {
        Log.d(TAG, "not requesting sync - throttling");
        return false;
    }
    // do not start if offline
    if (Preferences.getOfflineMode(context)) {
        Log.d(TAG, "not requesting sync - offline mode");
        return false;
    }
    Account acc = Authenticator.getDefaultAccount(context);
    Bundle extra = new Bundle();
    // override auto-sync and background data settings
    extra.putBoolean(ContentResolver.SYNC_EXTRAS_MANUAL, true);
    // put our sync ahead of other sync operations :)
    extra.putBoolean(ContentResolver.SYNC_EXTRAS_EXPEDITED, true);
    ContentResolver.requestSync(acc, ContactsContract.AUTHORITY, extra);
    return true;
}

69. 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));
    }
}

70. 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));
}

71. 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;
}

72. 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];
}

73. SyncAdapter#triggerSync()

Project: android-clean-sample-app
File: SyncAdapter.java
/**
     * This method will start a sync adapter that will upload data to the server.
     */
public static void triggerSync(Context context) {
    // TODO sync adapter is forced for debugging purposes, remove this in production
    // Pass the settings flags by inserting them in a bundle
    Bundle settingsBundle = new Bundle();
    settingsBundle.putBoolean(ContentResolver.SYNC_EXTRAS_MANUAL, true);
    settingsBundle.putBoolean(ContentResolver.SYNC_EXTRAS_EXPEDITED, true);
    // request a sync using sync adapter
    Account account = AuthUtils.getAccount(context);
    ContentResolver.requestSync(account, context.getString(R.string.stub_content_authority), settingsBundle);
}

74. RepeatTestsGtasksSync#initializeTestService()

Project: astrid
File: RepeatTestsGtasksSync.java
private void initializeTestService() throws Exception {
    GoogleAccountManager manager = new GoogleAccountManager(ContextManager.getContext());
    Account[] accounts = manager.getAccounts();
    Account toUse = null;
    for (Account a : accounts) {
        if (a.name.equals(TEST_ACCOUNT)) {
            toUse = a;
            break;
        }
    }
    if (toUse == null) {
        if (accounts.length == 0) {
            return;
        }
        toUse = accounts[0];
    }
    Preferences.setString(GtasksPreferenceService.PREF_USER_NAME, toUse.name);
    AccountManagerFuture<Bundle> accountManagerFuture = manager.manager.getAuthToken(toUse, "oauth2:https://www.googleapis.com/auth/tasks", true, null, null);
    Bundle authTokenBundle = accountManagerFuture.getResult();
    if (authTokenBundle.containsKey(AccountManager.KEY_INTENT)) {
        Intent i = (Intent) authTokenBundle.get(AccountManager.KEY_INTENT);
        ContextManager.getContext().startActivity(i);
        return;
    }
    String authToken = authTokenBundle.getString(AccountManager.KEY_AUTHTOKEN);
    authToken = GtasksTokenValidator.validateAuthToken(getContext(), authToken);
    gtasksPreferenceService.setToken(authToken);
    gtasksService = new GtasksInvoker(authToken);
    initialized = true;
}

75. GtasksSyncOnSaveTest#initializeTestService()

Project: astrid
File: GtasksSyncOnSaveTest.java
private void initializeTestService() throws Exception {
    GoogleAccountManager manager = new GoogleAccountManager(ContextManager.getContext());
    Account[] accounts = manager.getAccounts();
    Account toUse = null;
    for (Account a : accounts) {
        if (a.name.equals(TEST_ACCOUNT)) {
            toUse = a;
            break;
        }
    }
    if (toUse == null) {
        if (accounts.length == 0) {
            bypassTests = true;
            return;
        }
        toUse = accounts[0];
    }
    Preferences.setString(GtasksPreferenceService.PREF_USER_NAME, toUse.name);
    AccountManagerFuture<Bundle> accountManagerFuture = manager.manager.getAuthToken(toUse, "oauth2:https://www.googleapis.com/auth/tasks", true, null, null);
    Bundle authTokenBundle = accountManagerFuture.getResult();
    if (authTokenBundle.containsKey(AccountManager.KEY_INTENT)) {
        Intent i = (Intent) authTokenBundle.get(AccountManager.KEY_INTENT);
        ContextManager.getContext().startActivity(i);
        return;
    }
    String authToken = authTokenBundle.getString(AccountManager.KEY_AUTHTOKEN);
    authToken = GtasksTokenValidator.validateAuthToken(getContext(), authToken);
    gtasksPreferenceService.setToken(authToken);
    gtasksService = new GtasksInvoker(authToken);
    initialized = true;
}

76. GtasksNewSyncTest#initializeTestService()

Project: astrid
File: GtasksNewSyncTest.java
private void initializeTestService() throws Exception {
    GoogleAccountManager manager = new GoogleAccountManager(ContextManager.getContext());
    Account[] accounts = manager.getAccounts();
    Account toUse = null;
    for (Account a : accounts) {
        if (a.name.equals(TEST_ACCOUNT)) {
            toUse = a;
            break;
        }
    }
    if (toUse == null) {
        if (accounts.length == 0) {
            bypassTests = true;
            return;
        }
        toUse = accounts[0];
    }
    Preferences.setString(GtasksPreferenceService.PREF_USER_NAME, toUse.name);
    AccountManagerFuture<Bundle> accountManagerFuture = manager.manager.getAuthToken(toUse, "oauth2:https://www.googleapis.com/auth/tasks", true, null, null);
    Bundle authTokenBundle = accountManagerFuture.getResult();
    if (authTokenBundle.containsKey(AccountManager.KEY_INTENT)) {
        Intent i = (Intent) authTokenBundle.get(AccountManager.KEY_INTENT);
        ContextManager.getContext().startActivity(i);
        return;
    }
    String authToken = authTokenBundle.getString(AccountManager.KEY_AUTHTOKEN);
    authToken = GtasksTokenValidator.validateAuthToken(getContext(), authToken);
    gtasksPreferenceService.setToken(authToken);
    gtasksService = new GtasksInvoker(authToken);
    initialized = true;
}

77. 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();
}

78. UserAccountManager#buildAccount()

Project: SalesforceMobileSDK-Android
File: UserAccountManager.java
/**
	 * Builds an Account object from the user account passed in.
	 *
	 * @param userAccount UserAccount object.
	 * @return Account object.
	 */
public Account buildAccount(UserAccount userAccount) {
    final Account[] accounts = accountManager.getAccountsByType(accountType);
    if (userAccount == null) {
        return null;
    }
    if (accounts == null || accounts.length == 0) {
        return null;
    }
    // Reads the user account's user ID and org ID.
    final String storedUserId = ((userAccount.getUserId() == null) ? "" : userAccount.getUserId());
    final String storedOrgId = ((userAccount.getOrgId() == null) ? "" : userAccount.getOrgId());
    for (final Account account : accounts) {
        if (account != null) {
            // Reads the user ID and org ID from account manager.
            String passcodeHash = SalesforceSDKManager.getInstance().getPasscodeHash();
            final String orgId = SalesforceSDKManager.decryptWithPasscode(accountManager.getUserData(account, AuthenticatorService.KEY_ORG_ID), passcodeHash);
            final String userId = SalesforceSDKManager.decryptWithPasscode(accountManager.getUserData(account, AuthenticatorService.KEY_USER_ID), passcodeHash);
            if (storedUserId.trim().equals(userId.trim()) && storedOrgId.trim().equals(orgId.trim())) {
                return account;
            }
        }
    }
    return null;
}

79. UserAccountManager#getCurrentAccount()

Project: SalesforceMobileSDK-Android
File: UserAccountManager.java
/**
	 * Returns the current user logged in.
	 *
	 * @return Current user that's logged in.
	 */
public Account getCurrentAccount() {
    final Account[] accounts = accountManager.getAccountsByType(accountType);
    if (accounts == null || accounts.length == 0) {
        return null;
    }
    // Reads the stored user ID and org ID.
    final SharedPreferences sp = context.getSharedPreferences(CURRENT_USER_PREF, Context.MODE_PRIVATE);
    final String storedUserId = sp.getString(USER_ID_KEY, "");
    final String storedOrgId = sp.getString(ORG_ID_KEY, "");
    for (final Account account : accounts) {
        if (account != null) {
            // Reads the user ID and org ID from account manager.
            String passcodeHash = SalesforceSDKManager.getInstance().getPasscodeHash();
            final String orgId = SalesforceSDKManager.decryptWithPasscode(accountManager.getUserData(account, AuthenticatorService.KEY_ORG_ID), passcodeHash);
            final String userId = SalesforceSDKManager.decryptWithPasscode(accountManager.getUserData(account, AuthenticatorService.KEY_USER_ID), passcodeHash);
            if (storedUserId.trim().equals(userId) && storedOrgId.trim().equals(orgId)) {
                return account;
            }
        }
    }
    return null;
}

80. SignInActivity#findGoogleAccountByName()

Project: ribot-app-android
File: SignInActivity.java
private Account findGoogleAccountByName(String accountName) {
    Account[] accounts = mAccountManager.getAccountsByType(ACCOUNT_TYPE_GOOGLE);
    for (Account account : accounts) {
        if (account.name.equals(accountName)) {
            return account;
        }
    }
    return null;
}

81. AuthAccountManager#getAccountByName()

Project: retroauth
File: AuthAccountManager.java
/**
     * @param accountType of which you want to get the active account
     * @param accountName account name you're searching for
     * @return the account if found. {@code null} if not
     */
@Nullable
public Account getAccountByName(@NonNull String accountType, @NonNull String accountName) {
    Account[] accounts = accountManager.getAccountsByType(accountType);
    for (Account account : accounts) {
        if (accountName.equals(account.name))
            return account;
    }
    return null;
}

82. SyncUtils#clearSyncMarkers()

Project: PinDroid
File: SyncUtils.java
public static void clearSyncMarkers(Context context) {
    Account[] accounts = AccountManager.get(context).getAccountsByType(Constants.ACCOUNT_TYPE);
    for (Account a : accounts) {
        AccountManager.get(context).setUserData(a, Constants.SYNC_MARKER_KEY, "0");
    }
}

83. 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);
    }
}

84. 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);
    }
}

85. ContactHelper#getAccountEmails()

Project: open-keychain
File: ContactHelper.java
/**
     * Get emails from AccountManager
     */
private Set<String> getAccountEmails() {
    final Account[] accounts = AccountManager.get(mContext).getAccounts();
    final Set<String> emailSet = new HashSet<>();
    for (Account account : accounts) {
        emailSet.add(account.name);
    }
    return emailSet;
}

86. SyncGtaskHelper#getAccount()

Project: NotePad
File: SyncGtaskHelper.java
/**
     * Finds and returns the account of the name given
     *
     * @param accountName email of google account
     * @return a Google Account
     */
public static Account getAccount(@NonNull AccountManager manager, @NonNull String accountName) {
    Account[] accounts = manager.getAccountsByType("com.google");
    for (Account account : accounts) {
        if (account.name.equals(accountName)) {
            return account;
        }
    }
    return null;
}

87. SyncPrefs#getAccount()

Project: NotePad
File: SyncPrefs.java
// private Preference prefSyncFreq;
/**
     * Finds and returns the account of the name given
     *
     * @param accountName
     * @return
     */
public static Account getAccount(AccountManager manager, String accountName) {
    Account[] accounts = manager.getAccountsByType("com.google");
    for (Account account : accounts) {
        if (account.name.equals(accountName)) {
            return account;
        }
    }
    return null;
}

88. 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();
        }
    }
}

89. AccountUtils#getOwnCloudAccountByName()

Project: MyRepository-master
File: AccountUtils.java
/**
     * Returns owncloud account identified by accountName or null if it does not exist.
     * @param context
     * @param accountName name of account to be returned
     * @return owncloud account named accountName
     */
public static Account getOwnCloudAccountByName(Context context, String accountName) {
    Account[] ocAccounts = AccountManager.get(context).getAccountsByType(MainApp.getAccountType());
    for (Account account : ocAccounts) {
        if (account.name.equals(accountName))
            return account;
    }
    return null;
}

90. AccountUtils#getCurrentOwnCloudAccount()

Project: MyRepository-master
File: AccountUtils.java
/**
     * Can be used to get the currently selected ownCloud {@link Account} in the
     * application preferences.
     * 
     * @param   context     The current application {@link Context}
     * @return              The ownCloud {@link Account} currently saved in preferences, or the first 
     *                      {@link Account} available, if valid (still registered in the system as ownCloud 
     *                      account). If none is available and valid, returns null.
     */
public static Account getCurrentOwnCloudAccount(Context context) {
    Account[] ocAccounts = AccountManager.get(context).getAccountsByType(MainApp.getAccountType());
    Account defaultAccount = null;
    SharedPreferences appPreferences = PreferenceManager.getDefaultSharedPreferences(context);
    String accountName = appPreferences.getString("select_oc_account", null);
    // account validation: the saved account MUST be in the list of ownCloud Accounts known by the AccountManager
    if (accountName != null) {
        for (Account account : ocAccounts) {
            if (account.name.equals(accountName)) {
                defaultAccount = account;
                break;
            }
        }
    }
    if (defaultAccount == null && ocAccounts.length != 0) {
        // take first account as fallback
        defaultAccount = ocAccounts[0];
    }
    return defaultAccount;
}

91. 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);
}

92. Authenticator#onAccountAuthenticated()

Project: iFixitAndroid
File: Authenticator.java
/**
    * Call whenever an account has been authenticated so it can be added to the
    * AccountManager with all of the expected fields. Removes any accounts that
    * are associated with the same site and updates the account if we suspect
    * it's the same user.
    */
public Account onAccountAuthenticated(Site site, String email, String userName, int userid, String password, String authToken) {
    if (!site.reauthenticateOnLogout()) {
        // Don't store the password if the user shouldn't be reauthenticated.
        password = "";
    }
    Bundle userData = getUserDataBundle(site, email, userName, userid);
    Account existingAccount = getAccountForSite(site);
    if (existingAccount != null) {
        if (email.equals(mAccountManager.getUserData(existingAccount, USER_DATA_EMAIL))) {
            return updateAccount(existingAccount, password, authToken, userData);
        } else {
            // Remove the existing account because we will make a new one below. We only
            // allow at most 1 account per site.
            removeAccount(existingAccount);
        }
    }
    // Accounts cannot share the same name so we must prefix the username with the site
    // name if this is the dozuki app.
    String accountName = userName;
    if (BuildConfig.SITE_NAME.equals("dozuki")) {
        accountName = site.mTitle + ": " + userName;
    }
    Account newAccount = new Account(accountName, getAccountType());
    mAccountManager.addAccountExplicitly(newAccount, password, userData);
    mAccountManager.setAuthToken(newAccount, AUTH_TOKEN_TYPE_FULL_ACCESS, authToken);
    // By default, automatically sync user's data.
    mContext.getContentResolver().setSyncAutomatically(newAccount, ApiContentProvider.getAuthority(), true);
    return newAccount;
}

93. AccountSelectActivity#onCreate()

Project: hubroid
File: AccountSelectActivity.java
@Override
protected void onCreate(Bundle icicle) {
    super.onCreate(icicle, R.layout.account_select_activity);
    mProgress = (ProgressBar) findViewById(R.id.progress);
    mContent = (RelativeLayout) findViewById(R.id.content);
    ListView listView = (ListView) findViewById(R.id.lv_userselect_users);
    TextView msgView = (TextView) findViewById(R.id.tv_userselect_msg);
    Button noChoiceBtn = (Button) findViewById(R.id.btn_userselect_nochoice);
    mAccountManager = AccountManager.get(getContext());
    if (mCurrentAccount == null) {
        noChoiceBtn.setText(R.string.userselect_justbrowsing);
    }
    final Account[] accounts = mAccountManager.getAccountsByType(AuthConstants.GITHUB_ACCOUNT_TYPE);
    ArrayAdapter<String> listAdapter = new ArrayAdapter<String>(getContext(), R.layout.account_select_listitem);
    for (Account a : accounts) {
        listAdapter.add(a.name);
    }
    noChoiceBtn.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            mPrefsEditor.remove(HubroidConstants.PREF_CURRENT_USER_LOGIN);
            mPrefsEditor.remove(HubroidConstants.PREF_CURRENT_USER);
            mPrefsEditor.remove(HubroidConstants.PREF_CURRENT_CONTEXT_LOGIN);
            mPrefsEditor.commit();
            final Intent intent = new Intent(AccountSelectActivity.this, HomeActivity.class);
            intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_NEW_TASK);
            startActivity(intent);
            finish();
        }
    });
    if (!listAdapter.isEmpty()) {
        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {

            @Override
            public void onItemClick(AdapterView<?> parent, View view, final int position, long id) {
                mContent.setVisibility(GONE);
                mProgress.setVisibility(VISIBLE);
                new RoboAsyncTask<Boolean>(AccountSelectActivity.this) {

                    public Boolean call() throws Exception {
                        mCurrentAccount = accounts[position];
                        mGitHubClient = null;
                        UserService service = new UserService(getGHClient());
                        User user = service.getUser();
                        if (user != null) {
                            mPrefsEditor.putString(HubroidConstants.PREF_CURRENT_USER_LOGIN, user.getLogin());
                            mPrefsEditor.putString(HubroidConstants.PREF_CURRENT_USER, GsonUtils.toJson(user));
                            mPrefsEditor.commit();
                            return true;
                        }
                        return false;
                    }

                    @Override
                    public void onSuccess(Boolean authSuccess) {
                        final Intent intent = new Intent(AccountSelectActivity.this, HomeActivity.class);
                        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_NEW_TASK);
                        startActivity(intent);
                        finish();
                    }

                    @Override
                    protected void onFinally() throws RuntimeException {
                        mProgress.setVisibility(GONE);
                        mContent.setVisibility(VISIBLE);
                        super.onFinally();
                    }
                }.execute();
            }
        });
        listView.setAdapter(listAdapter);
    }
}

94. GtasksLoginActivity#onCreate()

Project: astrid
File: GtasksLoginActivity.java
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    ContextManager.setContext(this);
    requestWindowFeature(Window.FEATURE_NO_TITLE);
    setContentView(R.layout.gtasks_login_activity);
    TextView header = new TextView(this);
    header.setText(R.string.actfm_GAA_title);
    header.setTextAppearance(this, R.style.TextAppearance_Medium);
    header.setPadding(10, 0, 10, 50);
    getListView().addHeaderView(header);
    accountManager = new GoogleAccountManager(this);
    Account[] accounts = accountManager.getAccounts();
    ArrayList<String> accountNames = new ArrayList<String>();
    for (Account a : accounts) {
        accountNames.add(a.name);
    }
    nameArray = accountNames.toArray(new String[accountNames.size()]);
    setListAdapter(new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, nameArray));
    findViewById(R.id.empty_button).setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {
            onAuthCancel();
        }
    });
}

95. ActFmGoogleAuthActivity#onCreate()

Project: astrid
File: ActFmGoogleAuthActivity.java
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    ContextManager.setContext(this);
    requestWindowFeature(Window.FEATURE_NO_TITLE);
    setContentView(R.layout.gtasks_login_activity);
    TextView header = new TextView(this);
    header.setText(R.string.actfm_GAA_title);
    header.setTextAppearance(this, R.style.TextAppearance_Medium);
    header.setPadding(10, 0, 10, 50);
    getListView().addHeaderView(header);
    accountManager = new GoogleAccountManager(this);
    Account[] accounts = accountManager.getAccounts();
    ArrayList<String> accountNames = new ArrayList<String>();
    for (Account a : accounts) accountNames.add(a.name);
    nameArray = accountNames.toArray(new String[accountNames.size()]);
    setListAdapter(new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, nameArray));
    findViewById(R.id.empty_button).setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {
            onAuthCancel();
        }
    });
}

96. ContactHelper#getAccountEmails()

Project: apg
File: ContactHelper.java
/**
     * Get emails from AccountManager
     *
     * @param context
     * @return
     */
private static Set<String> getAccountEmails(Context context) {
    final Account[] accounts = AccountManager.get(context).getAccounts();
    final Set<String> emailSet = new HashSet<>();
    for (Account account : accounts) {
        emailSet.add(account.name);
    }
    return emailSet;
}

97. 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();
        }
    }
}

98. AccountUtils#getOwnCloudAccountByName()

Project: android
File: AccountUtils.java
/**
     * Returns owncloud account identified by accountName or null if it does not exist.
     * @param context
     * @param accountName name of account to be returned
     * @return owncloud account named accountName
     */
public static Account getOwnCloudAccountByName(Context context, String accountName) {
    Account[] ocAccounts = AccountManager.get(context).getAccountsByType(MainApp.getAccountType());
    for (Account account : ocAccounts) {
        if (account.name.equals(accountName))
            return account;
    }
    return null;
}

99. AccountUtils#getCurrentOwnCloudAccount()

Project: android
File: AccountUtils.java
/**
     * Can be used to get the currently selected ownCloud {@link Account} in the
     * application preferences.
     * 
     * @param   context     The current application {@link Context}
     * @return              The ownCloud {@link Account} currently saved in preferences, or the first 
     *                      {@link Account} available, if valid (still registered in the system as ownCloud 
     *                      account). If none is available and valid, returns null.
     */
public static Account getCurrentOwnCloudAccount(Context context) {
    Account[] ocAccounts = getAccounts(context);
    Account defaultAccount = null;
    SharedPreferences appPreferences = PreferenceManager.getDefaultSharedPreferences(context);
    String accountName = appPreferences.getString("select_oc_account", null);
    // account validation: the saved account MUST be in the list of ownCloud Accounts known by the AccountManager
    if (accountName != null) {
        for (Account account : ocAccounts) {
            if (account.name.equals(accountName)) {
                defaultAccount = account;
                break;
            }
        }
    }
    if (defaultAccount == null && ocAccounts.length != 0) {
        // take first account as fallback
        defaultAccount = ocAccounts[0];
    }
    return defaultAccount;
}

100. BaseAuthFragment#getSuggestedEmailChecked()

Project: actor-platform
File: BaseAuthFragment.java
private String getSuggestedEmailChecked() {
    Pattern emailPattern = Patterns.EMAIL_ADDRESS;
    Account[] accounts = AccountManager.get(getActivity()).getAccounts();
    for (Account account : accounts) {
        if (emailPattern.matcher(account.name).matches()) {
            return account.name;
        }
    }
    return null;
}