Example usage for android.accounts Account Account

List of usage examples for android.accounts Account Account

Introduction

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

Prototype

public Account(@NonNull Account other, @NonNull String accessId) 

Source Link

Usage

From source file:org.pixmob.feedme.ui.EntriesFragment.java

private void authenticateAccount(String accountName) {
    Log.i(TAG, "Authenticating account: " + accountName);

    final Activity a = getActivity();
    final AccountManager am = (AccountManager) a.getSystemService(Context.ACCOUNT_SERVICE);
    final Account account = new Account(accountName, GOOGLE_ACCOUNT);
    am.getAuthToken(account, "reader", null, a, new AccountManagerCallback<Bundle>() {
        @Override//  w w  w  .  ja v a  2 s. com
        public void run(AccountManagerFuture<Bundle> resultContainer) {
            String authToken = null;
            final Bundle result;
            try {
                result = resultContainer.getResult();
                authToken = result.getString(AccountManager.KEY_AUTHTOKEN);
            } catch (IOException e) {
                Log.w(TAG, "I/O error while authenticating account " + account.name, e);
            } catch (OperationCanceledException e) {
                Log.w(TAG, "Authentication was canceled for account " + account.name, e);
            } catch (AuthenticatorException e) {
                Log.w(TAG, "Authentication failed for account " + account.name, e);
            }

            if (authToken == null) {
                Toast.makeText(a, a.getString(R.string.authentication_failed), Toast.LENGTH_SHORT).show();
            } else {
                Log.i(TAG, "Authentication done");
                onAuthenticationDone(account.name, authToken);
            }
        }
    }, null);
}

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.
 * //from   w w  w. j av  a 2  s  . com
 * @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:com.rukman.emde.smsgroups.authenticator.GMSAuthenticatorActivity.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.
 *
 * @param result the confirmCredentials result.
 *///  www  .j ava  2s  .  c  o m
private void finishLogin(String authToken) {

    Log.i(TAG, "finishLogin()");
    final Account account = new Account(mUsername, GMSApplication.ACCOUNT_TYPE);
    if (mIsUnknownAccountName) {
        mAccountManager.addAccountExplicitly(account, mPassword, null);
        // Set contacts sync for this account.
        ContentResolver.setIsSyncable(account, GMSProvider.AUTHORITY, 1);
        ContentResolver.setSyncAutomatically(account, GMSProvider.AUTHORITY, true);
    } else {
        mAccountManager.setPassword(account, mPassword);
    }
    final Intent intent = new Intent();
    intent.putExtra(AccountManager.KEY_ACCOUNT_NAME, mUsername);
    intent.putExtra(AccountManager.KEY_ACCOUNT_TYPE, GMSApplication.ACCOUNT_TYPE);
    setAccountAuthenticatorResult(intent.getExtras());
    setResult(RESULT_OK, intent);
    finish();
}

From source file:edu.mit.mobile.android.locast.accounts.Authenticator.java

/**
 * Adds an account that acts as a placeholder to allow the sync to work properly. The sync
 * framework always requires an account.
 *
 * @param context// w  ww  .  j  a  v  a 2s.co m
 */
public static void addDemoAccount(Context context) {
    final Account[] accounts = Authenticator.getAccounts(context);

    if (accounts.length > 0) {
        // if there's already a demo account, we don't want to add another.
        // if there isn't, we're not going to delete the actual account.
        return;
    }
    final AccountManager am = AccountManager.get(context);
    final Account account = new Account(DEMO_ACCOUNT, AuthenticationService.ACCOUNT_TYPE);
    am.addAccountExplicitly(account, null, null);

    ContentResolver.setSyncAutomatically(account, MediaProvider.AUTHORITY, true);
}

From source file:org.klnusbaum.udj.auth.AuthActivity.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.
 *
 * @param result the confirmCredentials result.
 *///from   w  w  w. j a va2  s  . c  o m
private void finishLogin(ServerConnection.AuthResult authResult) {
    Log.i(TAG, "finishLogin()");
    final Account account = new Account(mUsername, Constants.ACCOUNT_TYPE);
    if (mRequestNewAccount) {
        mAccountManager.addAccountExplicitly(account, mPassword, null);
        ContentResolver.setIsSyncable(account, Constants.AUTHORITY, 0);
    } else {
        mAccountManager.setPassword(account, mPassword);
    }
    mAccountManager.setUserData(account, Constants.USER_ID_DATA, authResult.userId);
    mAccountManager.setUserData(account, Constants.LAST_PLAYER_ID_DATA, Constants.NO_PLAYER_ID);
    mAccountManager.setUserData(account, Constants.PLAYER_STATE_DATA,
            Integer.toString(Constants.NOT_IN_PLAYER));
    final Intent intent = new Intent();
    intent.putExtra(AccountManager.KEY_ACCOUNT_NAME, mUsername);
    intent.putExtra(AccountManager.KEY_ACCOUNT_TYPE, Constants.ACCOUNT_TYPE);
    intent.putExtra(Constants.ACCOUNT_EXTRA, account);
    setAccountAuthenticatorResult(intent.getExtras());
    setResult(RESULT_OK, intent);
    finish();
}

From source file:eu.trentorise.smartcampus.ac.authenticator.AMSCAccessProvider.java

@Override
public String promote(final Activity activity, String inAuthority, final String token) {
    final String authority = inAuthority == null ? Constants.AUTHORITY_DEFAULT : inAuthority;
    final AccountManager am = AccountManager.get(activity);
    //      Bundle options = new Bundle();
    //      if (token != null) {
    //         options.putString(Constants.PROMOTION_TOKEN, token);
    //      }/*from ww w.j  ava2  s.c om*/
    final Account a = new Account(Constants.getAccountName(activity), Constants.getAccountType(activity));
    final String userDataString = am.getUserData(a, AccountManager.KEY_USERDATA);

    invalidateToken(activity, authority);

    am.getAuthToken(new Account(Constants.getAccountName(activity), Constants.getAccountType(activity)),
            authority, null, null, new AccountManagerCallback<Bundle>() {
                @Override
                public void run(AccountManagerFuture<Bundle> result) {
                    Bundle bundle = null;
                    try {
                        bundle = result.getResult();
                        Intent launch = (Intent) bundle.get(AccountManager.KEY_INTENT);
                        if (launch != null) {
                            launch.putExtra(Constants.KEY_AUTHORITY, authority);
                            launch.putExtra(Constants.PROMOTION_TOKEN, token);
                            launch.putExtra(Constants.OLD_DATA, userDataString);
                            activity.startActivityForResult(launch, SC_AUTH_ACTIVITY_REQUEST_CODE);
                        } else if (bundle.getString(AccountManager.KEY_AUTHTOKEN) != null) {
                            //                         am.setAuthToken(a, authority, bundle.getString(AccountManager.KEY_AUTHTOKEN));
                            //                         am.addAccountExplicitly(a, null, null);
                            // no token acquired
                        } else {
                            storeAnonymousToken(token, authority, am, a);
                        }
                    } catch (Exception e) {
                        // revert the invalidated token
                        storeAnonymousToken(token, authority, am, a);
                        return;
                    }
                }
            }, null);
    return null;
}

From source file:sk.mpage.androidsample.drawerwithauthenticator.MainActivity.java

private void getTokenForAccountCreateIfNeeded(String accountType, String authTokenType) {
    final AccountManagerFuture<Bundle> future = mAccountManager.getAuthTokenByFeatures(accountType,
            authTokenType, null, this, null, null, new AccountManagerCallback<Bundle>() {
                @Override/*  w ww  .  ja  v  a 2s  .c  o  m*/
                public void run(AccountManagerFuture<Bundle> future) {
                    Bundle bnd = null;
                    try {
                        bnd = future.getResult();
                        authToken = bnd.getString(AccountManager.KEY_AUTHTOKEN);
                        if (authToken != null) {
                            String accountName = bnd.getString(AccountManager.KEY_ACCOUNT_NAME);
                            mConnectedAccount = new Account(accountName, AccountGeneral.ACCOUNT_TYPE);
                            //callback after connected
                            setAppUIForUser();
                        } else {
                            getTokenForAccountCreateIfNeeded(AccountGeneral.ACCOUNT_TYPE,
                                    AccountGeneral.AUTHTOKEN_TYPE_FULL_ACCESS);
                        }

                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }, null);
}

From source file:com.beesham.popularmovies.sync.MoviesSyncAdapter.java

private static Account getSyncAccount(Context context) {
    AccountManager accountManager = (AccountManager) context.getSystemService(Context.ACCOUNT_SERVICE);

    Account newAccount = new Account(context.getString(R.string.app_name),
            context.getString(R.string.sync_account_type));

    if (accountManager.getPassword(newAccount) == null) {
        if (!accountManager.addAccountExplicitly(newAccount, "", null)) {
            return null;
        }/*from  w w w  .j  a va 2 s .  c  o m*/
        onAccountCreated(newAccount, context);
    }
    return newAccount;
}

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 w w  w  . j av a2  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:p1.nd.khan.jubair.mohammadd.popularmovies.sync.MovieSyncAdapter.java

/**
 * 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.//from  w w w.ja v a 2 s .  c om
 */
public static Account getSyncAccount(Context context) {
    AccountManager accountManager = (AccountManager) context.getSystemService(Context.ACCOUNT_SERVICE);
    Account newAccount = new Account(context.getString(R.string.app_name),
            context.getString(R.string.sync_account_type));
    if (null == accountManager.getPassword(newAccount)) {
        if (!accountManager.addAccountExplicitly(newAccount, "", null)) {
            return null;
        }
        onAccountCreated(newAccount, context);
    }
    return newAccount;
}