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:com.androidexperiments.sprayscape.unitydriveplugin.GoogleDriveUnityPlayerActivity.java

@Override
protected void onActivityResult(final int requestCode, final int resultCode, final Intent data) {
    Log.i(TAG, "onActivityResult(" + requestCode + ", " + resultCode + ", " + data + ")");
    UnityPlayer.UnitySendMessage("OnActivityResultListener", "OnActivityResult",
            requestCode + "," + resultCode + "," + data);
    switch (requestCode) {
    case REQUEST_CODE_ACCOUNT_SELECTED: {
        if (resultCode == RESULT_OK) {
            final String accountName = data.getStringExtra(AccountManager.KEY_ACCOUNT_NAME);
            String accountType = data.getStringExtra(AccountManager.KEY_ACCOUNT_TYPE);
            SharedPreferences prefs = getPreferences(MODE_PRIVATE);

            final SharedPreferences.Editor e = prefs.edit();
            e.putString(GOOGLE_ACCOUNT_NAME, accountName);
            e.apply();/*  w w w  .  j a v a 2 s .  c  o m*/

            Log.i(TAG, "user selected account: " + accountName + " type: " + accountType
                    + " saved to shared preferences");
            account = new Account(accountName, accountType);
            // TODO: maybe don't assume the user was trying to upload?
            // try uploading again
            //uploadFile(lastDriveFolderName, lastDriveFileName, lastLocalPath, lastCallbackObjectName);

            driveService = initDriveServiceFromAccount(account, lastCallbackObjectName);

        } else {
            // user cancel the account picker without selecting....
            UnityPlayer.UnitySendMessage(lastCallbackObjectName,
                    CALLBACK_METHOD_DRIVE_ACCOUNT_SELECTION_CANCELED, "" + resultCode);
        }
        break;
    }
    case REQUEST_CODE_RECOVER_FROM_TOKEN_AUTHENTICATE: {
        //                if(resultCode == RESULT_OK){
        fetchAuthToken(lastCallbackObjectName);
        //                } else {
        //                    clearAccount();
        //                    UnityPlayer.UnitySendMessage(lastCallbackObjectName, CALLBACK_METHOD_DRIVE_AUTH_CANCELED, "" + resultCode);
        //                }
        break;
    }
    case REQUEST_CODE_RECOVER_FROM_DRIVE_UPLOAD_ERROR: {
        if (resultCode == RESULT_OK) {
            // user fixed the authentication problem try upload again
            uploadFile(lastDriveFolderName, lastDriveFileName, lastLocalPath, lastCallbackObjectName);
        } else {
            // this happens when the user deny's the authorization
            // we will clear the auth data in-case they wanted to switch accounts on the next try
            clearAccount();
            UnityPlayer.UnitySendMessage(lastCallbackObjectName, CALLBACK_METHOD_DRIVE_AUTH_CANCELED,
                    "" + resultCode);
        }
        break;
    }
    default:
        super.onActivityResult(requestCode, resultCode, data);
    }
}

From source file:com.he5ed.lib.cloudprovider.auth.OAuth2Fragment.java

/**
 * Create a new user account or update the current user account
 *
 * @param user user information returned from server
 *///from  ww w .j a  v  a 2 s . c o  m
private void addAccount(User user) {
    boolean accountExist = false;
    AccountManager am = AccountManager.get(getActivity());
    // check if account already exist in AccountManager
    Account[] accounts = am.getAccountsByType(CloudProvider.ACCOUNT_TYPE);
    for (Account account : accounts) {
        if (account.name.equals(user.id)) {
            accountExist = true;
            break;
        }
    }

    Account account = new Account(user.id, CloudProvider.ACCOUNT_TYPE);
    Bundle userData = new Bundle(); // must be string value
    String accessToken = mTokenInfo.get(Authenticator.KEY_ACCESS_TOKEN);
    String refreshToken = mTokenInfo.get(Authenticator.KEY_REFRESH_TOKEN);
    String expiryDuration = mTokenInfo.get(Authenticator.KEY_EXPIRY);
    if (accountExist) {
        // update current account access token
        am.setAuthToken(account, CloudProvider.AUTH_TYPE, accessToken);
        if (refreshToken != null)
            am.setUserData(account, Authenticator.KEY_REFRESH_TOKEN, refreshToken);
        if (expiryDuration != null)
            am.setUserData(account, Authenticator.KEY_EXPIRY, expiryDuration);
    } else {
        // add new account into AccountManager
        if (refreshToken != null)
            userData.putString(Authenticator.KEY_REFRESH_TOKEN, refreshToken);
        if (expiryDuration != null)
            userData.putString(Authenticator.KEY_EXPIRY, expiryDuration);
        userData.putString(Authenticator.KEY_CLOUD_API, AuthHelper.getCloudApi(mCloudApi));
        userData.putString(Authenticator.KEY_USERNAME, user.name);
        userData.putString(Authenticator.KEY_EMAIL, user.email);
        userData.putString(Authenticator.KEY_AVATAR_URL, user.avatarUrl);

        am.addAccountExplicitly(account, null, userData);
        am.setAuthToken(account, CloudProvider.AUTH_TYPE, accessToken);
    }

    // send result back to AccountManager
    Bundle result = new Bundle();
    result.putString(AccountManager.KEY_ACCOUNT_NAME, user.id);
    result.putString(AccountManager.KEY_ACCOUNT_TYPE, CloudProvider.ACCOUNT_TYPE);
    ((AccountAuthenticatorActivity) getActivity()).setAccountAuthenticatorResult(result);

    getActivity().finish();
}

From source file:org.amahi.anywhere.activity.AuthenticationActivity.java

private void finishAuthentication(String authenticationToken) {
    AccountManager accountManager = AccountManager.get(this);

    Bundle authenticationBundle = new Bundle();

    Account account = new AmahiAccount(getUsername());

    if (accountManager.addAccountExplicitly(account, getPassword(), null)) {
        authenticationBundle.putString(AccountManager.KEY_ACCOUNT_NAME, account.name);
        authenticationBundle.putString(AccountManager.KEY_ACCOUNT_TYPE, account.type);
        authenticationBundle.putString(AccountManager.KEY_AUTHTOKEN, authenticationToken);

        accountManager.setAuthToken(account, account.type, authenticationToken);
    }/*ww  w  .  j a  v  a 2  s . c  om*/

    setAccountAuthenticatorResult(authenticationBundle);

    setResult(Activity.RESULT_OK);

    finish();
}

From source file:com.nbos.phonebook.sync.authenticator.AuthenticatorActivity.java

/**
 * //w  w  w . ja  v  a 2s. com
 * 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.
 * 
 * @param the confirmCredentials result.
 */

protected void finishLogin() {
    Log.i(tag, "finishLogin()");
    final Account account = new Account(mUsername, Constants.ACCOUNT_TYPE);

    if (mRequestNewAccount) {
        mAccountManager.addAccountExplicitly(account, mPassword, null);
        mAccountManager.setUserData(account, Constants.PHONE_NUMBER_KEY, countryCode + mPhone);
        // Set contacts sync for this account.
        ContentResolver.setSyncAutomatically(account, ContactsContract.AUTHORITY, true);
    } else {
        mAccountManager.setPassword(account, mPassword);
    }
    final Intent intent = new Intent();
    mAuthtoken = mPassword;
    intent.putExtra(AccountManager.KEY_ACCOUNT_NAME, mUsername);
    intent.putExtra(AccountManager.KEY_ACCOUNT_TYPE, Constants.ACCOUNT_TYPE);
    if (mAuthtokenType != null && mAuthtokenType.equals(Constants.AUTHTOKEN_TYPE))
        intent.putExtra(AccountManager.KEY_AUTHTOKEN, mAuthtoken);
    Db.deleteServerData(getApplicationContext());
    setAccountAuthenticatorResult(intent.getExtras());
    setResult(RESULT_OK, intent);
    finish();
}

From source file:pt.up.mobile.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. We store the
 * authToken that's returned from the server as the 'password' for this
 * account - so we're never storing the user's actual password locally.
 * //ww w.  ja va 2s  .c  o  m
 * @param result
 *            the confirmCredentials result.
 */
@TargetApi(8)
private void finishLogin(final User user) {

    Log.i(TAG, "finishLogin()");
    new Thread(new Runnable() {
        @Override
        public void run() {
            final Account account = new Account(mUsername, Constants.ACCOUNT_TYPE);
            if (mRequestNewAccount) {
                final ContentValues values = new ContentValues();
                values.put(SigarraContract.Users.CODE, user.getUserCode());
                values.put(SigarraContract.Users.TYPE, user.getType());
                values.put(SigarraContract.Users.ID, account.name);
                getContentResolver().insert(SigarraContract.Users.CONTENT_URI, values);
                // Set contacts sync for this account.

                if (!mAccountManager.addAccountExplicitly(account, mPassword, Bundle.EMPTY)) {
                    getContentResolver().delete(SigarraContract.Users.CONTENT_URI,
                            SigarraContract.Users.PROFILE,
                            SigarraContract.Users.getUserSelectionArgs(account.name));
                    finish();
                }
                String syncIntervalValue = PreferenceManager
                        .getDefaultSharedPreferences(getApplicationContext())
                        .getString(getString(R.string.key_sync_interval),
                                Integer.toString(getResources().getInteger(R.integer.default_sync_interval)));

                String syncNotIntervalValue = PreferenceManager
                        .getDefaultSharedPreferences(getApplicationContext())
                        .getString(getString(R.string.key_notifications_sync_interval),
                                Integer.toString(getResources().getInteger(R.integer.default_sync_interval)));

                ContentResolver.setSyncAutomatically(account, SigarraContract.CONTENT_AUTHORITY, true);
                ContentResolver.setSyncAutomatically(account, ContactsContract.AUTHORITY, true);
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.FROYO) {
                    ContentResolver.addPeriodicSync(account, SigarraContract.CONTENT_AUTHORITY, Bundle.EMPTY,
                            Integer.parseInt(syncIntervalValue) * 3600);
                    ContentResolver.addPeriodicSync(account, SigarraContract.CONTENT_AUTHORITY,
                            SigarraSyncAdapterUtils.getNotificationsPeriodicBundle(),
                            Integer.parseInt(syncNotIntervalValue) * 3600);
                } else {
                    PeriodicSyncReceiver.cancelPreviousAlarms(getApplicationContext(), account,
                            SigarraContract.CONTENT_AUTHORITY, Bundle.EMPTY);
                    PeriodicSyncReceiver.addPeriodicSync(getApplicationContext(), account,
                            SigarraContract.CONTENT_AUTHORITY, Bundle.EMPTY,
                            Integer.parseInt(syncIntervalValue) * 3600);

                    PeriodicSyncReceiver.addPeriodicSync(getApplicationContext(), account,
                            SigarraContract.CONTENT_AUTHORITY, SigarraSyncAdapterUtils.getNotificationsBundle(),
                            Integer.parseInt(syncNotIntervalValue) * 3600);
                }
            } else {
                mAccountManager.setPassword(account, user.getPassword());
            }
            final Intent intent = new Intent();
            intent.putExtra(AccountManager.KEY_ACCOUNT_NAME, mUsername);
            intent.putExtra(AccountManager.KEY_ACCOUNT_TYPE, Constants.ACCOUNT_TYPE);
            setAccountAuthenticatorResult(intent.getExtras());
            setResult(RESULT_OK, intent);
            finish();
        }
    }).start();
}

From source file:edu.mit.mobile.android.locast.accounts.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.
 *
 * @param userData// ww  w .j  a v a2s.c om
 *            TODO
 * @param the
 *            confirmCredentials result.
 */

protected void finishLogin(Bundle userData) {
    Log.i(TAG, "finishLogin()");
    // ensure that there isn't a demo account sticking around.

    // TODO this is NOT the place where this code belongs. Find it a better home
    if (Authenticator.isDemoMode(this)) {
        Log.d(TAG, "cleaning up demo mode account...");
        ContentResolver.cancelSync(Authenticator.getFirstAccount(this), MediaProvider.AUTHORITY);

        mAccountManager.removeAccount(
                new Account(Authenticator.DEMO_ACCOUNT, AuthenticationService.ACCOUNT_TYPE),
                new AccountManagerCallback<Boolean>() {

                    @Override
                    public void run(AccountManagerFuture<Boolean> arg0) {
                        try {
                            if (arg0.getResult()) {

                                final ContentValues cv = new ContentValues();
                                // invalidate all the content to force a sync.
                                // this is to ensure that items which were marked favorite get set as
                                // such.
                                cv.put(Cast._SERVER_MODIFIED_DATE, 0);
                                cv.put(Cast._MODIFIED_DATE, 0);
                                getContentResolver().update(Cast.CONTENT_URI, cv, null, null);
                                if (Constants.DEBUG) {
                                    Log.d(TAG, "reset all cast modified dates to force a reload");
                                }
                            }
                        } catch (final OperationCanceledException e) {
                            // TODO Auto-generated catch block
                            e.printStackTrace();
                        } catch (final AuthenticatorException e) {
                            // TODO Auto-generated catch block
                            e.printStackTrace();
                        } catch (final IOException e) {
                            // TODO Auto-generated catch block
                            e.printStackTrace();
                        }
                    }
                }, null);

    }
    final Account account = new Account(mUsername, AuthenticationService.ACCOUNT_TYPE);

    if (mRequestNewAccount) {
        mAccountManager.addAccountExplicitly(account, mPassword, userData);
        // Automatically enable sync for this account
        ContentResolver.setSyncAutomatically(account, MediaProvider.AUTHORITY, true);
    } else {
        mAccountManager.setPassword(account, mPassword);
    }
    final Intent intent = new Intent();
    mAuthtoken = mPassword;
    intent.putExtra(AccountManager.KEY_ACCOUNT_NAME, mUsername);
    intent.putExtra(AccountManager.KEY_ACCOUNT_TYPE, AuthenticationService.ACCOUNT_TYPE);
    if (mAuthtokenType != null && mAuthtokenType.equals(AuthenticationService.AUTHTOKEN_TYPE)) {
        intent.putExtra(AccountManager.KEY_AUTHTOKEN, mAuthtoken);
    }
    setAccountAuthenticatorResult(intent.getExtras());
    setResult(RESULT_OK, intent);
    finish();
}

From source file:edu.mit.mobile.android.locast.accounts.AbsLocastAuthenticatorActivity.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.
 *
 * @param userData//  w  w w  .  j  ava 2s  . c  o m
 *            TODO
 * @param the
 *            confirmCredentials result.
 */

protected void finishLogin(Bundle userData) {
    if (BuildConfig.DEBUG) {
        Log.i(TAG, "finishLogin()");
    }

    final Account account = createAccount(mUsername);

    if (mRequestNewAccount) {
        mAccountManager.addAccountExplicitly(account, mPassword, userData);
        // Automatically enable sync for this account
        ContentResolver.setSyncAutomatically(account, getAuthority(), true);
    } else {
        mAccountManager.setPassword(account, mPassword);
    }
    final Intent intent = new Intent();
    mAuthtoken = mPassword;
    intent.putExtra(AccountManager.KEY_ACCOUNT_NAME, mUsername);
    intent.putExtra(AccountManager.KEY_ACCOUNT_TYPE, getAccountType());
    if (mAuthtokenType != null && mAuthtokenType.equals(getAuthtokenType())) {
        intent.putExtra(AccountManager.KEY_AUTHTOKEN, mAuthtoken);
    }
    setAccountAuthenticatorResult(intent.getExtras());
    setResult(RESULT_OK, intent);
    finish();
}

From source file:com.clearcenter.mobile_demo.mdAuthenticatorActivity.java

private void finishLogin(String authToken) {
    Log.i(TAG, "finishLogin()");

    final Account account = new Account(nickname, mdConstants.ACCOUNT_TYPE);
    if (request_new_account) {
        account_manager.addAccountExplicitly(account, authToken, null);
        account_manager.setUserData(account, "hostname", hostname);
        account_manager.setUserData(account, "username", username);

        // Set system info sync for this account.
        final Bundle extras = new Bundle();
        ContentResolver.setSyncAutomatically(account, mdContentProvider.AUTHORITY, true);
        if (android.os.Build.VERSION.SDK_INT >= 8) {
            ContentResolver.addPeriodicSync(account, mdContentProvider.AUTHORITY, extras, 10);
        }/*from  w  w  w .  j av  a  2 s.  co  m*/
    } else
        account_manager.setPassword(account, authToken);

    final Intent intent = new Intent();
    intent.putExtra(AccountManager.KEY_ACCOUNT_NAME, nickname);
    intent.putExtra(AccountManager.KEY_ACCOUNT_TYPE, mdConstants.ACCOUNT_TYPE);
    setAccountAuthenticatorResult(intent.getExtras());
    setResult(RESULT_OK, intent);

    ContentResolver.requestSync(account, mdContentProvider.AUTHORITY, new Bundle());

    finish();
}

From source file:org.xwiki.android.authenticator.auth.AuthenticatorActivity.java

public void finishLogin(Intent intent) {
    Log.d(TAG, "> finishLogin");

    //before add new account, clear old account data.
    clearOldAccount();//from w  w w  .  ja v  a  2s.co  m

    //get values
    String accountName = intent.getStringExtra(AccountManager.KEY_ACCOUNT_NAME);
    String accountPassword = intent.getStringExtra(PARAM_USER_PASS);
    String accountServer = intent.getStringExtra(PARAM_USER_SERVER);

    // Creating the account on the device and setting the auth token we got
    // (Not setting the auth token will cause another call to the server to authenticate the user)
    Log.d(TAG, "finishLogin > addAccountExplicitly" + " "
            + intent.getStringExtra(AccountManager.KEY_ACCOUNT_TYPE));
    final Account account = new Account(accountName, Constants.ACCOUNT_TYPE);
    mAccountManager.addAccountExplicitly(account, accountPassword, null);
    mAccountManager.setUserData(account, AccountManager.KEY_USERDATA, accountName);
    mAccountManager.setUserData(account, AccountManager.KEY_PASSWORD, accountPassword);
    mAccountManager.setUserData(account, AuthenticatorActivity.PARAM_USER_SERVER, accountServer);

    //grant permission if adding user from the third-party app (UID,PackageName);
    String packaName = getIntent().getStringExtra(PARAM_APP_PACKAGENAME);
    int uid = getIntent().getIntExtra(PARAM_APP_UID, 0);
    Log.d(TAG, packaName + ", " + getPackageName());
    //only if adding account from the third-party apps exclude android.uid.system, this will execute to grant permission and set token
    if (!packaName.contains("android.uid.system")) {
        AppContext.addAuthorizedApp(uid, packaName);
        String authToken = intent.getStringExtra(AccountManager.KEY_AUTHTOKEN);
        if (!TextUtils.isEmpty(authToken)) {
            String authTokenType = getIntent().getStringExtra(KEY_AUTH_TOKEN_TYPE);
            mAccountManager.setAuthToken(account, authTokenType, authToken);
        }
    }

    //return value to AccountManager
    Intent intentReturn = new Intent();
    intentReturn.putExtra(AccountManager.KEY_ACCOUNT_TYPE, Constants.ACCOUNT_TYPE);
    intentReturn.putExtra(AccountManager.KEY_ACCOUNT_NAME, accountName);
    setAccountAuthenticatorResult(intentReturn.getExtras());
    setResult(RESULT_OK, intentReturn);
    Log.d(TAG, ">" + "finish return");
    // in SettingSyncViewFlipper this activity finish;
}

From source file:com.sharpcart.android.wizardpager.SharpCartLoginActivity.java

private void createAccount(final String mUsername, final String mPassword) {
    final Account account = new Account(mUsername, PARAM_ACCOUNT_TYPE);

    if (mRequestNewAccount) {
        mAccountManager.addAccountExplicitly(account, mPassword, null);

        /*//from  w  w w .ja  va 2s.c  om
         * Turn on periodic syncing. I need to add randomness to the sync interval to make sure 
         * that not all users sync at the same time, which will overload the server.
         */

        final Bundle extras = new Bundle();
        final long random = (long) (Math.random() * 1000L);

        ContentResolver.addPeriodicSync(account, SharpCartContentProvider.AUTHORITY, extras,
                (8 * SYNC_INTERVAL) + random);

        //Will run the syncadapter everytime we get a network tinkle
        //ContentResolver.setSyncAutomatically(account,SharpCartContentProvider.AUTHORITY, true);

        //initiate a sync
        SharpCartUtilities.getInstance().syncFromServer(account);

    } else {
        mAccountManager.setPassword(account, mPassword);
    }

    final Intent intent = new Intent();
    intent.putExtra(AccountManager.KEY_ACCOUNT_NAME, mUsername);
    intent.putExtra(AccountManager.KEY_ACCOUNT_TYPE, PARAM_ACCOUNT_TYPE);

    if (mAuthTokenType != null && mAuthTokenType.equals(PARAM_AUTHTOKEN_TYPE)) {
        intent.putExtra(AccountManager.KEY_AUTHTOKEN, mAuthToken);
    }

    setResult(RESULT_OK, intent);

    finish();
}