Example usage for android.accounts AccountManagerCallback AccountManagerCallback

List of usage examples for android.accounts AccountManagerCallback AccountManagerCallback

Introduction

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

Prototype

AccountManagerCallback

Source Link

Usage

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/*from   w ww.  ja  va2 s.com*/
                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:org.creativecommons.thelist.utils.ListUser.java

/**
 * Get auth token for existing account (assumes pre-existing account)
 *//*from w w w  . j  a  v a 2  s.c o  m*/
public void getToken(final AuthCallback callback) {
    Log.d(TAG, "getToken > getting session token");
    //sessionComplete = false;
    //TODO: match userID to account with the same userID store in AccountManager
    Account account = getAccount();

    if (account == null) {
        Log.v(TAG, "getToken > getAccount > account is null");
        return;
    }

    am.getAuthToken(account, AccountGeneral.AUTHTOKEN_TYPE_FULL_ACCESS, null, mActivity,
            new AccountManagerCallback<Bundle>() {
                @Override
                public void run(AccountManagerFuture<Bundle> future) {
                    try {
                        Bundle bundle = future.getResult();
                        String authtoken = bundle.getString(AccountManager.KEY_AUTHTOKEN);
                        Log.v(TAG, "> getToken, token received: " + authtoken);
                        callback.onSuccess(authtoken);
                    } catch (OperationCanceledException e) {
                        e.printStackTrace();
                    } catch (IOException e) {
                        e.printStackTrace();
                    } catch (AuthenticatorException e) {
                        e.printStackTrace();
                    }
                }
            }, null);
}

From source file:cl.chileagil.agileday2012.fragment.MainFragment.java

private void chooseAccount() {
    accountManager.getAccountManager().getAuthTokenByFeatures(GoogleAccountManager.ACCOUNT_TYPE,
            AUTH_TOKEN_TYPE, null, MainFragment.this, null, null, new AccountManagerCallback<Bundle>() {

                public void run(AccountManagerFuture<Bundle> future) {
                    Bundle bundle;/*from   w  w  w . j a v a  2s  .  com*/
                    try {
                        bundle = future.getResult();
                        setAccountName(bundle.getString(AccountManager.KEY_ACCOUNT_NAME));
                        setAuthToken(bundle.getString(AccountManager.KEY_AUTHTOKEN));
                        onAuthToken();
                    } catch (OperationCanceledException e) {
                        // user canceled
                    } catch (AuthenticatorException e) {
                        Log.e(TAG, e.getMessage(), e);
                    } catch (IOException e) {
                        Log.e(TAG, e.getMessage(), e);
                    }
                }
            }, null);
}

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//from  ww w  . j a va  2 s  .co  m
        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:com.mobilyzer.AccountSelector.java

/** Starts an authentication request  */
public void authenticate() throws OperationCanceledException, AuthenticatorException, IOException {
    Logger.i("AccountSelector.authenticate() running");
    /* We only need to authenticate every AUTHENTICATE_PERIOD_MILLI milliseconds, during
     * which we can reuse the cookie. If authentication fails due to expired
     * authToken, the client of AccountSelector can call authImmedately() to request
     * authenticate() upon the next checkin
     *///from w w w.  j a  va  2s  .  c om
    long authTimeLast = this.getLastAuthTime();
    long timeSinceLastAuth = System.currentTimeMillis() - authTimeLast;
    if (!this.shouldAuthImmediately() && authTimeLast != 0 && (timeSinceLastAuth < AUTHENTICATE_PERIOD_MSEC)) {
        return;
    }

    Logger.i("Authenticating. Last authentication is " + timeSinceLastAuth / 1000 / 60 + " minutes ago. ");

    AccountManager accountManager = AccountManager.get(context.getApplicationContext());
    if (this.authToken != null) {
        // There will be no effect on the token if it is still valid
        Logger.i("Invalidating token");
        accountManager.invalidateAuthToken(ACCOUNT_TYPE, this.authToken);
    }
    if (!hasGetAccountsPermission(context)) {
        isAnonymous = true;
        return;
    }

    Account[] accounts = accountManager.getAccountsByType(ACCOUNT_TYPE);
    Logger.i("Got " + accounts.length + " accounts");

    SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context.getApplicationContext());
    String selectedAccount = prefs.getString(Config.PREF_KEY_SELECTED_ACCOUNT, null);
    Logger.i("Selected account = " + selectedAccount);

    final String defaultUserName = Config.DEFAULT_USER;
    isAnonymous = true;
    if (selectedAccount != null && selectedAccount.equals(defaultUserName)) {
        return;
    }

    if (accounts != null && accounts.length > 0) {
        // Default account should be the Anonymous account
        Account accountToUse = new Account(Config.DEFAULT_USER, ACCOUNT_TYPE);
        if (!accounts[accounts.length - 1].name.equals(defaultUserName)) {
            for (Account account : accounts) {
                if (account.name.equals(defaultUserName)) {
                    accountToUse = account;
                    break;
                }
            }
        }
        if (selectedAccount != null) {
            for (Account account : accounts) {
                if (account.name.equals(selectedAccount)) {
                    accountToUse = account;
                    break;
                }
            }
        }

        isAnonymous = accountToUse.name.equals(defaultUserName);

        if (isAnonymous) {
            Logger.d("Skipping authentication as account is " + defaultUserName);
            return;
        }

        Logger.i("Trying to get auth token for " + accountToUse);
        AccountManagerFuture<Bundle> future = accountManager.getAuthToken(accountToUse, "ah", false,
                new AccountManagerCallback<Bundle>() {
                    @Override
                    public void run(AccountManagerFuture<Bundle> result) {
                        Logger.i("AccountManagerCallback invoked");
                        try {
                            getAuthToken(result);
                        } catch (RuntimeException e) {
                            Logger.e("Failed to get authToken", e);
                            /* TODO(Wenjie): May ask the user whether to quit the app nicely here if a number
                             * of trials have been made and failed. Since Speedometer is basically useless 
                             * without checkin
                             */
                        }
                    }
                }, null);
        Logger.i("AccountManager.getAuthToken returned " + future);
    } else {
        throw new RuntimeException("No google account found");
    }
}

From source file:org.brussels.gtug.attendance.AccountsActivity.java

/**
 * Registers for C2DM messaging with the given account name.
 * // w w  w. j a  va  2  s  .  c  o m
 * @param accountName a String containing a Google account name
 */
private void register(final String accountName) {
    // Store the account name in shared preferences
    final SharedPreferences prefs = Util.getSharedPreferences(mContext);
    SharedPreferences.Editor editor = prefs.edit();
    editor.putString(Util.ACCOUNT_NAME, accountName);
    editor.remove(Util.AUTH_COOKIE);
    editor.remove(Util.DEVICE_REGISTRATION_ID);
    editor.commit();

    // Obtain an auth token and register<
    final AccountManager mgr = AccountManager.get(mContext);
    Account[] accts = mgr.getAccountsByType("com.google");
    for (Account acct : accts) {
        final Account account = acct;
        if (account.name.equals(accountName)) {
            // Get the auth token from the AccountManager and convert
            // it into a cookie for the appengine server
            final Activity activity = this;
            mgr.getAuthToken(account, "ah", null, activity, new AccountManagerCallback<Bundle>() {
                public void run(AccountManagerFuture<Bundle> future) {
                    String authToken = getAuthToken(future);
                    // Ensure the token is not expired by invalidating it and
                    // obtaining a new one
                    mgr.invalidateAuthToken(account.type, authToken);
                    mgr.getAuthToken(account, "ah", null, activity, new AccountManagerCallback<Bundle>() {
                        public void run(AccountManagerFuture<Bundle> future) {
                            String authToken = getAuthToken(future);
                            // Convert the token into a cookie for future use
                            String authCookie = getAuthCookie(authToken);
                            Editor editor = prefs.edit();
                            editor.putString(Util.AUTH_COOKIE, authCookie);
                            editor.commit();
                            C2DMessaging.register(mContext, Constants.SENDER_ID);
                        }
                    }, null);
                }
            }, null);
            break;
        }
    }
}

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 .  ja 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: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().
 * /* ww w .ja  va  2  s . co  m*/
 * @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:uk.co.bubblebearapps.contactsintegration.MainActivity.java

private void removeAccount(Account account) {
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP_MR1) {
        mAccountManager.removeAccount(account, this, new AccountManagerCallback<Bundle>() {
            @Override//  ww w  .  j a v  a 2s. c  o m
            public void run(AccountManagerFuture<Bundle> future) {

                try {
                    Boolean result = future.getResult().getBoolean(AccountManager.KEY_BOOLEAN_RESULT);
                    if (result) {
                        showMessage("Account deleted");
                    } else {
                        showMessage("Account not deleted");
                    }

                } catch (Exception e) {
                    e.printStackTrace();
                    showMessage(e.getMessage());
                }
            }
        }, new Handler());
    } else {
        mAccountManager.removeAccount(account, new AccountManagerCallback<Boolean>() {
            @Override
            public void run(AccountManagerFuture<Boolean> future) {
                try {
                    Boolean result = future.getResult();
                    if (result) {
                        showMessage("Account deleted");
                    } else {
                        showMessage("Account not deleted");
                    }

                } catch (Exception e) {
                    e.printStackTrace();
                    showMessage(e.getMessage());
                }

            }
        }, new Handler());
    }
}