Example usage for android.accounts AccountManager KEY_AUTHTOKEN

List of usage examples for android.accounts AccountManager KEY_AUTHTOKEN

Introduction

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

Prototype

String KEY_AUTHTOKEN

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

Click Source Link

Document

Bundle key used for the auth token value in results from #getAuthToken and friends.

Usage

From source file:com.num.mobiperf.AccountSelector.java

private void getAuthToken(AccountManagerFuture<Bundle> result) {
    //Logger.i("getAuthToken() called, result " + result);
    String errMsg = "Failed to get login cookie. ";
    Bundle bundle;//from   www  . j  a  va2 s. c o m
    try {
        bundle = result.getResult();
        Intent intent = (Intent) bundle.get(AccountManager.KEY_INTENT);
        if (intent != null) {
            // User input required. (A UI will pop up for user's consent to allow
            // this app access account information.)
            //Logger.i("Starting account manager activity");
            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            context.startActivity(intent);
        } else {
            //Logger.i("Executing getCookie task");
            synchronized (this) {
                this.authToken = bundle.getString(AccountManager.KEY_AUTHTOKEN);
                this.checkinFuture = checkinExecutor.submit(new GetCookieTask());
            }
        }
    } catch (OperationCanceledException e) {
        //Logger.e(errMsg, e);
        throw new RuntimeException("Can't get login cookie", e);
    } catch (AuthenticatorException e) {
        //Logger.e(errMsg, e);
        throw new RuntimeException("Can't get login cookie", e);
    } catch (IOException e) {
        //Logger.e(errMsg, e);
        throw new RuntimeException("Can't get login cookie", e);
    }
}

From source file:com.mobilyzer.AccountSelector.java

private void getAuthToken(AccountManagerFuture<Bundle> result) {
    Logger.i("getAuthToken() called, result " + result);
    String errMsg = "Failed to get login cookie. ";
    Bundle bundle;/*from   w  w w .  j a v a2 s . com*/
    try {
        bundle = result.getResult();
        Intent intent = (Intent) bundle.get(AccountManager.KEY_INTENT);
        if (intent != null) {
            // User input required. (A UI will pop up for user's consent to allow
            // this app access account information.)
            Logger.i("Starting account manager activity");
            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);
            context.startActivity(intent);
        } else {
            Logger.i("Executing getCookie task");
            synchronized (this) {
                this.authToken = bundle.getString(AccountManager.KEY_AUTHTOKEN);
                this.checkinFuture = checkinExecutor.submit(new GetCookieTask());
            }
        }
    } catch (OperationCanceledException e) {
        Logger.e(errMsg, e);
        throw new RuntimeException("Can't get login cookie", e);
    } catch (AuthenticatorException e) {
        Logger.e(errMsg, e);
        throw new RuntimeException("Can't get login cookie", e);
    } catch (IOException e) {
        Logger.e(errMsg, e);
        throw new RuntimeException("Can't get login cookie", e);
    }
}

From source file:de.unclenet.dehabewe.CalendarActivity.java

private void gotAccount(final AccountManager manager, final Account account) {
    SharedPreferences settings = getSharedPreferences(PREF, 0);
    SharedPreferences.Editor editor = settings.edit();
    editor.putString("accountName", account.name);
    editor.commit();/*w ww .  ja  va2 s .c  om*/
    new Thread() {

        @Override
        public void run() {
            try {
                final Bundle bundle = manager.getAuthToken(account, AUTH_TOKEN_TYPE, true, null, null)
                        .getResult();
                runOnUiThread(new Runnable() {

                    public void run() {
                        try {
                            if (bundle.containsKey(AccountManager.KEY_INTENT)) {
                                Intent intent = bundle.getParcelable(AccountManager.KEY_INTENT);
                                int flags = intent.getFlags();
                                flags &= ~Intent.FLAG_ACTIVITY_NEW_TASK;
                                intent.setFlags(flags);
                                startActivityForResult(intent, REQUEST_AUTHENTICATE);
                            } else if (bundle.containsKey(AccountManager.KEY_AUTHTOKEN)) {
                                authenticatedClientLogin(bundle.getString(AccountManager.KEY_AUTHTOKEN));
                            }
                        } catch (Exception e) {
                            handleException(e);
                        }
                    }
                });
            } catch (Exception e) {
                handleException(e);
            }
        }
    }.start();
}

From source file:net.xisberto.phonetodesktop.GoogleTasksActivity.java

/**
 * Gets a auth token from Google services for Google Tasks service. May
 * launch a new Activity to ask the user for permission. Stores the account
 * name and the auth token in preferences and executes callback.run().
 * // w w w  .j a  v a 2 s.c om
 * @param account
 *            the Account to ask the auth token.
 * @param callback
 *            {@link GoogleTasksCallback} object whose run method will be
 *            executed when the new auth token is obtained.
 */
private void getAuthToken(final Account account, final GoogleTasksCallback callback) {
    AccountManagerCallback<Bundle> ac_callback = new AccountManagerCallback<Bundle>() {
        public void run(AccountManagerFuture<Bundle> future) {
            try {
                Bundle bundle = future.getResult();
                // Here we got the auth token! Saving accountname and
                // authtoken
                String new_auth_token = bundle.getString(AccountManager.KEY_AUTHTOKEN);
                //saveAccountName(bundle.getString(AccountManager.KEY_ACCOUNT_NAME));
                saveAuthToken(new_auth_token);
                credential.setAccessToken(new_auth_token);
                log("Token obtained: " + new_auth_token);
                // And executing the callback function
                callback.run();
            } catch (OperationCanceledException canceledException) {
                // User has canceled operation
                broadcastUpdatingStatus(ACTION_AUTHENTICATE, false);
            } catch (SocketTimeoutException e) {
                broadcastUpdatingStatus(ACTION_AUTHENTICATE, false);
                log("Timeout");
                dismissNotification(NOTIFICATION_SENDING);
                showNotification(NOTIFICATION_TIMEOUT);
            } catch (IOException e) {
                if (e instanceof GoogleJsonResponseException) {
                    log("Got an GoogleJson exception");
                    if (handleGoogleException(e)) {
                        getAuthToken(account, callback);
                    }
                } else {
                    e.printStackTrace();
                }
            } catch (AuthenticatorException e) {
                e.printStackTrace();
            } catch (Exception e) {
                broadcastUpdatingStatus(ACTION_AUTHENTICATE, false);
                dismissNotification(NOTIFICATION_SENDING);
                e.printStackTrace();
            }
        }
    };
    accountManager.getAccountManager().getAuthToken(account, "Manage your tasks", null,
            GoogleTasksActivity.this, ac_callback, handler);
}

From source file:com.google.sampling.experiential.android.lib.GoogleAccountLoginHelper.java

private String getNewAuthToken(AccountManager accountManager, Account account)
        throws OperationCanceledException, IOException, AuthenticatorException {
    AccountManagerFuture<Bundle> accountManagerFuture = accountManager.getAuthToken(account, "ah", null,
            context, null, null);//ww  w .ja  v a2s  .com

    Bundle authTokenBundle = accountManagerFuture.getResult();
    return authTokenBundle.get(AccountManager.KEY_AUTHTOKEN).toString();
}

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  w w  w .  j a v  a 2 s .  c o  m
    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:org.voidsink.anewjkuapp.activity.KusssAuthenticatorActivity.java

private void finishLogin(Intent intent) {
    String accountName = intent.getStringExtra(AccountManager.KEY_ACCOUNT_NAME);
    String accountPassword = intent.getStringExtra(PARAM_USER_PASS);
    String accountType = intent.getStringExtra(AccountManager.KEY_ACCOUNT_TYPE);

    Log.i(TAG, "finish login to " + accountName);

    Account account;/*from  w  ww . j  ava  2 s. c  om*/
    boolean addNewAccount;

    final Account oldAccount = AppUtils.getAccount(this);
    if (oldAccount != null) {
        if (oldAccount.name.equals(accountName)) {
            account = oldAccount;
            addNewAccount = false;
        } else {
            AppUtils.removeAccout(mAccountManager, oldAccount);
            account = new Account(accountName, accountType);
            addNewAccount = true;
        }
    } else {
        account = new Account(accountName, accountType);
        addNewAccount = true;
    }

    if (addNewAccount) {
        String authtoken = intent.getStringExtra(AccountManager.KEY_AUTHTOKEN);
        String authtokenType = mAuthTokenType;

        // 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)
        mAccountManager.addAccountExplicitly(account, accountPassword, null);
        mAccountManager.setAuthToken(account, authtokenType, authtoken);
        mAccountManager.setPassword(account, accountPassword);

        // Turn on periodic syncing
        long interval = PreferenceWrapper.getSyncInterval(this) * 60 * 60;

        ContentResolver.addPeriodicSync(account, CalendarContractWrapper.AUTHORITY(), new Bundle(), interval);
        ContentResolver.addPeriodicSync(account, KusssContentContract.AUTHORITY, new Bundle(), interval);
        // Inform the system that this account supports sync
        ContentResolver.setIsSyncable(account, CalendarContractWrapper.AUTHORITY(), 1);
        ContentResolver.setIsSyncable(account, KusssContentContract.AUTHORITY, 1);
        // Inform the system that this account is eligible for auto sync
        // when the network is up
        ContentResolver.setSyncAutomatically(account, CalendarContractWrapper.AUTHORITY(), true);
        ContentResolver.setSyncAutomatically(account, KusssContentContract.AUTHORITY, true);
        // Recommend a schedule for automatic synchronization. The system
        // may modify this based
        // on other scheduled syncs and network utilization.
    } else {
        mAccountManager.setPassword(account, accountPassword);
    }

    // Kalender aktualisieren
    CalendarUtils.createCalendarsIfNecessary(this, account);

    // Sync NOW
    KusssAuthenticator.triggerSync(this);

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

    finish();
}

From source file:com.he5ed.lib.cloudprovider.apis.BoxApi.java

@Override
public synchronized void prepareApi(OnPrepareListener prepareListener) {
    mPrepareListener = prepareListener;//w  w w . j a  v a2  s. co m

    AccountManager.get(mContext).getAuthToken(mAccount, CloudProvider.AUTH_TYPE, false,
            new AccountManagerCallback<Bundle>() {
                @Override
                public void run(AccountManagerFuture<Bundle> future) {
                    try {
                        mAccessToken = future.getResult().getString(AccountManager.KEY_AUTHTOKEN);

                        validateAccessToken();
                    } catch (OperationCanceledException e) {
                        e.printStackTrace();
                        Log.e(TAG, e.getMessage());
                        if (mPrepareListener != null)
                            mPrepareListener.onPrepareFail(e);
                    } catch (IOException e) {
                        e.printStackTrace();
                        Log.e(TAG, e.getMessage());
                        if (mPrepareListener != null)
                            mPrepareListener.onPrepareFail(e);
                    } catch (AuthenticatorException e) {
                        e.printStackTrace();
                        Log.e(TAG, e.getMessage());
                        if (mPrepareListener != null)
                            mPrepareListener.onPrepareFail(e);
                    }
                }
            }, null);
}

From source file:com.sefford.beauthentic.activities.LoginActivity.java

void performLogin() {
    final AccountManager am = AccountManager.get(this);
    final Bundle data = new Bundle();
    data.putString(AuthenticAuthenticator.EXTRA_PASSWORD, etPassword.getText().toString());
    data.putInt(AuthenticAuthenticator.EXTRA_TYPE, AuthenticAuthenticator.Type.PASSWORD.ordinal());
    final Account account = new Account(etUsername.getText().toString(), AuthenticAuthenticator.ACCOUNT_TYPE);
    am.getAuthToken(account, "", data, true, new AccountManagerCallback<Bundle>() {
        @Override//from w  w  w .  java  2s .c o  m
        public void run(AccountManagerFuture<Bundle> future) {
            try {
                final Bundle result = future.getResult();
                if (result.getBoolean(AccountManager.KEY_BOOLEAN_RESULT)) {
                    Sessions.addAccount(am, account, etPassword.getText().toString(), Bundle.EMPTY);
                    am.setAuthToken(account, AuthenticAuthenticator.AUTHTOKEN_TYPE,
                            result.getString(AccountManager.KEY_AUTHTOKEN));
                    am.setUserData(account, AuthenticAuthenticator.EXTRA_TYPE,
                            Integer.toString(AuthenticAuthenticator.Type.PASSWORD.ordinal()));
                    notifyLoginToGCM(AuthenticAuthenticator.Type.PASSWORD.ordinal(), account.name,
                            etPassword.getText().toString(), result.getString(AccountManager.KEY_AUTHTOKEN));
                    googleApi
                            .saveCredential(
                                    new Credential.Builder(account.name)
                                            .setPassword(etPassword.getText().toString()).build(),
                                    new SmartlockCredentialCallback());
                } else {
                    Snackbar.make(vLoginForm, R.string.error_invalid_credentials, Snackbar.LENGTH_LONG).show();
                }
            } catch (OperationCanceledException e) {
                Snackbar.make(vLoginForm, R.string.error_operation_cancelled, Snackbar.LENGTH_LONG).show();
            } catch (IOException e) {
                Snackbar.make(vLoginForm, R.string.error_not_connected_to_internet, Snackbar.LENGTH_LONG)
                        .show();
            } catch (AuthenticatorException e) {
                Snackbar.make(vLoginForm, R.string.error_invalid_credentials, Snackbar.LENGTH_LONG).show();
            }
        }

    }, null);
}

From source file:com.google.android.apps.mytracks.AbstractSendToGoogleActivity.java

private void onDrivePermissionSuccess() {
    // Check Maps permission
    if (sendRequest.isSendMaps()) {
        AccountManager.get(this).getAuthToken(sendRequest.getAccount(), MapsConstants.SERVICE_NAME, null, this,
                new AccountManagerCallback<Bundle>() {
                    @Override//from w ww.ja va2s .  c o  m
                    public void run(AccountManagerFuture<Bundle> future) {
                        try {
                            if (future.getResult().getString(AccountManager.KEY_AUTHTOKEN) != null) {
                                runOnUiThread(new Runnable() {
                                    @Override
                                    public void run() {
                                        onMapsPermissionSuccess();
                                    }
                                });
                                return;
                            } else {
                                Log.d(TAG, "auth token is null");
                            }
                        } catch (OperationCanceledException e) {
                            Log.d(TAG, "Unable to get auth token", e);
                        } catch (AuthenticatorException e) {
                            Log.d(TAG, "Unable to get auth token", e);
                        } catch (IOException e) {
                            Log.d(TAG, "Unable to get auth token", e);
                        }
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                onPermissionFailure();
                            }
                        });
                    }
                }, null);
    } else {
        onMapsPermissionSuccess();
    }
}