Java Code Examples for android.accounts.AccountManager

The following examples show how to use android.accounts.AccountManager. These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source Project: cathode   Source File: Accounts.java    License: Apache License 2.0 8 votes vote down vote up
public static void removeAccount(Context context) {
  try {
    AccountManager am = AccountManager.get(context);
    Account account = getAccount(context);
    ContentResolver.removePeriodicSync(account, BuildConfig.PROVIDER_AUTHORITY, new Bundle());
    ContentResolver.removePeriodicSync(account, BuildConfig.AUTHORITY_DUMMY_CALENDAR,
        new Bundle());
    AccountAuthenticator.allowRemove();
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP_MR1) {
      am.removeAccount(account, null, null, null);
    } else {
      am.removeAccount(account, null, null);
    }
  } catch (SecurityException e) {
    Timber.e(e, "Unable to remove account");
  }
}
 
Example 2
/**
 * Service clean up
 */
@Override
public void onDestroy() {
    Log_OC.v(TAG, "Destroying service" );
    mBinder = null;
    mServiceHandler = null;
    mServiceLooper.quit();
    mServiceLooper = null;
    mNotificationManager = null;

    // remove AccountsUpdatedListener
    AccountManager am = AccountManager.get(getApplicationContext());
    am.removeOnAccountsUpdatedListener(this);

    super.onDestroy();
}
 
Example 3
public static final AccountIdentifier getAccountIdentifierWithName(Context context, String account){
    String rootFolder = "Notes";
    String email = "local";
    if(account != null && !account.equals("local")) {
        AccountManager accountManager = AccountManager.get(context);
        Account[] accounts = AccountManager.get(context).getAccountsByType(AuthenticatorActivity.ARG_ACCOUNT_TYPE);

        for (Account acc : accounts) {
            if(account.equals(accountManager.getUserData(acc, AuthenticatorActivity.KEY_ACCOUNT_NAME))){
                email = accountManager.getUserData(acc, AuthenticatorActivity.KEY_EMAIL);
                rootFolder = accountManager.getUserData(acc, AuthenticatorActivity.KEY_ROOT_FOLDER);
            }
        }
    }

    return new AccountIdentifier(email,rootFolder);
}
 
Example 4
private void createAccount() {
    final Context context = this;

    new SilentBackgroundTask<Void>(this) {
        @Override
        protected Void doInBackground() {
            AccountManager accountManager = (AccountManager) context.getSystemService(ACCOUNT_SERVICE);
            Account account = new Account(Constants.SYNC_ACCOUNT_NAME, Constants.SYNC_ACCOUNT_TYPE);
            accountManager.addAccountExplicitly(account, null, null);

            SharedPreferences prefs = Util.getPreferences(context);
            boolean syncEnabled = prefs.getBoolean(Constants.PREFERENCES_KEY_SYNC_ENABLED, true);
            int syncInterval = Integer.parseInt(prefs.getString(Constants.PREFERENCES_KEY_SYNC_INTERVAL, "60"));

            // Add enabled/frequency to playlist syncing
            ContentResolver.setSyncAutomatically(account, Constants.SYNC_ACCOUNT_PLAYLIST_AUTHORITY, syncEnabled);
            ContentResolver.addPeriodicSync(account, Constants.SYNC_ACCOUNT_PLAYLIST_AUTHORITY, new Bundle(), 60L * syncInterval);

            return null;
        }
    }.execute();
}
 
Example 5
Source Project: Pioneer   Source File: MainPresenter.java    License: Apache License 2.0 6 votes vote down vote up
private void fetchPioneerAccount() {
    String ACCOUNT_TYPE = "com.github.baoti";
    String AUTH_TOKEN_TYPE = "pioneer";

    accountManager.getAuthTokenByFeatures(ACCOUNT_TYPE, AUTH_TOKEN_TYPE, null,
            getView().getActivity(), null, null,
            new AccountManagerCallback<Bundle>() {
                @Override
                public void run(AccountManagerFuture<Bundle> future) {
                    try {
                        Bundle result = future.getResult();
                        String name = result.getString(AccountManager.KEY_ACCOUNT_NAME);
                        String type = result.getString(AccountManager.KEY_ACCOUNT_TYPE);
                        String token = result.getString(AccountManager.KEY_AUTHTOKEN);
                        toaster.show(
                                String.format("Auth result - name: %s, type: %s, token: %s",
                                        name, type, token));
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }, null);
}
 
Example 6
Source Project: hr   Source File: OdooAccountManager.java    License: GNU Affero General Public License v3.0 6 votes vote down vote up
/**
 * Login to user account. changes active state for user.
 * Other users will be automatically logged out
 *
 * @param context
 * @param username
 * @return new user object
 */
public static OUser login(Context context, String username) {

    // Setting odoo instance to null
    App app = (App) context.getApplicationContext();
    app.setOdoo(null, null);
    // Clearing models registry
    OModelRegistry registry = new OModelRegistry();
    registry.clearAll();
    OUser activeUser = getActiveUser(context);
    // Logging out user if any
    if (activeUser != null) {
        logout(context, activeUser.getAndroidName());
    }

    OUser newUser = getDetails(context, username);
    if (newUser != null) {
        AccountManager accountManager = AccountManager.get(context);
        accountManager.setUserData(newUser.getAccount(), "isactive", "true");
        Log.i(TAG, newUser.getName() + " Logged in successfully");
        return newUser;
    }
    // Clearing old cache of the system
    OCacheUtils.clearSystemCache(context);
    return null;
}
 
Example 7
Source Project: WayHoo   Source File: AndroidAuthenticator.java    License: Apache License 2.0 6 votes vote down vote up
@SuppressWarnings("deprecation")
@Override
public String getAuthToken() throws AuthFailureError {
    final AccountManager accountManager = AccountManager.get(mContext);
    AccountManagerFuture<Bundle> future = accountManager.getAuthToken(mAccount,
            mAuthTokenType, mNotifyAuthFailure, null, null);
    Bundle result;
    try {
        result = future.getResult();
    } catch (Exception e) {
        throw new AuthFailureError("Error while retrieving auth token", e);
    }
    String authToken = null;
    if (future.isDone() && !future.isCancelled()) {
        if (result.containsKey(AccountManager.KEY_INTENT)) {
            Intent intent = result.getParcelable(AccountManager.KEY_INTENT);
            throw new AuthFailureError(intent);
        }
        authToken = result.getString(AccountManager.KEY_AUTHTOKEN);
    }
    if (authToken == null) {
        throw new AuthFailureError("Got null auth token for type: " + mAuthTokenType);
    }

    return authToken;
}
 
Example 8
Source Project: drupalfit   Source File: ToolBarActivity.java    License: MIT License 6 votes vote down vote up
/** {@inheritDoc} */
@Override
public void addAccount(String username, String password, String authToken) {
    String accountType = "drualfit";
    String authTokenType = "drualfit";
    Account account = new Account(username, accountType);
    Bundle userdata = null;

    Intent intent = new Intent();

    intent.putExtra(AccountManager.KEY_ACCOUNT_NAME, username);
    intent.putExtra(AccountManager.KEY_ACCOUNT_TYPE, accountType);
    intent.putExtra(AccountManager.KEY_AUTHTOKEN, authToken);

    if (TextUtils.isEmpty(password)) {
        boolean added = getAccountManager().addAccountExplicitly(account, password, userdata);
    } else {
        getAccountManager().setPassword(account, password);
    }

    getAccountManager().setAuthToken(account, authTokenType, authToken);

    setAccountAuthenticatorResult(intent.getExtras());
    setResult(RESULT_OK, intent);
}
 
Example 9
Source Project: ChannelSurfer   Source File: DummyAccountService.java    License: MIT License 6 votes vote down vote up
@Override
public Bundle addAccount(AccountAuthenticatorResponse accountAuthenticatorResponse,
                         String s, String s2, String[] strings, Bundle options) throws NetworkErrorException {
    Log.d(TAG, "Trying to add an account");
    final AccountManager accountManager = AccountManager.get(getApplicationContext());
    String ACCOUNT_NAME = getApplicationContext().getString(R.string.app_name);
    Account[] accounts = accountManager.getAccountsByType(ACCOUNT_NAME);
    Log.d(TAG, accounts.length+"accounts");
    Log.d(TAG, accounts[0].toString());
    if(accounts.length > 0) {
        final Intent intent = new Intent(getApplicationContext(), DummyAccountIgnoreActivity.class);
        intent.putExtra(DummyAccountIgnoreActivity.INTENT_ACTION, DummyAccountIgnoreActivity.ACTION_ADD);
        final Bundle bundle = new Bundle();
        bundle.putParcelable(AccountManager.KEY_INTENT, intent);
        return bundle;
    } else {
        return null;
    }
}
 
Example 10
/**
 * Create the preference for allow adding new accounts
 */
private void createAddAccountPreference() {
    Preference addAccountPref = new Preference(this);
    addAccountPref.setKey("add_account");
    addAccountPref.setTitle(getString(R.string.prefs_add_account));
    mAccountsPrefCategory.addPreference(addAccountPref);

    addAccountPref.setOnPreferenceClickListener(new OnPreferenceClickListener() {
        @Override
        public boolean onPreferenceClick(Preference preference) {
            AccountManager am = AccountManager.get(getApplicationContext());
            am.addAccount(MainApp.getAccountType(), null, null, null, Preferences.this,
                    null, null);
            return true;
        }
    });

}
 
Example 11
Source Project: v2ex   Source File: SyncUtils.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Create an entry for this application in the system account list, if it isn't already there.
 *
 * @param context Context
 */
public static void createSyncAccount(Context context) {

    // Create account, if it's missing. (Either first run, or user has deleted account.)
    Account account = AccountUtils.getActiveAccount(context);
    AccountManager accountManager = (AccountManager) context.getSystemService(Context.ACCOUNT_SERVICE);
    accountManager.addAccountExplicitly(account, null, null);
    // Inform the system that this account supports sync
    ContentResolver.setIsSyncable(account, V2exContract.CONTENT_AUTHORITY, 1);
    // Inform the system that this account is eligible for auto sync when the network is up
    ContentResolver.setSyncAutomatically(account, V2exContract.CONTENT_AUTHORITY, true);

    Bundle extras = new Bundle();

    extras.putBoolean(ContentResolver.SYNC_EXTRAS_MANUAL, false);
    extras.putBoolean(ContentResolver.SYNC_EXTRAS_UPLOAD, false);
    extras.putBoolean(SyncAdapter.EXTRA_SYNC_REMOTE, true);

    // Recommend a schedule for automatic synchronization. The system may modify this based
    // on other scheduled syncs and network utilization.
    ContentResolver.addPeriodicSync(
            account, V2exContract.CONTENT_AUTHORITY, extras, SYNC_FREQUENCY);
}
 
Example 12
Source Project: android-discourse   Source File: AndroidAuthenticator.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public String getAuthToken() throws AuthFailureError {
    final AccountManager accountManager = AccountManager.get(mContext);
    AccountManagerFuture<Bundle> future = accountManager.getAuthToken(mAccount, mAuthTokenType, mNotifyAuthFailure, null, null);
    Bundle result;
    try {
        result = future.getResult();
    } catch (Exception e) {
        throw new AuthFailureError("Error while retrieving auth token", e);
    }
    String authToken = null;
    if (future.isDone() && !future.isCancelled()) {
        if (result.containsKey(AccountManager.KEY_INTENT)) {
            Intent intent = result.getParcelable(AccountManager.KEY_INTENT);
            throw new AuthFailureError(intent);
        }
        authToken = result.getString(AccountManager.KEY_AUTHTOKEN);
    }
    if (authToken == null) {
        throw new AuthFailureError("Got null auth token for type: " + mAuthTokenType);
    }

    return authToken;
}
 
Example 13
Source Project: android-atleap   Source File: AuthHelper.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Recreate authToken for the specified account. Do not use this method from main thread.
 * @param context context
 * @param account account
 * @param accountType accountType
 * @param authTokenType authTokenType
 * @param requiredFeatures requiredFeatures, could be <code>null</code>
 * @param options options, could be <code>null</code>
 * @param activity activity, could be <code>null</code>
 */
public static void reCreateAuthTokenBlocking(Context context, Account account, String accountType, String authTokenType, String[] requiredFeatures, Bundle options, Activity activity) {
    boolean isAccountExist = isAccountExist(context, account);
    if (!isAccountExist) {
        addAccountBlocking(context, accountType, authTokenType, requiredFeatures, options, activity);
        return;
    }

    final AccountManager am = AccountManager.get(context);
    String authToken = am.peekAuthToken(account, authTokenType);

    if (TextUtils.isEmpty(authToken)) {
        getAuthTokenWithoutCheck(context, account, authTokenType, options, activity);
        return;
    }

    am.invalidateAuthToken(account.type, authToken);

    getAuthTokenWithoutCheck(context, account, authTokenType, options, activity);
}
 
Example 14
Source Project: materialistic   Source File: DrawerActivityLoginTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testAddAccount() {
    AccountManager.get(activity).addAccountExplicitly(new Account("existing",
            BuildConfig.APPLICATION_ID), "password", null);
    drawerAccount.performClick();
    AlertDialog alertDialog = ShadowAlertDialog.getLatestAlertDialog();
    assertNotNull(alertDialog);
    assertThat(alertDialog.getListView().getAdapter()).hasCount(1);
    alertDialog.getButton(DialogInterface.BUTTON_NEGATIVE).performClick();
    assertThat(alertDialog).isNotShowing();
    ((ShadowSupportDrawerLayout) Shadow.extract(activity.findViewById(R.id.drawer_layout)))
            .getDrawerListeners().get(0)
            .onDrawerClosed(activity.findViewById(R.id.drawer));
    assertThat(shadowOf(activity).getNextStartedActivity())
            .hasComponent(activity, LoginActivity.class);
}
 
Example 15
Source Project: coursera-android   Source File: InsertActivity.java    License: MIT License 6 votes vote down vote up
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    // Exit if there are no google accounts
    if (AccountManager.get(this).getAccountsByType("com.google").length == 0)
        finish();

    setContentView(R.layout.main);
    mInsertButton = findViewById(R.id.insert);

    if (!checkPermission()) {
        requestPermissions(permissions, mRequestCode);
    } else {
        onPermissionsGranted();
    }
}
 
Example 16
Source Project: cnode-android   Source File: MainActivity.java    License: MIT License 6 votes vote down vote up
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    setContentView(R.layout.activity_main);

    queue = Volley.newRequestQueue(this);

    accountManager = AccountManager.get(this);

    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    toolbar.setTitle("");
    setSupportActionBar(toolbar);

    setupSwipingLayout();
    setupTopicsView();
    setupFilter();
}
 
Example 17
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_detail);

    toolbar = (Toolbar) findViewById(R.id.toolbar);
    if(toolbar != null){
        toolbar.setTitle("");
    }

    detailFragment = (DetailFragment)getFragmentManager().findFragmentById(R.id.detail_fragment);

    Intent startIntent = getIntent();
    String uid = startIntent.getStringExtra(Utils.NOTE_UID);
    String notebook = startIntent.getStringExtra(Utils.NOTEBOOK_UID);

    detailFragment.setStartNotebook(notebook);
    detailFragment.setStartUid(uid);

    String action = startIntent.getAction();
    if (Intent.ACTION_SEND.equals(action)) {
        AccountManager accountManager = AccountManager.get(this);
        Account[] accounts = AccountManager.get(this).getAccountsByType(AuthenticatorActivity.ARG_ACCOUNT_TYPE);
    }
}
 
Example 18
Source Project: COCOFramework   Source File: SyncAdapterHelper.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Create a new dummy account for the sync adapter
 *
 * @param context The application context
 */
public Account createSyncAccount(Context context) {
    // Create the account type and default account
    Account newAccount = mAccount == null ? new Account(
            ACCOUNT, ACCOUNT_TYPE) : mAccount;
    // Get an instance of the Android account manager
    AccountManager accountManager =
            (AccountManager) context.getSystemService(
                    Context.ACCOUNT_SERVICE);
    /*
     * Add the account and account type, no password or user data
     * If successful, return the Account object, otherwise report an error.
     */
    if (accountManager.addAccountExplicitly(newAccount, null, null)) {
        ContentResolver.setIsSyncable(newAccount, AUTHORITY, 1);
        turnOnSync(newAccount);
    }
    return newAccount;
}
 
Example 19
Source Project: tindroid   Source File: ChatsActivity.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public void onMetaSub(final Subscription<VxCard,PrivateType> sub) {
    if (sub.deleted == null) {
        if (sub.pub != null) {
            sub.pub.constructBitmap();
        }

        if (!UiUtils.isPermissionGranted(ChatsActivity.this, Manifest.permission.WRITE_CONTACTS)) {
            // We can't save contact if we don't have appropriate permission.
            return;
        }

        if (mAccount == null) {
            mAccount = Utils.getSavedAccount(AccountManager.get(ChatsActivity.this),
                    Cache.getTinode().getMyId());
        }
        if (Topic.getTopicTypeByName(sub.topic) == Topic.TopicType.P2P) {
            ContactsManager.processContact(ChatsActivity.this,
                    ChatsActivity.this.getContentResolver(),
                    mAccount, sub.pub, null, sub.getUnique(), sub.deleted != null,
                    null, false);
        }
    }
}
 
Example 20
@Override
public void onReceive(Context context, Intent intent) {
    if (!AccountManager.LOGIN_ACCOUNTS_CHANGED_ACTION.equals(intent.getAction())) {
        Log.w(TAG, "Received unknown broadcast: " + intent);
        return;
    }

    // Ideally the account preference could live in a different preferences file
    // that wasn't being backed up and restored, however the preference fragments
    // currently only deal with the default shared preferences which is why
    // separating this out into a different file is not trivial currently.
    final SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);
    final String currentAccount = prefs.getString(
            LocalSettingsConstants.PREF_ACCOUNT_NAME, null);
    removeUnknownAccountFromPreference(prefs, getAccountsForLogin(context), currentAccount);
}
 
Example 21
Source Project: android-proguards   Source File: DesignerNewsLogin.java    License: Apache License 2.0 6 votes vote down vote up
@SuppressLint("NewApi")
private void setupAccountAutocomplete() {
    if (ContextCompat.checkSelfPermission(this, Manifest.permission.GET_ACCOUNTS) ==
            PackageManager.PERMISSION_GRANTED) {
        permissionPrimer.setVisibility(View.GONE);
        final Account[] accounts = AccountManager.get(this).getAccounts();
        final Set<String> emailSet = new HashSet<>();
        for (Account account : accounts) {
            if (Patterns.EMAIL_ADDRESS.matcher(account.name).matches()) {
                emailSet.add(account.name);
            }
        }
        username.setAdapter(new ArrayAdapter<>(this,
                R.layout.account_dropdown_item, new ArrayList<>(emailSet)));
    } else {
        if (shouldShowRequestPermissionRationale(Manifest.permission.GET_ACCOUNTS)) {
            setupPermissionPrimer();
        } else {
            permissionPrimer.setVisibility(View.GONE);
            shouldPromptForPermission = true;
        }
    }
}
 
Example 22
private SignInResult signInAndDoAfter(final Account account, final String authTokenType, final String authToken, final Bundle options) {
    final SignInResult[] signInResult = new SignInResult[1];
    new AsyncTask<Void, Void, Void>() {

        @Override
        protected Void doInBackground(Void... params) {
            signInResult[0] = interfaceImplementation.signInToServer(context, account, authTokenType, authToken, options);
            return null;
        }

        @Override
        protected void onPostExecute(Void aVoid) {
            if (signInResult[0].isSuccessful) {
                interfaceImplementation.doAfterSignInIsSuccessful(context, account, authTokenType, authToken, signInResult[0], options);
            } else {
                if (signInResult[0].isAccessTokenExpired) {
                    AccountManager accountManager = AccountManager.get(context);
                    accountManager.invalidateAuthToken(accountType, authToken);
                    Toast.makeText(context, signInResult[0].errMessage + ", getting new access token from the server", Toast.LENGTH_SHORT).show();
                    signUpAndDoAfter(account, authTokenType, accountManager.getPassword(account), options);
                } else {
                    Toast.makeText(context, "Sign-in was not possible due to the following:\n" + signInResult[0].errMessage, Toast.LENGTH_SHORT).show();
                }
            }
        }
    }.execute();
    return signInResult[0];
}
 
Example 23
private Bundle createAuthActivityIntentBundle(AccountAuthenticatorResponse response,
    String accountType, String[] requiredFeatures, String authTokenType, String password,
    Bundle options) {

  final Bundle bundle = new Bundle();
  final Intent intent = createAuthActivityIntent(response, accountType, authTokenType, options);
  bundle.putParcelable(AccountManager.KEY_INTENT, intent);

  return bundle;
}
 
Example 24
Source Project: android-atleap   Source File: BaseAuthenticator.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * {@inheritDoc}
 */
@Override
public Bundle getAuthToken(AccountAuthenticatorResponse response, Account account, String authTokenType, Bundle options) throws NetworkErrorException {

    Log.v(TAG, "getAuthToken for account=" + account + " and tokenType=" + authTokenType);

    final AccountManager am = AccountManager.get(mContext);

    String authToken = am.peekAuthToken(account, authTokenType);

    if (!TextUtils.isEmpty(authToken)) {
        Log.v(TAG, "Auth token is in the cache. Retuning.");
        return createAccountManagerResult(account, authToken);
    }

    Log.v(TAG, "Trying to get password from cache");

    final String password = am.getPassword(account);
    if (TextUtils.isEmpty(authToken)) {
        if (password != null) {
            Log.v(TAG, "Password is in cache. Trying to authenticate again.");
            try {
                authToken = authenticateOnServer(account, password, authTokenType, options, response);
            } catch (Exception e) {
                Log.w(TAG, "Cannot authenticate on the server", e);
            }
        }
    }


    if (!TextUtils.isEmpty(authToken)) {
        Log.v(TAG, "Auth token was received from the server");
        return createAccountManagerResult(account, authToken);
    }


    Log.v(TAG, "Auth token was not received. Starting auth activity.");
    return createAuthActivityIntentBundle(response, account.name, account.type, authTokenType, password, options);
}
 
Example 25
Source Project: product-emm   Source File: AndroidAuthenticator.java    License: Apache License 2.0 5 votes vote down vote up
AndroidAuthenticator(AccountManager accountManager, Account account,
        String authTokenType, boolean notifyAuthFailure) {
    mAccountManager = accountManager;
    mAccount = account;
    mAuthTokenType = authTokenType;
    mNotifyAuthFailure = notifyAuthFailure;
}
 
Example 26
Source Project: moVirt   Source File: AddAccountActivity.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Retreives the AccountAuthenticatorResponse from either the intent of the icicle, if the
 * icicle is non-zero.
 *
 * @param icicle the save instance data of this Activity, may be null
 */
@Override
protected void onCreate(Bundle icicle) {
    super.onCreate(icicle);

    mAccountAuthenticatorResponse =
            getIntent().getParcelableExtra(AccountManager.KEY_ACCOUNT_AUTHENTICATOR_RESPONSE);

    if (mAccountAuthenticatorResponse != null) {
        mAccountAuthenticatorResponse.onRequestContinued();
    }
}
 
Example 27
Source Project: Pioneer   Source File: AccountAuthenticator.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public Bundle getAuthToken(AccountAuthenticatorResponse response, Account account, String authTokenType, Bundle options) throws NetworkErrorException {
    Timber.d("[getAuthToken] - account: %s, authTokenType: %s", account, authTokenType);

    Bundle result = new Bundle();

    if (!authTokenType.equals(AUTH_TOKEN_TYPE_PIONEER)) {
        return result;
    }

    AccountManager am = AccountManager.get(context);
    String password = am.getPassword(account);
    if (TextUtils.isEmpty(password)) {
        result.putParcelable(KEY_INTENT, createActivityIntent(response, authTokenType));
        return result;
    }

    String authToken = getOrCreateAuthorization(account.name, password);

    if (TextUtils.isEmpty(authToken)) {
        result.putParcelable(KEY_INTENT, createActivityIntent(response, authTokenType));
    } else {
        result.putString(KEY_ACCOUNT_NAME, account.name);
        result.putString(KEY_ACCOUNT_TYPE, ACCOUNT_TYPE);
        result.putString(KEY_AUTHTOKEN, authToken);
        am.clearPassword(account);
    }
    return result;
}
 
Example 28
Source Project: CrossBow   Source File: AndroidAuthenticatorTest.java    License: Apache License 2.0 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 29
Source Project: android-testdpc   Source File: AddAccountActivity.java    License: Apache License 2.0 5 votes vote down vote up
private void accountCreated(Bundle result) {
    String accountNameAdded = result.getString(AccountManager.KEY_ACCOUNT_NAME);
    Log.d(TAG, "addAccount - accountNameAdded: " + accountNameAdded);
    if (mNextActivityIntent != null) {
        startActivity(mNextActivityIntent);
    }
    final Intent resultIntent = new Intent();
    resultIntent.putExtra(EXTRA_PROVISIONING_ACCOUNT_TO_MIGRATE,
        new Account(accountNameAdded, GOOGLE_ACCOUNT_TYPE));
    setResult(RESULT_OK, resultIntent);
    finish();

}
 
Example 30
Source Project: cathode   Source File: AccountAuthenticator.java    License: Apache License 2.0 5 votes vote down vote up
@Override public Bundle addAccount(AccountAuthenticatorResponse response, String accountType,
    String authTokenType, String[] requiredFeatures, Bundle options)
    throws NetworkErrorException {
  AccountManager manager = AccountManager.get(context);

  final Account account =
      new Account(context.getString(R.string.accountName), context.getPackageName());
  manager.addAccountExplicitly(account, null, null);

  return null;
}