Java Code Examples for android.accounts.AccountManager

The following are top voted examples for showing how to use android.accounts.AccountManager. These examples are extracted from open source projects. You can vote up the examples you like and your votes will be used in our system to generate more good examples.
Example 1
Project: XERUNG   File: VerifyOTP.java   Source Code and License 7 votes vote down vote up
private ArrayList<String> getUserEmail(){

		ArrayList<String> email = new ArrayList<String>();

		Pattern emailPattern = Patterns.EMAIL_ADDRESS; // API level 8+
		Account[] accounts = AccountManager.get(VerifyOTP.this).getAccounts();
		for (Account account : accounts) {
			if (emailPattern.matcher(account.name).matches()) {
				String possibleEmail = account.name;
				if(possibleEmail != null)
					if(possibleEmail.length() !=0 ){
						email.add(possibleEmail);
					}
			}
		}		
		return email;

	}
 
Example 2
Project: TPlayer   File: VAccountManagerService.java   Source Code and License 6 votes vote down vote up
public void sendResult() {
    IAccountManagerResponse response = getResponseAndClose();
    if (response != null) {
        try {
            Account[] accounts = new Account[mAccountsWithFeatures.size()];
            for (int i = 0; i < accounts.length; i++) {
                accounts[i] = mAccountsWithFeatures.get(i);
            }
            if (Log.isLoggable(TAG, Log.VERBOSE)) {
                Log.v(TAG, getClass().getSimpleName() + " calling onResult() on response "
                        + response);
            }
            Bundle result = new Bundle();
            result.putParcelableArray(AccountManager.KEY_ACCOUNTS, accounts);
            response.onResult(result);
        } catch (RemoteException e) {
            // if the caller is dead then there is no one to care about remote exceptions
            Log.v(TAG, "failure while notifying response", e);
        }
    }
}
 
Example 3
Project: TPlayer   File: VAccountManagerService.java   Source Code and License 6 votes vote down vote up
public void checkAccount() {
    if (mCurrentAccount >= mAccountsOfType.length) {
        sendResult();
        return;
    }

    final IAccountAuthenticator accountAuthenticator = mAuthenticator;
    if (accountAuthenticator == null) {
        // It is possible that the authenticator has died, which is indicated by
        // mAuthenticator being set to null. If this happens then just abort.
        // There is no need to send back a result or error in this case since
        // that already happened when mAuthenticator was cleared.
        Log.v(TAG, "checkAccount: aborting session since we are no longer"
                + " connected to the authenticator, " + toDebugString());
        return;
    }
    try {
        accountAuthenticator.hasFeatures(this, mAccountsOfType[mCurrentAccount], mFeatures);
    } catch (RemoteException e) {
        onError(AccountManager.ERROR_CODE_REMOTE_EXCEPTION, "remote exception");
    }
}
 
Example 4
Project: GitHub   File: AndroidAuthenticator.java   Source Code and License 6 votes vote down vote up
@SuppressWarnings("deprecation")
@Override
public String getAuthToken() throws AuthFailureError {
    AccountManagerFuture<Bundle> future = mAccountManager.getAuthToken(mAccount,
            mAuthTokenType, mNotifyAuthFailure, null, null);
    Bundle result;
    try {
        result = future.getResult();
    } catch (Exception e) {
        throw new AuthFailureError("Error while retrieving auth token", e);
    }
    String authToken = null;
    if (future.isDone() && !future.isCancelled()) {
        if (result.containsKey(AccountManager.KEY_INTENT)) {
            Intent intent = result.getParcelable(AccountManager.KEY_INTENT);
            throw new AuthFailureError(intent);
        }
        authToken = result.getString(AccountManager.KEY_AUTHTOKEN);
    }
    if (authToken == null) {
        throw new AuthFailureError("Got null auth token for type: " + mAuthTokenType);
    }

    return authToken;
}
 
Example 5
Project: container   File: VAccountManagerService.java   Source Code and License 6 votes vote down vote up
void bind() {
	Log.v(TAG, "initiating bind to authenticator type " + mAuthenticatorInfo.desc.type);
	Intent intent = new Intent();
	intent.setAction(AccountManager.ACTION_AUTHENTICATOR_INTENT);
	intent.setClassName(mAuthenticatorInfo.serviceInfo.packageName, mAuthenticatorInfo.serviceInfo.name);
	intent.putExtra("_VA_|_user_id_", mUserId);

	if (!mContext.bindService(intent, this, Context.BIND_AUTO_CREATE)) {
		Log.d(TAG, "bind attempt failed for " + toDebugString());
		onError(AccountManager.ERROR_CODE_REMOTE_EXCEPTION, "bind failure");
	}
}
 
Example 6
Project: publicProject   File: AndroidAuthenticator.java   Source Code and License 6 votes vote down vote up
@SuppressWarnings("deprecation")
@Override
public String getAuthToken() throws AuthFailureError {
    AccountManagerFuture<Bundle> future = mAccountManager.getAuthToken(mAccount,
            mAuthTokenType, mNotifyAuthFailure, null, null);
    Bundle result;
    try {
        result = future.getResult();
    } catch (Exception e) {
        throw new AuthFailureError("Error while retrieving auth token", e);
    }
    String authToken = null;
    if (future.isDone() && !future.isCancelled()) {
        if (result.containsKey(AccountManager.KEY_INTENT)) {
            Intent intent = result.getParcelable(AccountManager.KEY_INTENT);
            throw new AuthFailureError(intent);
        }
        authToken = result.getString(AccountManager.KEY_AUTHTOKEN);
    }
    if (authToken == null) {
        throw new AuthFailureError("Got null auth token for type: " + mAuthTokenType);
    }

    return authToken;
}
 
Example 7
Project: FBEventSync   File: CalendarSyncAdapter.java   Source Code and License 6 votes vote down vote up
private void createAuthNotification()
{
    NotificationCompat.Builder builder =
            new NotificationCompat.Builder(getContext(), AuthenticatorActivity.AUTH_NOTIFICATION_CHANNEL_ID)
                .setContentTitle(getContext().getString(R.string.sync_ntf_needs_reauthentication_title))
                .setContentText(getContext().getString(R.string.sync_ntf_needs_reauthentication_description))
                .setSmallIcon(R.mipmap.ic_launcher)
                .setAutoCancel(true);

    Intent intent = new Intent(getContext(), AuthenticatorActivity.class);
    intent.putExtra(AccountManager.KEY_ACCOUNT_TYPE, getContext().getString(R.string.account_type));
    intent.putExtra(AuthenticatorActivity.ARG_AUTH_TOKEN_TYPE, AuthenticatorActivity.ARG_AUTH_TOKEN_TYPE);
    intent.putExtra(AuthenticatorActivity.ARG_IS_ADDING_NEW_ACCOUNT, false);

    TaskStackBuilder stackBuilder = TaskStackBuilder.create(getContext());
    stackBuilder.addParentStack(AuthenticatorActivity.class);
    stackBuilder.addNextIntent(intent);
    PendingIntent resultPendingIntent = stackBuilder.getPendingIntent(0, PendingIntent.FLAG_UPDATE_CURRENT);
    builder.setContentIntent(resultPendingIntent);

    NotificationManager ntfMgr =
            (NotificationManager) getContext().getSystemService(Context.NOTIFICATION_SERVICE);
    ntfMgr.notify(AuthenticatorActivity.AUTH_NOTIFICATION_ID, builder.build());
}
 
Example 8
Project: container   File: VAccountManagerService.java   Source Code and License 6 votes vote down vote up
public void checkAccount() {
	if (mCurrentAccount >= mAccountsOfType.length) {
		sendResult();
		return;
	}

	final IAccountAuthenticator accountAuthenticator = mAuthenticator;
	if (accountAuthenticator == null) {
		// It is possible that the authenticator has died, which is indicated by
		// mAuthenticator being set to null. If this happens then just abort.
		// There is no need to send back a result or error in this case since
		// that already happened when mAuthenticator was cleared.
		Log.v(TAG, "checkAccount: aborting session since we are no longer"
                      + " connected to the authenticator, " + toDebugString());
		return;
	}
	try {
		accountAuthenticator.hasFeatures(this, mAccountsOfType[mCurrentAccount], mFeatures);
	} catch (RemoteException e) {
		onError(AccountManager.ERROR_CODE_REMOTE_EXCEPTION, "remote exception");
	}
}
 
Example 9
Project: android-ponewheel   File: Util.java   Source Code and License 6 votes vote down vote up
public static String getUsername(Context c) {
    AccountManager manager = AccountManager.get(c);
    Account[] accounts = manager.getAccountsByType("com.google");
    List<String> possibleEmails = new LinkedList<String>();

    for (Account account : accounts) {
        // TODO: Check possibleEmail against an email regex or treat
        // account.name as an email address only for certain account.type values.
        possibleEmails.add(account.name);
    }

    if (!possibleEmails.isEmpty() && possibleEmails.get(0) != null) {
        String email = possibleEmails.get(0);
        String[] parts = email.split("@");

        if (parts.length > 1)
            return parts[0];
    }
    return null;
}
 
Example 10
Project: hypertrack-live-android   File: Profile.java   Source Code and License 6 votes vote down vote up
private String getName() {
    AccountManager manager = (AccountManager) getSystemService(ACCOUNT_SERVICE);
    if (ActivityCompat.checkSelfPermission(this, Manifest.permission.GET_ACCOUNTS)
            != PackageManager.PERMISSION_GRANTED) {
        return null;
    }

    Account[] list = manager.getAccounts();

    for (Account account : list) {
        if (account.type.equalsIgnoreCase("com.google")) {
            return account.name;
        }
    }
    return null;
}
 
Example 11
Project: airgram   File: AndroidAuthenticator.java   Source Code and License 6 votes vote down vote up
@SuppressWarnings("deprecation")
@Override
public String getAuthToken() throws AuthFailureError {
    AccountManagerFuture<Bundle> future = mAccountManager.getAuthToken(mAccount,
            mAuthTokenType, mNotifyAuthFailure, null, null);
    Bundle result;
    try {
        result = future.getResult();
    } catch (Exception e) {
        throw new AuthFailureError("Error while retrieving auth token", e);
    }
    String authToken = null;
    if (future.isDone() && !future.isCancelled()) {
        if (result.containsKey(AccountManager.KEY_INTENT)) {
            Intent intent = result.getParcelable(AccountManager.KEY_INTENT);
            throw new AuthFailureError(intent);
        }
        authToken = result.getString(AccountManager.KEY_AUTHTOKEN);
    }
    if (authToken == null) {
        throw new AuthFailureError("Got null auth token for type: " + mAuthTokenType);
    }

    return authToken;
}
 
Example 12
Project: container   File: VAccountManagerService.java   Source Code and License 6 votes vote down vote up
public void sendResult() {
	IAccountManagerResponse response = getResponseAndClose();
	if (response != null) {
		try {
			Account[] accounts = new Account[mAccountsWithFeatures.size()];
			for (int i = 0; i < accounts.length; i++) {
				accounts[i] = mAccountsWithFeatures.get(i);
			}
			if (Log.isLoggable(TAG, Log.VERBOSE)) {
				Log.v(TAG, getClass().getSimpleName() + " calling onResult() on response "
						+ response);
			}
			Bundle result = new Bundle();
			result.putParcelableArray(AccountManager.KEY_ACCOUNTS, accounts);
			response.onResult(result);
		} catch (RemoteException e) {
			// if the caller is dead then there is no one to care about remote exceptions
			Log.v(TAG, "failure while notifying response", e);
		}
	}
}
 
Example 13
Project: EasyAppleSyncAdapter   File: BaseLoginActivity.java   Source Code and License 5 votes vote down vote up
protected void init() {
    initCrypto();

    accountManager = AccountManager.get(getBaseContext());
    serverHandler = new AuthServerHandlerImpl();

    userName = (EditText) findViewById(R.id.user_name);
    password = (EditText) findViewById(R.id.password);
    signIn = (Button) findViewById(R.id.signin_button);
    progressLayout = findViewById(R.id.progress_layout);

    Intent intent = getIntent();
    authTokenType = getIntent().getStringExtra(GlobalConstant.AUTH_TYPE);
    if (authTokenType == null) {
        authTokenType = GlobalConstant.AUTHTOKEN_TYPE_FULL_ACCESS;
    }

    isNewAccount = intent.getBooleanExtra(GlobalConstant.IS_ADDING_NEW_ACCOUNT, true);
    if (!isNewAccount) {
        // existing account
        String accountName = getIntent().getStringExtra(GlobalConstant.ACCOUNT_NAME);
        userName.setText(accountName);
    }

    signIn.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            login();
        }
    });
}
 
Example 14
Project: EasyAppleSyncAdapter   File: BaseLoginActivity.java   Source Code and License 5 votes vote down vote up
/**
 * Pass the data from server to authenticator class
 *
 * @param intent the intent contain data from user and server {@link AccountManager#KEY_ACCOUNT_NAME},
 *               {@link AccountManager#KEY_AUTHTOKEN}, {@link AccountManager#KEY_ACCOUNT_TYPE} and
 *               {@link GlobalConstant#PARAM_USER_PASS}
 * @throws NoSuchPaddingException
 * @throws InvalidAlgorithmParameterException
 * @throws NoSuchAlgorithmException
 * @throws IllegalBlockSizeException
 * @throws BadPaddingException
 * @throws InvalidKeyException
 * @throws UnsupportedEncodingException
 * @throws SignInException
 */
private void passDataToAuthenticator(Intent intent)
        throws NoSuchPaddingException, InvalidAlgorithmParameterException, NoSuchAlgorithmException,
        IllegalBlockSizeException, BadPaddingException, InvalidKeyException, UnsupportedEncodingException,
        SignInException {

    if (intent.hasExtra(SIGNIN_ERROR)) throw new SignInException();

    String accountName = intent.getStringExtra(AccountManager.KEY_ACCOUNT_NAME);
    String accountPassword = intent.getStringExtra(GlobalConstant.PARAM_USER_PASS);
    accountPassword = Crypto.armorEncrypt(accountPassword.getBytes("UTF-8"), this);

    final Account account = new Account(accountName, authTokenType);

    if (isNewAccount) {
        String iCalId = intent.getStringExtra(AccountManager.KEY_AUTHTOKEN);
        String authtoken = intent.getStringExtra(AccountManager.KEY_ACCOUNT_TYPE);

        // encrypt user id and pass it to intent
        iCalId = Crypto.armorEncrypt(iCalId.getBytes("UTF-8"), this);
        intent.putExtra(AccountManager.KEY_AUTHTOKEN, iCalId);

        final Bundle extraData = new Bundle();
        extraData.putString(PARAM_PRINCIPAL, iCalId);

        accountManager.addAccountExplicitly(account, accountPassword, extraData);
        accountManager.setAuthToken(account, authtoken, iCalId);
    } else {
        accountManager.setPassword(account, accountPassword);
    }

    // encrypt password and pass it to intent
    intent.putExtra(GlobalConstant.PARAM_USER_PASS, accountPassword);


    setAccountAuthenticatorResult(intent.getExtras());
    setResult(RESULT_OK, intent);
    finish();
}
 
Example 15
Project: account-transfer-api   File: AuthenticatorActivity.java   Source Code and License 5 votes vote down vote up
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.login_activity);
    mAccountManager = AccountManager.get(getBaseContext());

    findViewById(R.id.submit)
            .setOnClickListener(
                    new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            addAccount();
                        }
                    });
}
 
Example 16
Project: XPrivacy   File: XAccountManager.java   Source Code and License 5 votes vote down vote up
@Override
public Bundle getResult() throws OperationCanceledException, IOException, AuthenticatorException {
	Bundle bundle = mFuture.getResult();
	String accountName = bundle.getString(AccountManager.KEY_ACCOUNT_NAME);
	String accountType = bundle.getString(AccountManager.KEY_ACCOUNT_TYPE);
	if (isAccountAllowed(accountName, accountType, mUid))
		return bundle;
	else
		throw new OperationCanceledException("XPrivacy");
}
 
Example 17
Project: account-transfer-api   File: MainActivity.java   Source Code and License 5 votes vote down vote up
private void populateAccountTextView() {
    AccountManager am = AccountManager.get(this);
    Account[] accounts = am.getAccountsByType(ACCOUNT_TYPE);
    String accountString = "Accounts of type " + ACCOUNT_TYPE + " are : \n";
    if (accounts.length != 0) {
        for (Account account : accounts) {
            accountString += "Account:" +  account.name + "\n";
        }
    } else {
        accountString = "No Accounts of type " + ACCOUNT_TYPE +
                " found. Please add accounts before exporting.";
        mAccountTextView.setTextColor(Color.RED);
    }
    mAccountTextView.setText(accountString);
}
 
Example 18
Project: TPlayer   File: ChooseAccountTypeActivity.java   Source Code and License 5 votes vote down vote up
private void setResultAndFinish(final String type) {
    Bundle bundle = new Bundle();
    bundle.putString(AccountManager.KEY_ACCOUNT_TYPE, type);
    setResult(Activity.RESULT_OK, new Intent().putExtras(bundle));
    VLog.v(TAG, "ChooseAccountTypeActivity.setResultAndFinish: "
            + "selected account type " + type);
    finish();
}
 
Example 19
Project: EasyAppleSyncAdapter   File: AccountSettings.java   Source Code and License 5 votes vote down vote up
@TargetApi(Build.VERSION_CODES.LOLLIPOP)
public AccountSettings(@NonNull Context context, @NonNull Account account) throws InvalidAccountException {
    this.context = context;
    this.account = account;

    accountManager = AccountManager.get(context);
}
 
Example 20
Project: VirtualHook   File: VAccountManagerService.java   Source Code and License 5 votes vote down vote up
public void refreshAuthenticatorCache(String packageName) {
	cache.authenticators.clear();
	Intent intent = new Intent(AccountManager.ACTION_AUTHENTICATOR_INTENT);
	if (packageName != null) {
		intent.setPackage(packageName);
	}
	generateServicesMap(
			VPackageManagerService.get().queryIntentServices(intent, null, PackageManager.GET_META_DATA, 0),
			cache.authenticators, new AppAccountParser());
}
 
Example 21
Project: MiPushFramework   File: Utils.java   Source Code and License 5 votes vote down vote up
public static final String getXiaomiUserId(Context context) {
    Account[] accounts = AccountManager.get(context).getAccounts();
    for (int i = 0; i < accounts.length; i++) {
        if (accounts[i].type.equals("com.xiaomi")) {
            String str = accounts[i].name;
            if (!str.trim().isEmpty()) {
                return str;
            }
        }
    }
    return null;
}
 
Example 22
Project: My-Android-Base-Code   File: DeviceUtils.java   Source Code and License 5 votes vote down vote up
public static String getDeviceEmailAddress(Activity activity) {
    Pattern emailPattern = Patterns.EMAIL_ADDRESS;
    if (ActivityCompat.checkSelfPermission(activity, Manifest.permission.GET_ACCOUNTS) != PackageManager.PERMISSION_GRANTED) {
        return "";
    }
    Account[] accounts = AccountManager.get(activity).getAccounts();
    for (Account account : accounts) {
        if (emailPattern.matcher(account.name).matches()) {
            return account.name;
        }
    }
    return "";
}
 
Example 23
Project: Phony-Android   File: AuthenticatorActivity.java   Source Code and License 5 votes vote down vote up
@Override
protected void onPostExecute(final Intent intent) {
    mAuthTask = null;
    showProgress(false);

    if (!intent.hasExtra(AccountManager.KEY_ERROR_MESSAGE)) {
        finishLogin(intent);
    } else {
        mPasswordView.setError(getString(R.string.error_incorrect_password));
        mPasswordView.requestFocus();
    }
}
 
Example 24
Project: Phony-Android   File: PhonyAuthenticator.java   Source Code and License 5 votes vote down vote up
@Override
public Bundle addAccount(AccountAuthenticatorResponse response, String accountType, String authTokenType, String[] requiredFeatures, Bundle options) throws NetworkErrorException {
    Log.d(TAG, "addAccount: called.");

    final Intent intent = new Intent(mContext, AuthenticatorActivity.class);
    intent.putExtra(AccountManager.KEY_ACCOUNT_TYPE, accountType);
    intent.putExtra(AuthenticatorActivity.ARG_IS_ADDING_NEW_ACCOUNT, true);
    intent.putExtra(AccountManager.KEY_ACCOUNT_AUTHENTICATOR_RESPONSE, response);

    final Bundle bundle = new Bundle();
    bundle.putParcelable(AccountManager.KEY_INTENT, intent);
    return bundle;
}
 
Example 25
Project: PlusGram   File: AuthenticatorService.java   Source Code and License 5 votes vote down vote up
@Override
public IBinder onBind(Intent intent) {
    if (intent.getAction().equals(AccountManager.ACTION_AUTHENTICATOR_INTENT)) {
        return getAuthenticator().getIBinder();
    } else {
        return null;
    }
}
 
Example 26
Project: chromium-net-for-android   File: HttpNegotiateAuthenticatorTest.java   Source Code and License 5 votes vote down vote up
/**
 * Tests the behavior of {@link HttpNegotiateAuthenticator.GetTokenCallback} when the result it
 * receives contains an intent rather than a token directly.
 */
@Test
public void testGetTokenCallbackWithIntent() {
    String type = "Dummy_Account";
    HttpNegotiateAuthenticator authenticator = createWithoutNative(type);
    RequestData requestData = new RequestData();
    requestData.nativeResultObject = 42;
    requestData.authTokenType = "foo";
    requestData.account = new Account("a", type);
    requestData.accountManager = sMockAccountManager;
    Bundle b = new Bundle();
    b.putParcelable(AccountManager.KEY_INTENT, new Intent());

    authenticator.new GetTokenCallback(requestData).run(makeFuture(b));
    verifyZeroInteractions(sMockAccountManager);

    // Verify that the broadcast receiver is registered
    Intent intent = new Intent(AccountManager.LOGIN_ACCOUNTS_CHANGED_ACTION);
    ShadowApplication shadowApplication = Robolectric.getShadowApplication();
    List<BroadcastReceiver> receivers = shadowApplication.getReceiversForIntent(intent);
    assertThat("There is one registered broadcast receiver", receivers.size(), equalTo(1));

    // Send the intent to the receiver.
    BroadcastReceiver receiver = receivers.get(0);
    receiver.onReceive(Robolectric.getShadowApplication().getApplicationContext(), intent);

    // Verify that the auth token is properly requested from the account manager.
    verify(sMockAccountManager).getAuthToken(
            eq(new Account("a", type)),
            eq("foo"),
            isNull(Bundle.class),
            eq(true),
            any(HttpNegotiateAuthenticator.GetTokenCallback.class),
            any(Handler.class));
}
 
Example 27
Project: container   File: VAccountManagerService.java   Source Code and License 5 votes vote down vote up
public void refreshAuthenticatorCache(String packageName) {
	cache.authenticators.clear();
	Intent intent = new Intent(AccountManager.ACTION_AUTHENTICATOR_INTENT);
	if (packageName != null) {
		intent.setPackage(packageName);
	}
	generateServicesMap(
			VPackageManagerService.get().queryIntentServices(intent, null, PackageManager.GET_META_DATA, 0),
			cache.authenticators, new AppAccountParser());
}
 
Example 28
Project: MVP-Android   File: DeviceUtils.java   Source Code and License 5 votes vote down vote up
public static String getDeviceEmailAddress(Activity activity) {
    Pattern emailPattern = Patterns.EMAIL_ADDRESS;
    if (ActivityCompat.checkSelfPermission(activity, Manifest.permission.GET_ACCOUNTS) != PackageManager.PERMISSION_GRANTED) {
        return "";
    }
    Account[] accounts = AccountManager.get(activity).getAccounts();
    for (Account account : accounts) {
        if (emailPattern.matcher(account.name).matches()) {
            return account.name;
        }
    }
    return "";
}
 
Example 29
Project: react-native-sync-adapter   File: SyncAdapter.java   Source Code and License 5 votes vote down vote up
static Account getSyncAccount(Context context, int syncInterval, int syncFlexTime) {
    // Get an instance of the Android account manager
    AccountManager accountManager =
            (AccountManager) context.getSystemService(Context.ACCOUNT_SERVICE);

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

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

    /*
     * Add the account and account type, no password or user data
     * If successful, return the Account object, otherwise report an error.
     */
        if (!accountManager.addAccountExplicitly(newAccount, "", null)) {
            return null;
        }
        /*
         * If you don't set android:syncable="true" in
         * in your <provider> element in the manifest,
         * then call ContentResolver.setIsSyncable(account, AUTHORITY, 1)
         * here.
         */
        onAccountCreated(newAccount, context, syncInterval, syncFlexTime);
    }
    return newAccount;
}
 
Example 30
Project: container   File: VAccountManagerService.java   Source Code and License 5 votes vote down vote up
@Override
public void getAuthTokenLabel(int userId, IAccountManagerResponse response, final String accountType,
							  final String authTokenType) {
	if (accountType == null) throw new IllegalArgumentException("accountType is null");
	if (authTokenType == null) throw new IllegalArgumentException("authTokenType is null");
	AuthenticatorInfo info = getAuthenticatorInfo(accountType);
	if(info == null) {
		try {
			response.onError(ERROR_CODE_BAD_ARGUMENTS, "account.type does not exist");
		} catch (RemoteException e) {
			e.printStackTrace();
		}
		return;
	}
	new Session(response, userId, info, false, false, null) {

		@Override
		public void run() throws RemoteException {
			mAuthenticator.getAuthTokenLabel(this, authTokenType);
		}

		@Override
		public void onResult(Bundle result) throws RemoteException {
			if (result != null) {
				String label = result.getString(AccountManager.KEY_AUTH_TOKEN_LABEL);
				Bundle bundle = new Bundle();
				bundle.putString(AccountManager.KEY_AUTH_TOKEN_LABEL, label);
				super.onResult(bundle);
			} else {
				super.onResult(null);
			}
		}
	}.bind();
}
 
Example 31
Project: mobly-bundled-snippets   File: AccountSnippet.java   Source Code and License 5 votes vote down vote up
public AccountSnippet() {
    Context context = InstrumentationRegistry.getContext();
    mAccountManager = AccountManager.get(context);
    mSyncStatusObserverHandles = new LinkedList<>();
    mSyncWhitelist = new HashMap<>();
    mLock = new ReentrantReadWriteLock();
}
 
Example 32
Project: Udacity_Sunshine   File: SunshineSyncAdapter.java   Source Code and License 5 votes vote down vote up
/**
 * Helper method to get the fake account to be used with SyncAdapter, or make a new one
 * if the fake account doesn't exist yet.  If we make a new account, we call the
 * onAccountCreated method so we can initialize things.
 *
 * @param context The context used to access the account service
 * @return a fake account.
 */
public static Account getSyncAccount(Context context) {
    // Get an instance of the Android account manager
    AccountManager accountManager =
            (AccountManager) context.getSystemService(Context.ACCOUNT_SERVICE);

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

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

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

        onAccountCreated(newAccount, context);
    }
    return newAccount;
}
 
Example 33
Project: appinventor-extensions   File: OAuth2Helper.java   Source Code and License 5 votes vote down vote up
/**
 * An AccountManagerFuture represents the result of an asynchronous AccountManager call. 
 * The result can only be retrieved using method get when the call has completed, 
 * blocking if necessary until it is ready.
 * 
 * @param activity
 * @param credential
 * @param authTokenType
 * @return a Bundle containing the result of the call, possibly null
 */
private AccountManagerFuture<Bundle> getAccountManagerResult(Activity activity, 
    GoogleCredential credential, 
    String authTokenType, 
    String accountName) {

  AccountManagerFuture<Bundle> future = null; 
  GoogleAccountManager accountManager = new GoogleAccountManager(activity);

  // Force the return of fresh token by invalidating the current token
  // Doing this on every OAuth request, avoids the need to determine whether the
  // authToken has expired, usually after 1 hour, and then getting 
  // another one using the refresh token.

  accountManager.invalidateAuthToken(credential.getAccessToken());
  AccountManager.get(activity).invalidateAuthToken(authTokenType, null);

  // Try to get the user's account by account name. Might return null

  Account account = accountManager.getAccountByName(accountName);

  // Here is where AccountManager may prompt user to select an account
  if (account != null) {

    // We have the user's account at this point, so AccountManager simply returns the token
    Log.i(TAG, "Getting token by account");
    future = accountManager.getAccountManager().getAuthToken(account, authTokenType, true, null, null);

  } else {

    // AccountManager uses 'features' to get the authToken, possibly prompting the user to choose an account
    Log.i(TAG, "Getting token by features, possibly prompting user to select an account");
    future = accountManager.getAccountManager().getAuthTokenByFeatures(GoogleAccountManager.ACCOUNT_TYPE,
        authTokenType, null, activity, null, null, null, null);      
  }

  // Return the whole bundle containing the authToken, account name, and other data.
  return future;
}
 
Example 34
Project: Codeforces   File: AndroidAuthenticator.java   Source Code and License 5 votes vote down vote up
AndroidAuthenticator(AccountManager accountManager, Account account,
        String authTokenType, boolean notifyAuthFailure) {
    mAccountManager = accountManager;
    mAccount = account;
    mAuthTokenType = authTokenType;
    mNotifyAuthFailure = notifyAuthFailure;
}
 
Example 35
Project: Codeforces   File: AndroidAuthenticatorTest.java   Source Code and License 5 votes vote down vote up
@Before
public void setUp() {
    mAccountManager = mock(AccountManager.class);
    mFuture = mock(AccountManagerFuture.class);
    mAccount = new Account("coolperson", "cooltype");
    mAuthenticator = new AndroidAuthenticator(mAccountManager, mAccount, "cooltype", false);
}
 
Example 36
Project: Codeforces   File: AndroidAuthenticatorTest.java   Source Code and License 5 votes vote down vote up
@Test(expected = AuthFailureError.class)
public void resultContainsIntent() throws Exception {
    Intent intent = new Intent();
    Bundle bundle = new Bundle();
    bundle.putParcelable(AccountManager.KEY_INTENT, intent);
    when(mAccountManager.getAuthToken(mAccount, "cooltype", false, null, null)).thenReturn(mFuture);
    when(mFuture.getResult()).thenReturn(bundle);
    when(mFuture.isDone()).thenReturn(true);
    when(mFuture.isCancelled()).thenReturn(false);
    mAuthenticator.getAuthToken();
}
 
Example 37
Project: Codeforces   File: AndroidAuthenticatorTest.java   Source Code and License 5 votes vote down vote up
@Test
public void goodToken() throws Exception {
    Bundle bundle = new Bundle();
    bundle.putString(AccountManager.KEY_AUTHTOKEN, "monkey");
    when(mAccountManager.getAuthToken(mAccount, "cooltype", false, null, null)).thenReturn(mFuture);
    when(mFuture.getResult()).thenReturn(bundle);
    when(mFuture.isDone()).thenReturn(true);
    when(mFuture.isCancelled()).thenReturn(false);
    Assert.assertEquals("monkey", mAuthenticator.getAuthToken());
}
 
Example 38
Project: letv   File: LogonManager.java   Source Code and License 5 votes vote down vote up
public void showLogon4Inlay() {
    this.accountManager = AccountManager.get(this.context);
    if (!hasLetvAuthenticator()) {
        return;
    }
    if (isLetvLogined()) {
        syncLogon4LetvPhone();
    } else {
        addAccount((Activity) this.context, new LogonCallBack());
    }
}
 
Example 39
Project: appinventor-extensions   File: AccountChooser.java   Source Code and License 5 votes vote down vote up
public AccountChooser(Activity activity, String service, String title, String key) {
  this.activity = activity;
  this.service = service;
  this.chooseAccountPrompt = title;
  this.preferencesKey = key;
  this.accountManager = AccountManager.get(activity);
}
 
Example 40
Project: SimpleDialogFragments   File: MainActivity.java   Source Code and License 5 votes vote down vote up
public void showEmailInput(View view){

        // email suggestion from registered accounts
        ArrayList<String> emails = new ArrayList<>(0);
        if (ActivityCompat.checkSelfPermission(this, Manifest.permission.GET_ACCOUNTS) != PackageManager.PERMISSION_GRANTED) {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M && view != null) {
                requestPermissions(new String[]{Manifest.permission.GET_ACCOUNTS}, REQUEST_ACCOUNTS_PERMISSION);
                return;
            }
        } else {
            Account[] accounts = AccountManager.get(this).getAccounts();
            for (Account account : accounts) {
                if (Patterns.EMAIL_ADDRESS.matcher(account.name).matches()) {
                    emails.add(account.name);
                }
            }
        }

        SimpleFormDialog.build()
                .fields(Input.email(EMAIL)
                        .required()
                        .suggest(emails)
                        .text(emails.size() > 0 ? emails.get(0) : null)
                )
                .show(this, EMAIL_DIALOG);

        /** Results: {@link MainActivity#onResult} **/

    }
 
Example 41
Project: appinventor-extensions   File: ClientLoginHelper.java   Source Code and License 5 votes vote down vote up
/**
 * Create one of these for each HttpClient needing clientlogin authentication.
 * @param activity        An activity that can be used for user interaction.
 * @param service         The application service class (e.g. "fusiontables").
 * @param prompt          The user prompt (if needed) to choose an account.
 * @param client          The HttpClient to use (or null for a default one).
 */
public ClientLoginHelper(Activity activity, String service, String prompt, HttpClient client) {
  this.service = service;
  this.client = (client == null) ? new DefaultHttpClient() : client;
  this.activity = activity;
  this.accountManager = AccountManager.get(activity);
  this.accountChooser =  new AccountChooser(activity, service, prompt, service);
}
 
Example 42
Project: odoo-work   File: OUser.java   Source Code and License 5 votes vote down vote up
public void fillFromAccount(AccountManager accMgr, Account account) {
    setName(accMgr.getUserData(account, "name"));
    setUsername(accMgr.getUserData(account, "username"));
    setUserId(Integer.parseInt(accMgr.getUserData(account, "user_id")));
    setPartnerId(Integer.parseInt(accMgr.getUserData(account, "partner_id")));
    setAvatar(accMgr.getUserData(account, "avatar"));
    setDatabase(accMgr.getUserData(account, "database"));
    setHost(accMgr.getUserData(account, "host"));
    setCompanyId(Integer.parseInt(accMgr.getUserData(account, "company_id")));
    setSession_id(accMgr.getUserData(account, "session_id"));
    setFCMID(accMgr.getUserData(account, "fcm_project_id"));
}
 
Example 43
Project: TPlayer   File: VAccountManagerService.java   Source Code and License 5 votes vote down vote up
@Override
public void renameAccount(int userId, IAccountManagerResponse response, Account accountToRename, String newName) {
    if (accountToRename == null) throw new IllegalArgumentException("account is null");
    Account resultingAccount = renameAccountInternal(userId, accountToRename, newName);
    Bundle result = new Bundle();
    result.putString(AccountManager.KEY_ACCOUNT_NAME, resultingAccount.name);
    result.putString(AccountManager.KEY_ACCOUNT_TYPE, resultingAccount.type);
    try {
        response.onResult(result);
    } catch (RemoteException e) {
        Log.w(TAG, e.getMessage());
    }
}
 
Example 44
Project: GeekZone   File: AndroidAuthenticator.java   Source Code and License 5 votes vote down vote up
AndroidAuthenticator(AccountManager accountManager, Account account,
        String authTokenType, boolean notifyAuthFailure) {
    mAccountManager = accountManager;
    mAccount = account;
    mAuthTokenType = authTokenType;
    mNotifyAuthFailure = notifyAuthFailure;
}
 
Example 45
Project: TPlayer   File: VAccountManagerService.java   Source Code and License 5 votes vote down vote up
void bind() {
    Log.v(TAG, "initiating bind to authenticator type " + mAuthenticatorInfo.desc.type);
    Intent intent = new Intent();
    intent.setAction(AccountManager.ACTION_AUTHENTICATOR_INTENT);
    intent.setClassName(mAuthenticatorInfo.serviceInfo.packageName, mAuthenticatorInfo.serviceInfo.name);
    intent.putExtra("_VA_|_user_id_", mUserId);

    if (!mContext.bindService(intent, this, Context.BIND_AUTO_CREATE)) {
        Log.d(TAG, "bind attempt failed for " + toDebugString());
        onError(AccountManager.ERROR_CODE_REMOTE_EXCEPTION, "bind failure");
    }
}
 
Example 46
Project: ChatExchange-old   File: AuthenticatorActivity.java   Source Code and License 5 votes vote down vote up
private void onAuthFinish(String accountName, String authToken)
{
    // Create the intent for returning to the caller
    Intent intent = new Intent();
    intent.putExtra(AccountManager.KEY_ACCOUNT_NAME, accountName);
    intent.putExtra(AccountManager.KEY_ACCOUNT_TYPE, Authenticator.ACCOUNT_TYPE);
    intent.putExtra(AccountManager.KEY_AUTHTOKEN, authToken);

    setAccountAuthenticatorResult(intent.getExtras());
    setResult(RESULT_OK, intent);
    startActivity(new Intent(this, MainActivity.class));
    finish();
}
 
Example 47
Project: ChatExchange-old   File: Authenticator.java   Source Code and License 5 votes vote down vote up
/**
 * Return a bundle with the information necessary to create a new account
 */
private Bundle newAccount(AccountAuthenticatorResponse response)
{
    Intent intent = new Intent(mContext, AuthenticatorActivity.class);
    intent.putExtra(AccountManager.KEY_ACCOUNT_AUTHENTICATOR_RESPONSE, response);
    Bundle bundle = new Bundle();
    bundle.putParcelable(AccountManager.KEY_INTENT, intent);
    return bundle;
}
 
Example 48
Project: ChatExchange-old   File: PreferencesActivity.java   Source Code and License 5 votes vote down vote up
@Override
protected void onCreate(Bundle savedInstanceState)
{
    themeHue = new ThemeHue();
    actionBarHue = new ActionBarHue();
    ThemeHue.setTheme(PreferencesActivity.this);

    super.onCreate(null);
    getFragmentManager().beginTransaction().replace(android.R.id.content, new MyPreferenceFragment()).commit();

    mSharedPrefs = PreferenceManager.getDefaultSharedPreferences(this);

    ActionBarHue.setActionBarColorToSharedPrefsValue(this);

    AccountManager mAccountManager = AccountManager.get(this);
    if (mAccountManager.getAccounts().length > 0)
    {
        Account[] mAccounts = mAccountManager.getAccounts();

        for (Account a : mAccounts)
        {
            mAccountNames.add(a.name);
        }
    }

    getSupportActionBar().setDisplayHomeAsUpEnabled(true);
}
 
Example 49
Project: iosched-reader   File: AccountFragment.java   Source Code and License 5 votes vote down vote up
@Override
public void onAttach(Activity activity) {
    super.onAttach(activity);

    mAccountManager = AccountManager.get(activity);
    mAccounts = new ArrayList<Account>(
            Arrays.asList(mAccountManager.getAccountsByType(GoogleAuthUtil.GOOGLE_ACCOUNT_TYPE)));
}
 
Example 50
Project: VirtualHook   File: VAccountManagerService.java   Source Code and License 5 votes vote down vote up
void bind() {
	Log.v(TAG, "initiating bind to authenticator type " + mAuthenticatorInfo.desc.type);
	Intent intent = new Intent();
	intent.setAction(AccountManager.ACTION_AUTHENTICATOR_INTENT);
	intent.setClassName(mAuthenticatorInfo.serviceInfo.packageName, mAuthenticatorInfo.serviceInfo.name);
	intent.putExtra("_VA_|_user_id_", mUserId);

	if (!mContext.bindService(intent, this, Context.BIND_AUTO_CREATE)) {
		Log.d(TAG, "bind attempt failed for " + toDebugString());
		onError(AccountManager.ERROR_CODE_REMOTE_EXCEPTION, "bind failure");
	}
}
 
Example 51
Project: AOSP-Kayboard-7.1.2   File: AccountUtils.java   Source Code and License 4 votes vote down vote up
private static Account[] getAccounts(final Context context) {
    return AccountManager.get(context).getAccounts();
}
 
Example 52
Project: Linphone4Android   File: InAppPurchaseHelper.java   Source Code and License 4 votes vote down vote up
public String getGmailAccount() {
	Account[] accounts = AccountManager.get(mContext).getAccountsByType("com.google");
	
    for (Account account: accounts) {
    	if (isEmailCorrect(account.name)) {
            String possibleEmail = account.name;
            return possibleEmail;
        }
    }
    
    return null;
}
 
Example 53
Project: FBEventSync   File: AuthenticatorActivity.java   Source Code and License 4 votes vote down vote up
private void createAccount(String accessToken, String accountName) {
    mLogger.debug("AUTH", "Creating account %s", accountName);
    Intent intent = getIntent();
    Account account = new Account(accountName, intent.getStringExtra(AccountManager.KEY_ACCOUNT_TYPE));
    if (intent.getBooleanExtra(ARG_IS_ADDING_NEW_ACCOUNT, false)) {
        mAccountManager.addAccountExplicitly(account, null, null);

        ContentResolver.setIsSyncable(account, CalendarContract.AUTHORITY, 1);
        ContentResolver.setSyncAutomatically(account, CalendarContract.AUTHORITY, true);
    }

    Uri icalUri = Uri.parse(mBDayCalendar);
    String key = icalUri.getQueryParameter("key");
    String uid = icalUri.getQueryParameter("uid");
    if (key == null || key.isEmpty() || uid == null || uid.isEmpty()) {
        mLogger.error("AUTH", "Failed to retrieve iCal URL! The raw URL was " + mBDayCalendar);
        Toast.makeText(this, getString(R.string.auth_calendar_uri_error_toast), Toast.LENGTH_SHORT)
                .show();
        finish();
        return;
    }
    mAccountManager.setUserData(account, Authenticator.DATA_BDAY_URI, null); // clear the legacy storage
    mAccountManager.setAuthToken(account, Authenticator.FB_OAUTH_TOKEN, accessToken);
    mAccountManager.setAuthToken(account, Authenticator.FB_KEY_TOKEN, key);
    mAccountManager.setAuthToken(account, Authenticator.FB_UID_TOKEN, uid);

    Intent result = new Intent();
    result.putExtra(AccountManager.KEY_ACCOUNT_NAME, accountName);
    result.putExtra(AccountManager.KEY_ACCOUNT_TYPE, intent.getStringExtra(AccountManager.KEY_ACCOUNT_TYPE));
    String authTokenType = intent.getStringExtra(AuthenticatorActivity.ARG_AUTH_TOKEN_TYPE);
    if (authTokenType != null && authTokenType.equals(Authenticator.FB_KEY_TOKEN)) {
        result.putExtra(AccountManager.KEY_AUTHTOKEN, key);
    } else if (authTokenType != null && authTokenType.equals(Authenticator.FB_UID_TOKEN)) {
        result.putExtra(AccountManager.KEY_AUTHTOKEN, uid);
    } else {
        result.putExtra(AccountManager.KEY_AUTHTOKEN, accessToken);
    }

    setAccountAuthenticatorResult(result.getExtras());
    setResult(RESULT_OK, result);

    CalendarSyncAdapter.updateSync(this);

    Toast.makeText(this, R.string.auth_account_creation_success_toast, Toast.LENGTH_SHORT)
            .show();
    finish();
}
 
Example 54
Project: boohee_v5.6   File: AndroidAuthenticator.java   Source Code and License 4 votes vote down vote up
AndroidAuthenticator(AccountManager accountManager, Account account, String authTokenType, boolean notifyAuthFailure) {
    this.mAccountManager = accountManager;
    this.mAccount = account;
    this.mAuthTokenType = authTokenType;
    this.mNotifyAuthFailure = notifyAuthFailure;
}
 
Example 55
Project: EasyAndroid   File: Managers.java   Source Code and License 4 votes vote down vote up
/**
 * 返回 {@link AccountManager}
 */
public static AccountManager getAccountManager()
{
    return (AccountManager) get(ACCOUNT_SERVICE);
}
 
Example 56
Project: container   File: VAccountManagerService.java   Source Code and License 4 votes vote down vote up
private void sendAccountsChangedBroadcast(int userId) {
      Intent intent = new Intent(AccountManager.LOGIN_ACCOUNTS_CHANGED_ACTION);
VActivityManager.get().sendBroadcast(intent, userId);
broadcastCheckInNow(userId);
  }
 
Example 57
Project: financisto1-holo   File: FlowzrSyncTask.java   Source Code and License 4 votes vote down vote up
protected void onGetAuthToken(Bundle bundle) {
	String auth_token = bundle.getString(AccountManager.KEY_AUTHTOKEN);
	new GetCookieTask().execute(auth_token);
}
 
Example 58
Project: chromium-net-for-android   File: HttpNegotiateAuthenticator.java   Source Code and License 4 votes vote down vote up
/**
 * Process a result bundle from a completed token request, communicating its content back to
 * the native code.
 */
private void processResult(Bundle result, RequestData requestData) {
    mSpnegoContext = result.getBundle(HttpNegotiateConstants.KEY_SPNEGO_CONTEXT);
    int status;
    switch (result.getInt(
            HttpNegotiateConstants.KEY_SPNEGO_RESULT, HttpNegotiateConstants.ERR_UNEXPECTED)) {
        case HttpNegotiateConstants.OK:
            status = 0;
            break;
        case HttpNegotiateConstants.ERR_UNEXPECTED:
            status = NetError.ERR_UNEXPECTED;
            break;
        case HttpNegotiateConstants.ERR_ABORTED:
            status = NetError.ERR_ABORTED;
            break;
        case HttpNegotiateConstants.ERR_UNEXPECTED_SECURITY_LIBRARY_STATUS:
            status = NetError.ERR_UNEXPECTED_SECURITY_LIBRARY_STATUS;
            break;
        case HttpNegotiateConstants.ERR_INVALID_RESPONSE:
            status = NetError.ERR_INVALID_RESPONSE;
            break;
        case HttpNegotiateConstants.ERR_INVALID_AUTH_CREDENTIALS:
            status = NetError.ERR_INVALID_AUTH_CREDENTIALS;
            break;
        case HttpNegotiateConstants.ERR_UNSUPPORTED_AUTH_SCHEME:
            status = NetError.ERR_UNSUPPORTED_AUTH_SCHEME;
            break;
        case HttpNegotiateConstants.ERR_MISSING_AUTH_CREDENTIALS:
            status = NetError.ERR_MISSING_AUTH_CREDENTIALS;
            break;
        case HttpNegotiateConstants.ERR_UNDOCUMENTED_SECURITY_LIBRARY_STATUS:
            status = NetError.ERR_UNDOCUMENTED_SECURITY_LIBRARY_STATUS;
            break;
        case HttpNegotiateConstants.ERR_MALFORMED_IDENTITY:
            status = NetError.ERR_MALFORMED_IDENTITY;
            break;
        default:
            status = NetError.ERR_UNEXPECTED;
    }
    nativeSetResult(requestData.nativeResultObject, status,
            result.getString(AccountManager.KEY_AUTHTOKEN));
}
 
Example 59
Project: chromium-net-for-android   File: HttpNegotiateAuthenticatorTest.java   Source Code and License 4 votes vote down vote up
@Implementation
public static AccountManager get(Context context) {
    return sMockAccountManager;
}
 
Example 60
Project: mobly-bundled-snippets   File: AccountSnippet.java   Source Code and License 4 votes vote down vote up
/**
 * Adds a Google account to the device.
 *
 * <p>TODO(adorokhine): Support adding accounts of other types with an optional 'type' kwarg.
 *
 * <p>TODO(adorokhine): Allow users to choose whether to enable/disable sync with a kwarg.
 *
 * @param username Username of the account to add (including @gmail.com).
 * @param password Password of the account to add.
 */
@Rpc(
    description = "Add a Google (GMail) account to the device, with account data sync disabled."
)
public void addAccount(String username, String password)
        throws AccountSnippetException, AccountsException, IOException {
    // Check for existing account. If we try to re-add an existing account, Android throws an
    // exception that says "Account does not exist or not visible. Maybe change pwd?" which is
    // a little hard to understand.
    if (listAccounts().contains(username)) {
        throw new AccountSnippetException(
                "Account " + username + " already exists on the device");
    }
    Bundle addAccountOptions = new Bundle();
    addAccountOptions.putString("username", username);
    addAccountOptions.putString("password", password);
    AccountManagerFuture<Bundle> future =
            mAccountManager.addAccount(
                    GOOGLE_ACCOUNT_TYPE,
                    AUTH_TOKEN_TYPE,
                    null /* requiredFeatures */,
                    addAccountOptions,
                    null /* activity */,
                    null /* authCallback */,
                    null /* handler */);
    Bundle result = future.getResult();
    if (result.containsKey(AccountManager.KEY_ERROR_CODE)) {
        throw new AccountSnippetException(
                String.format(
                        Locale.US,
                        "Failed to add account due to code %d: %s",
                        result.getInt(AccountManager.KEY_ERROR_CODE),
                        result.getString(AccountManager.KEY_ERROR_MESSAGE)));
    }

    // Disable sync to avoid test flakiness as accounts fetch additional data.
    // It takes a while for all sync adapters to be populated, so register for broadcasts when
    // sync is starting and disable them there.
    // NOTE: this listener is NOT unregistered because several sync requests for the new account
    // will come in over time.
    Account account = new Account(username, GOOGLE_ACCOUNT_TYPE);
    Object handle =
            ContentResolver.addStatusChangeListener(
                    ContentResolver.SYNC_OBSERVER_TYPE_ACTIVE
                            | ContentResolver.SYNC_OBSERVER_TYPE_PENDING,
                    which -> {
                        for (SyncAdapterType adapter : ContentResolver.getSyncAdapterTypes()) {
                            // Ignore non-Google account types.
                            if (!adapter.accountType.equals(GOOGLE_ACCOUNT_TYPE)) {
                                continue;
                            }
                            // If a content provider is not whitelisted, then disable it.
                            // Because startSync and stopSync synchronously update the whitelist
                            // and sync settings, writelock both the whitelist check and the
                            // call to sync together.
                            mLock.writeLock().lock();
                            try {
                                if (!isAdapterWhitelisted(username, adapter.authority)) {
                                    updateSync(account, adapter.authority, false /* sync */);
                                }
                            } finally {
                                mLock.writeLock().unlock();
                            }
                        }
                    });
    mSyncStatusObserverHandles.add(handle);
}