Example usage for android.accounts AccountManager KEY_ACCOUNT_TYPE

List of usage examples for android.accounts AccountManager KEY_ACCOUNT_TYPE

Introduction

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

Prototype

String KEY_ACCOUNT_TYPE

To view the source code for android.accounts AccountManager KEY_ACCOUNT_TYPE.

Click Source Link

Document

Bundle key used for the String account type in results from methods which return information about a particular account.

Usage

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

/**
 * Called when response is received from the server for authentication
 * request. See onAuthenticationResult(). Sets the
 * AccountAuthenticatorResult which is sent back to the caller. Also sets
 * the authToken in AccountManager for this account.
 * /*  ww w  .j a  v a 2  s  . c om*/
 * @param the confirmCredentials result.
 */

protected void createAccount() {
    Log.v(TAG, "finishLogin()");
    final Account account = new Account(mUsername, OhmageApplication.ACCOUNT_TYPE);
    Bundle userData = new Bundle();
    userData.putString(KEY_OHMAGE_SERVER, ConfigHelper.serverUrl());
    mAuthtoken = mHashedPassword;

    if (TextUtils.isEmpty(mAuthtoken)) {
        Log.w(TAG, "Trying to create account with empty password");
        return;
    }

    if (mRequestNewAccount) {
        mAccountManager.addAccountExplicitly(account, mPassword, userData);
        mAccountManager.setAuthToken(account, OhmageApplication.AUTHTOKEN_TYPE, mAuthtoken);
        // Set sync for this account.
        ContentResolver.setIsSyncable(account, DbContract.CONTENT_AUTHORITY, 1);
        ContentResolver.setSyncAutomatically(account, DbContract.CONTENT_AUTHORITY, true);
        ContentResolver.addPeriodicSync(account, DbContract.CONTENT_AUTHORITY, new Bundle(), 3600);
    } else {
        mAccountManager.setPassword(account, mPassword);
    }
    final Intent intent = new Intent();
    intent.putExtra(AccountManager.KEY_ACCOUNT_NAME, mUsername);
    intent.putExtra(AccountManager.KEY_ACCOUNT_TYPE, OhmageApplication.ACCOUNT_TYPE);
    if (mAuthtokenType != null && mAuthtokenType.equals(OhmageApplication.AUTHTOKEN_TYPE)) {
        intent.putExtra(AccountManager.KEY_AUTHTOKEN, mAuthtoken);
    }
    setAccountAuthenticatorResult(intent.getExtras());
    setResult(RESULT_OK, intent);

    mPreferencesHelper.edit().putLoginTimestamp(System.currentTimeMillis()).commit();

    if (UserPreferencesHelper.isSingleCampaignMode()) {
        // Download the single campaign
        showDialog(DIALOG_DOWNLOADING_CAMPAIGNS);
        getSupportLoaderManager().restartLoader(0, null, this);
    } else {
        finishLogin();
    }
}

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

private void finishAccountAdd(String accountName, String authToken, String password) {
    final Intent intent = new Intent();
    intent.putExtra(AccountManager.KEY_ACCOUNT_NAME, accountName);
    intent.putExtra(AccountManager.KEY_ACCOUNT_TYPE, AuthUtil.ACCOUNT_TYPE);
    if (authToken != null)
        intent.putExtra(AccountManager.KEY_AUTHTOKEN, authToken);
    intent.putExtra(AccountManager.KEY_PASSWORD, password);
    setAccountAuthenticatorResult(intent.getExtras());
    setResult(RESULT_OK, intent);/*from   www.j a v  a2s  .  c o m*/
    finish();

    if (!calledByAuthenticator())
        startActivity(new Intent(getBaseContext(), MainActivity.class));
}

From source file:org.andstatus.app.account.AccountSettingsActivity.java

/** 
 * Mark the action completed, close this activity and go back to the proper screen.
 * Return result to the caller if necessary.
 * See also {@link com.android.email.activity.setup.AccountSetupBasics.finish}
 * /*from w  ww. j ava  2  s  .  c om*/
 * @return
 */
private void closeAndGoBack() {
    // Explicitly save MyAccount only on "Back key" 
    state.builder.save();
    String message = "";
    state.actionCompleted = true;
    overrideBackActivity = true;
    if (state.authenticatiorResponse != null) {
        // We should return result back to AccountManager
        overrideBackActivity = false;
        if (state.actionSucceeded) {
            if (state.builder.isPersistent()) {
                // Pass the new/edited account back to the account manager
                Bundle result = new Bundle();
                result.putString(AccountManager.KEY_ACCOUNT_NAME, state.getAccount().getAccountName());
                result.putString(AccountManager.KEY_ACCOUNT_TYPE, AuthenticatorService.ANDROID_ACCOUNT_TYPE);
                state.authenticatiorResponse.onResult(result);
                message += "authenticatiorResponse; account.name=" + state.getAccount().getAccountName() + "; ";
            }
        } else {
            state.authenticatiorResponse.onError(AccountManager.ERROR_CODE_CANCELED, "canceled");
        }
    }
    // Forget old state
    state.forget();
    if (!mIsFinishing) {
        MyLog.v(this, "finish: action=" + state.getAccountAction() + "; " + message);
        mIsFinishing = true;
        finish();
    }
}

From source file:mobile.tiis.appv2.LoginActivity.java

/**
 * This method will take the url built to use the webservice
 * and will try to parse JSON from the webservice stream to get
 * the user and password if they are correct or not. In case correct, fills
 * the Android Account Manager./* www. j  av  a 2s  . co  m*/
 *
 * <p>This method will throw a Toast message when user and password
 * are not valid
 *
 */

protected void startWebService(final CharSequence loginURL, final String username, final String password) {
    client.setBasicAuth(username, password, true);

    //new handler in case of login error in the thread
    handler = new Handler();

    Thread thread = new Thread(new Runnable() {
        public void run() {
            try {
                int balanceCounter = 0;
                DefaultHttpClient httpClient = new DefaultHttpClient();
                HttpGet httpGet = new HttpGet(loginURL.toString());
                Utils.writeNetworkLogFileOnSD(
                        Utils.returnDeviceIdAndTimestamp(getApplicationContext()) + loginURL.toString());
                httpGet.setHeader("Authorization", "Basic "
                        + Base64.encodeToString((username + ":" + password).getBytes(), Base64.NO_WRAP));
                HttpResponse httpResponse = httpClient.execute(httpGet);
                InputStream inputStream = httpResponse.getEntity().getContent();
                Log.d("", loginURL.toString());

                ByteArrayInputStream bais = Utils.getMultiReadInputStream(inputStream);
                Utils.writeNetworkLogFileOnSD(Utils.returnDeviceIdAndTimestamp(getApplicationContext())
                        + Utils.getStringFromInputStreamAndLeaveStreamOpen(bais));
                bais.reset();
                JsonFactory factory = new JsonFactory();
                JsonParser jsonParser = factory.createJsonParser(bais);
                JsonToken token = jsonParser.nextToken();

                if (token == JsonToken.START_OBJECT) {
                    balanceCounter++;
                    boolean idNextToHfId = false;
                    while (!(balanceCounter == 0)) {
                        token = jsonParser.nextToken();

                        if (token == JsonToken.START_OBJECT) {
                            balanceCounter++;
                        } else if (token == JsonToken.END_OBJECT) {
                            balanceCounter--;
                        } else if (token == JsonToken.FIELD_NAME) {
                            String object = jsonParser.getCurrentName();
                            switch (object) {
                            case "HealthFacilityId":
                                token = jsonParser.nextToken();
                                app.setLoggedInUserHealthFacilityId(jsonParser.getText());
                                Log.d("", "healthFacilityId is: " + jsonParser.getText());
                                idNextToHfId = true;
                                break;
                            case "Firstname":
                                token = jsonParser.nextToken();
                                app.setLoggedInFirstname(jsonParser.getText());
                                Log.d("", "firstname is: " + jsonParser.getText());
                                break;
                            case "Lastname":
                                token = jsonParser.nextToken();
                                app.setLoggedInLastname(jsonParser.getText());
                                Log.d("", "lastname is: " + jsonParser.getText());
                                break;
                            case "Username":
                                token = jsonParser.nextToken();
                                app.setLoggedInUsername(jsonParser.getText());
                                Log.d("", "username is: " + jsonParser.getText());
                                break;
                            case "Lastlogin":
                                token = jsonParser.nextToken();
                                Log.d("", "lastlogin is: " + jsonParser.getText());
                                break;
                            case "Id":
                                if (idNextToHfId) {
                                    token = jsonParser.nextToken();
                                    app.setLoggedInUserId(jsonParser.getText());
                                    Log.d("", "Id is: " + jsonParser.getText());
                                }
                                break;
                            default:
                                break;
                            }
                        }
                    }

                    Account account = new Account(username, ACCOUNT_TYPE);
                    AccountManager accountManager = AccountManager.get(LoginActivity.this);
                    //                        boolean accountCreated = accountManager.addAccountExplicitly(account, LoginActivity.this.password, null);
                    boolean accountCreated = accountManager.addAccountExplicitly(account, password, null);

                    Bundle extras = LoginActivity.this.getIntent().getExtras();
                    if (extras != null) {
                        if (accountCreated) { //Pass the new account back to the account manager
                            AccountAuthenticatorResponse response = extras
                                    .getParcelable(AccountManager.KEY_ACCOUNT_AUTHENTICATOR_RESPONSE);
                            Bundle res = new Bundle();
                            res.putString(AccountManager.KEY_ACCOUNT_NAME, username);
                            res.putString(AccountManager.KEY_ACCOUNT_TYPE, ACCOUNT_TYPE);
                            res.putString(AccountManager.KEY_PASSWORD, password);
                            response.onResult(res);
                        }
                    }

                    SharedPreferences prefs = PreferenceManager
                            .getDefaultSharedPreferences(getApplicationContext());
                    SharedPreferences.Editor editor = prefs.edit();
                    editor.putBoolean("secondSyncNeeded", true);
                    editor.commit();

                    ContentValues values = new ContentValues();
                    values.put(SQLHandler.SyncColumns.UPDATED, 1);
                    values.put(SQLHandler.UserColumns.FIRSTNAME, app.getLOGGED_IN_FIRSTNAME());
                    values.put(SQLHandler.UserColumns.LASTNAME, app.getLOGGED_IN_LASTNAME());
                    values.put(SQLHandler.UserColumns.HEALTH_FACILITY_ID, app.getLOGGED_IN_USER_HF_ID());
                    values.put(SQLHandler.UserColumns.ID, app.getLOGGED_IN_USER_ID());
                    values.put(SQLHandler.UserColumns.USERNAME, app.getLOGGED_IN_USERNAME());
                    values.put(SQLHandler.UserColumns.PASSWORD, password);
                    databaseHandler.addUser(values);

                    Log.d(TAG, "initiating offline for " + username + " password = " + password);
                    app.initializeOffline(username, password);

                    Intent intent;
                    if (prefs.getBoolean("synchronization_needed", true)) {
                        Log.d("supportLog", "call the loggin second time before the account was found");
                        intent = new Intent(LoginActivity.this, LotSettingsActivity.class);
                    } else {
                        Log.d("supportLog", "call the loggin second time before the account was found");
                        intent = new Intent(LoginActivity.this, LotSettingsActivity.class);
                        evaluateIfFirstLogin(app.getLOGGED_IN_USER_ID());
                    }
                    app.setUsername(username);

                    startActivity(intent);
                }
                //if login failed show error
                else {
                    handler.post(new Runnable() {
                        public void run() {
                            progressDialog.show();
                            progressDialog.dismiss();
                            toastMessage("Login failed.\nPlease check your details!");
                            loginButton.setEnabled(true);
                        }
                    });
                }
            } catch (Exception e) {
                handler.post(new Runnable() {
                    public void run() {
                        progressDialog.show();
                        progressDialog.dismiss();
                        toastMessage("Login failed Login failed.\n"
                                + "Please check your details or your web connectivity");
                        loginButton.setEnabled(true);

                    }
                });
                e.printStackTrace();
            }
        }
    });
    thread.start();

}

From source file:com.owncloud.android.authentication.AuthenticatorActivity.java

/**
 * Sets the proper response to get that the Account Authenticator that
 * started this activity saves a new authorization token for mAccount.
 */// w  w w  .j a  v  a2s.  co m
private boolean updateToken() {
    Bundle response = new Bundle();
    response.putString(AccountManager.KEY_ACCOUNT_NAME, mAccount.name);
    response.putString(AccountManager.KEY_ACCOUNT_TYPE, mAccount.type);

    if (AccountAuthenticator.AUTH_TOKEN_TYPE_ACCESS_TOKEN.equals(mAuthTokenType)) {
        response.putString(AccountManager.KEY_AUTHTOKEN, mAuthToken);
        // the next line is necessary; by now, notifications are calling
        // directly to the AuthenticatorActivity to update, without
        // AccountManager intervention
        mAccountMgr.setAuthToken(mAccount, mAuthTokenType, mAuthToken);

    } else if (AccountAuthenticator.AUTH_TOKEN_TYPE_SAML_WEB_SSO_SESSION_COOKIE.equals(mAuthTokenType)) {
        String username = getUserNameForSamlSso();

        if (!(mUsernameInput.getText().toString() + "@" + location).equals(username)) {
            // fail - not a new account, but an existing one; disallow
            RemoteOperationResult result = new RemoteOperationResult(ResultCode.ACCOUNT_NOT_THE_SAME);
            updateAuthStatusIconAndText(result);
            showAuthStatus();
            Log_OC.d(TAG, result.getLogMessage());

            return false;
        }

        response.putString(AccountManager.KEY_AUTHTOKEN, mAuthToken);
        // the next line is necessary; by now, notifications are calling
        // directly to the AuthenticatorActivity to update, without
        // AccountManager intervention
        mAccountMgr.setAuthToken(mAccount, mAuthTokenType, mAuthToken);

    } else {
        response.putString(AccountManager.KEY_AUTHTOKEN, mPasswordInput.getText().toString());
        mAccountMgr.setPassword(mAccount, mPasswordInput.getText().toString());
    }
    setAccountAuthenticatorResult(response);

    return true;
}

From source file:com.digitalarx.android.authentication.AuthenticatorActivity.java

/**
 * Sets the proper response to get that the Account Authenticator that started this activity saves 
 * a new authorization token for mAccount.
 *//*from  w  w w .jav a 2 s .  c  o  m*/
private void updateToken() {
    Bundle response = new Bundle();
    response.putString(AccountManager.KEY_ACCOUNT_NAME, mAccount.name);
    response.putString(AccountManager.KEY_ACCOUNT_TYPE, mAccount.type);

    if (AccountTypeUtils.getAuthTokenTypeAccessToken(MainApp.getAccountType()).equals(mAuthTokenType)) {
        response.putString(AccountManager.KEY_AUTHTOKEN, mAuthToken);
        // the next line is necessary; by now, notifications are calling directly to the AuthenticatorActivity to update, without AccountManager intervention
        mAccountMgr.setAuthToken(mAccount, mAuthTokenType, mAuthToken);

    } else if (AccountTypeUtils.getAuthTokenTypeSamlSessionCookie(MainApp.getAccountType())
            .equals(mAuthTokenType)) {

        response.putString(AccountManager.KEY_AUTHTOKEN, mAuthToken);
        // the next line is necessary; by now, notifications are calling directly to the AuthenticatorActivity to update, without AccountManager intervention
        mAccountMgr.setAuthToken(mAccount, mAuthTokenType, mAuthToken);

    } else {
        response.putString(AccountManager.KEY_AUTHTOKEN, mPasswordInput.getText().toString());
        mAccountMgr.setPassword(mAccount, mPasswordInput.getText().toString());
    }
    setAccountAuthenticatorResult(response);

}

From source file:com.cerema.cloud2.authentication.AuthenticatorActivity.java

/**
 * Updates the authentication token./*from  w  ww .j  ava 2 s . c  o m*/
 *
 * Sets the proper response so that the AccountAuthenticator that started this activity
 * saves a new authorization token for mAccount.
 *
 * Kills the session kept by OwnCloudClientManager so that a new one will created with
 * the new credentials when needed.
 */
private void updateAccountAuthentication() throws AccountNotFoundException {

    Bundle response = new Bundle();
    response.putString(AccountManager.KEY_ACCOUNT_NAME, mAccount.name);
    response.putString(AccountManager.KEY_ACCOUNT_TYPE, mAccount.type);

    if (AccountTypeUtils.getAuthTokenTypeAccessToken(MainApp.getAccountType()).equals(mAuthTokenType)) {
        response.putString(AccountManager.KEY_AUTHTOKEN, mAuthToken);
        // the next line is necessary, notifications are calling directly to the 
        // AuthenticatorActivity to update, without AccountManager intervention
        mAccountMgr.setAuthToken(mAccount, mAuthTokenType, mAuthToken);

    } else if (AccountTypeUtils.getAuthTokenTypeSamlSessionCookie(MainApp.getAccountType())
            .equals(mAuthTokenType)) {

        response.putString(AccountManager.KEY_AUTHTOKEN, mAuthToken);
        // the next line is necessary; by now, notifications are calling directly to the 
        // AuthenticatorActivity to update, without AccountManager intervention
        mAccountMgr.setAuthToken(mAccount, mAuthTokenType, mAuthToken);

    } else {
        response.putString(AccountManager.KEY_AUTHTOKEN, mPasswordInput.getText().toString());
        mAccountMgr.setPassword(mAccount, mPasswordInput.getText().toString());
    }
    setAccountAuthenticatorResult(response);

}

From source file:com.owncloud.android.authentication.AuthenticatorActivity.java

/**
 * Creates a new account through the Account Authenticator that started this
 * activity.//from ww  w  . j a  v  a  2 s .com
 * 
 * This makes the account permanent.
 * 
 * TODO Decide how to name the OAuth accounts
 */
private boolean createAccount() {
    // / create and save new ownCloud account
    boolean isOAuth = AccountAuthenticator.AUTH_TOKEN_TYPE_ACCESS_TOKEN.equals(mAuthTokenType);
    boolean isSaml = AccountAuthenticator.AUTH_TOKEN_TYPE_SAML_WEB_SSO_SESSION_COOKIE.equals(mAuthTokenType);

    Uri uri = Uri.parse(mHostBaseUrl);
    String username = mUsernameInput.getText().toString().trim();
    username = username + "@" + location;

    if (isSaml) {
        username = getUserNameForSamlSso();

    } else if (isOAuth) {
        username = "OAuth_user" + (new java.util.Random(System.currentTimeMillis())).nextLong();
    }
    String accountName = username + "@" + uri.getHost();
    if (uri.getPort() >= 0) {
        accountName += ":" + uri.getPort();
    }

    mAccount = new Account(accountName, AccountAuthenticator.ACCOUNT_TYPE);
    if (AccountUtils.exists(mAccount, getApplicationContext())) {
        // fail - not a new account, but an existing one; disallow
        RemoteOperationResult result = new RemoteOperationResult(ResultCode.ACCOUNT_NOT_NEW);
        updateAuthStatusIconAndText(result);
        showAuthStatus();
        Log_OC.d(TAG, result.getLogMessage());
        return false;

    } else {

        if (isOAuth || isSaml) {
            mAccountMgr.addAccountExplicitly(mAccount, "", null); // with
                                                                  // external
                                                                  // authorizations,
                                                                  // the
                                                                  // password
                                                                  // is
                                                                  // never
                                                                  // input
                                                                  // in the
                                                                  // app
        } else {
            mAccountMgr.addAccountExplicitly(mAccount, mPasswordInput.getText().toString(), null);
        }

        // / add the new account as default in preferences, if there is none
        // already
        Account defaultAccount = AccountUtils.getCurrentOwnCloudAccount(this);
        if (defaultAccount == null) {
            SharedPreferences.Editor editor = PreferenceManager.getDefaultSharedPreferences(this).edit();
            editor.putString("select_oc_account", accountName);
            editor.commit();
        }

        // / prepare result to return to the Authenticator
        // TODO check again what the Authenticator makes with it; probably
        // has the same effect as addAccountExplicitly, but it's not well
        // done
        final Intent intent = new Intent();
        intent.putExtra(AccountManager.KEY_ACCOUNT_TYPE, AccountAuthenticator.ACCOUNT_TYPE);
        intent.putExtra(AccountManager.KEY_ACCOUNT_NAME, mAccount.name);
        /*
         * if (!isOAuth) intent.putExtra(AccountManager.KEY_AUTHTOKEN,
         * AccountAuthenticator.ACCOUNT_TYPE);
         */
        intent.putExtra(AccountManager.KEY_USERDATA, username);
        if (isOAuth || isSaml) {
            mAccountMgr.setAuthToken(mAccount, mAuthTokenType, mAuthToken);
        }
        // / add user data to the new account; TODO probably can be done in
        // the last parameter addAccountExplicitly, or in KEY_USERDATA
        mAccountMgr.setUserData(mAccount, AccountAuthenticator.KEY_OC_VERSION, mDiscoveredVersion.toString());
        mAccountMgr.setUserData(mAccount, AccountAuthenticator.KEY_OC_BASE_URL, mHostBaseUrl);
        if (isSaml) {
            mAccountMgr.setUserData(mAccount, AccountAuthenticator.KEY_SUPPORTS_SAML_WEB_SSO, "TRUE");
        } else if (isOAuth) {
            mAccountMgr.setUserData(mAccount, AccountAuthenticator.KEY_SUPPORTS_OAUTH2, "TRUE");
        }

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

        // / immediately request for the synchronization of the new account
        Bundle bundle = new Bundle();
        bundle.putBoolean(ContentResolver.SYNC_EXTRAS_MANUAL, true);
        ContentResolver.requestSync(mAccount, AccountAuthenticator.AUTHORITY, bundle);
        syncAccount();
        // Bundle bundle = new Bundle();
        // bundle.putBoolean(ContentResolver.SYNC_EXTRAS_MANUAL, true);
        // ContentResolver.requestSync(mAccount,
        // AccountAuthenticator.AUTHORITY, bundle);
        return true;
    }
}

From source file:com.digitalarx.android.authentication.AuthenticatorActivity.java

/**
 * Creates a new account through the Account Authenticator that started this activity. 
 * /*from  w ww.  jav a 2s  .c o m*/
 * This makes the account permanent.
 * 
 * TODO Decide how to name the OAuth accounts
 */
private boolean createAccount() {
    /// create and save new ownCloud account
    boolean isOAuth = AccountTypeUtils.getAuthTokenTypeAccessToken(MainApp.getAccountType())
            .equals(mAuthTokenType);
    boolean isSaml = AccountTypeUtils.getAuthTokenTypeSamlSessionCookie(MainApp.getAccountType())
            .equals(mAuthTokenType);

    Uri uri = Uri.parse(mServerInfo.mBaseUrl);
    String username = mUsernameInput.getText().toString().trim();
    if (isOAuth) {
        username = "OAuth_user" + (new java.util.Random(System.currentTimeMillis())).nextLong();
    }
    String accountName = com.owncloud.android.lib.common.accounts.AccountUtils.buildAccountName(uri, username);
    Account newAccount = new Account(accountName, MainApp.getAccountType());
    if (AccountUtils.exists(newAccount, getApplicationContext())) {
        // fail - not a new account, but an existing one; disallow
        RemoteOperationResult result = new RemoteOperationResult(ResultCode.ACCOUNT_NOT_NEW);
        updateAuthStatusIconAndText(result);
        showAuthStatus();
        Log_OC.d(TAG, result.getLogMessage());
        return false;

    } else {
        mAccount = newAccount;

        if (isOAuth || isSaml) {
            mAccountMgr.addAccountExplicitly(mAccount, "", null); // with external authorizations, the password is never input in the app
        } else {
            mAccountMgr.addAccountExplicitly(mAccount, mPasswordInput.getText().toString(), null);
        }

        /// add the new account as default in preferences, if there is none already
        Account defaultAccount = AccountUtils.getCurrentOwnCloudAccount(this);
        if (defaultAccount == null) {
            SharedPreferences.Editor editor = PreferenceManager.getDefaultSharedPreferences(this).edit();
            editor.putString("select_oc_account", accountName);
            editor.commit();
        }

        /// prepare result to return to the Authenticator
        //  TODO check again what the Authenticator makes with it; probably has the same effect as addAccountExplicitly, but it's not well done
        final Intent intent = new Intent();
        intent.putExtra(AccountManager.KEY_ACCOUNT_TYPE, MainApp.getAccountType());
        intent.putExtra(AccountManager.KEY_ACCOUNT_NAME, mAccount.name);
        /*if (!isOAuth)
        intent.putExtra(AccountManager.KEY_AUTHTOKEN,   MainApp.getAccountType()); */
        intent.putExtra(AccountManager.KEY_USERDATA, username);
        if (isOAuth || isSaml) {
            mAccountMgr.setAuthToken(mAccount, mAuthTokenType, mAuthToken);
        }
        /// add user data to the new account; TODO probably can be done in the last parameter addAccountExplicitly, or in KEY_USERDATA
        mAccountMgr.setUserData(mAccount, Constants.KEY_OC_VERSION, mServerInfo.mVersion.getVersion());
        mAccountMgr.setUserData(mAccount, Constants.KEY_OC_BASE_URL, mServerInfo.mBaseUrl);

        if (isSaml) {
            mAccountMgr.setUserData(mAccount, Constants.KEY_SUPPORTS_SAML_WEB_SSO, "TRUE");
        } else if (isOAuth) {
            mAccountMgr.setUserData(mAccount, Constants.KEY_SUPPORTS_OAUTH2, "TRUE");
        }

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

        return true;
    }
}

From source file:com.synox.android.authentication.AuthenticatorActivity.java

/**
 * Creates a new account through the Account Authenticator that started this activity. 
 * /*from   w  w w.ja v a2  s .  c  o m*/
 * This makes the account permanent.
 * 
 * TODO Decide how to name the OAuth accounts
 */
private boolean createAccount(RemoteOperationResult authResult) {
    /// create and save new ownCloud account
    boolean isOAuth = AccountTypeUtils.getAuthTokenTypeAccessToken(MainApp.getAccountType())
            .equals(mAuthTokenType);
    boolean isSaml = AccountTypeUtils.getAuthTokenTypeSamlSessionCookie(MainApp.getAccountType())
            .equals(mAuthTokenType);

    String lastPermanentLocation = authResult.getLastPermanentLocation();
    if (lastPermanentLocation != null) {
        mServerInfo.mBaseUrl = AccountUtils.trimWebdavSuffix(lastPermanentLocation);
    }

    Uri uri = Uri.parse(mServerInfo.mBaseUrl);
    String username = mUsernameInput.getText().toString().trim();
    if (isOAuth) {
        username = "OAuth_user" + (new java.util.Random(System.currentTimeMillis())).nextLong();
    }
    String accountName = com.synox.android.lib.common.accounts.AccountUtils.buildAccountName(uri, username);
    Account newAccount = new Account(accountName, MainApp.getAccountType());
    if (AccountUtils.exists(newAccount, getApplicationContext())) {
        // fail - not a new account, but an existing one; disallow
        RemoteOperationResult result = new RemoteOperationResult(ResultCode.ACCOUNT_NOT_NEW);
        updateAuthStatusIconAndText(result);
        showAuthStatus();
        Log_OC.d(TAG, result.getLogMessage());
        return false;

    } else {
        mAccount = newAccount;

        if (isOAuth || isSaml) {
            // with external authorizations, the password is never input in the app
            mAccountMgr.addAccountExplicitly(mAccount, "", null);
        } else {
            mAccountMgr.addAccountExplicitly(mAccount, mPasswordInput.getText().toString(), null);
        }

        // include account version with the new account
        mAccountMgr.setUserData(mAccount, Constants.KEY_OC_ACCOUNT_VERSION,
                Integer.toString(AccountUtils.ACCOUNT_VERSION));

        /// add the new account as default in preferences, if there is none already
        Account defaultAccount = AccountUtils.getCurrentOwnCloudAccount(this);
        if (defaultAccount == null) {
            SharedPreferences.Editor editor = PreferenceManager.getDefaultSharedPreferences(this).edit();
            editor.putString("select_oc_account", accountName);
            editor.commit();
        }

        /// prepare result to return to the Authenticator
        //  TODO check again what the Authenticator makes with it; probably has the same 
        //  effect as addAccountExplicitly, but it's not well done
        final Intent intent = new Intent();
        intent.putExtra(AccountManager.KEY_ACCOUNT_TYPE, MainApp.getAccountType());
        intent.putExtra(AccountManager.KEY_ACCOUNT_NAME, mAccount.name);
        intent.putExtra(AccountManager.KEY_USERDATA, username);
        if (isOAuth || isSaml) {
            mAccountMgr.setAuthToken(mAccount, mAuthTokenType, mAuthToken);
        }
        /// add user data to the new account; TODO probably can be done in the last parameter 
        //      addAccountExplicitly, or in KEY_USERDATA
        mAccountMgr.setUserData(mAccount, Constants.KEY_OC_VERSION, mServerInfo.mVersion.getVersion());
        mAccountMgr.setUserData(mAccount, Constants.KEY_OC_BASE_URL, mServerInfo.mBaseUrl);

        if (isSaml) {
            mAccountMgr.setUserData(mAccount, Constants.KEY_SUPPORTS_SAML_WEB_SSO, "TRUE");
        } else if (isOAuth) {
            mAccountMgr.setUserData(mAccount, Constants.KEY_SUPPORTS_OAUTH2, "TRUE");
        }

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

        return true;
    }
}