Example usage for android.accounts AccountManagerFuture getResult

List of usage examples for android.accounts AccountManagerFuture getResult

Introduction

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

Prototype

V getResult() throws OperationCanceledException, IOException, AuthenticatorException;

Source Link

Document

Accessor for the future result the AccountManagerFuture represents.

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.j a v a 2  s.co 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:org.pixmob.appengine.client.AppEngineClient.java

private String getAuthToken() throws AppEngineAuthenticationException {
    // get an authentication token from the AccountManager:
    // this call is asynchronous, as the user may not respond immediately
    final AccountManagerFuture<Bundle> futureBundle = accountManager.getAuthToken(account, "ah", true, null,
            null);/* ww w.  j  ava2s . c  o m*/
    final Bundle authBundle;
    try {
        authBundle = futureBundle.getResult();
    } catch (OperationCanceledException e) {
        throw new AppEngineAuthenticationException(AUTHENTICATION_UNAVAILABLE, e);
    } catch (AuthenticatorException e) {
        throw new AppEngineAuthenticationException(AUTHENTICATION_UNAVAILABLE, e);
    } catch (IOException e) {
        throw new AppEngineAuthenticationException(AUTHENTICATION_UNAVAILABLE, e);
    }

    final String authToken = authBundle.getString(AccountManager.KEY_AUTHTOKEN);
    if (authToken == null) {
        // no authentication token was given: the user should give its
        // permission through an item in the notification bar
        Log.i(TAG, "Authentication permission is required");

        final Intent authPermIntent = (Intent) authBundle.get(AccountManager.KEY_INTENT);
        int flags = authPermIntent.getFlags();
        flags &= ~Intent.FLAG_ACTIVITY_NEW_TASK;
        authPermIntent.setFlags(flags);

        throw new AppEngineAuthenticationException(AUTHENTICATION_PENDING, authPermIntent);
    }

    return authToken;
}

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//from   www .ja v  a2  s .c o  m
 *            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: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().
 * /*from   ww w  . ja  va2s . 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:org.creativecommons.thelist.utils.ListUser.java

/**
 * Get auth token for existing account (assumes pre-existing account)
 *//*  w ww . j ava  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:com.coloreight.plugin.socialAuth.SocialAuth.java

public void getTwitterSystemAccount(final String networkUserName, final CallbackContext callbackContext) {
    cordova.getThreadPool().execute(new Runnable() {
        public void run() {

            PluginResult pluginResult;//w ww  .  ja v a2s . c  o  m
            final JSONObject json = new JSONObject();
            final JSONObject account = new JSONObject();

            final Account[] twitterAccounts = accountManager
                    .getAccountsByType("com.twitter.android.auth.login");

            try {
                if (twitterAccounts.length > 0) {
                    json.put("granted", true);

                    for (int i = 0; i < twitterAccounts.length; i++) {
                        if (twitterAccounts[i].name.equals(networkUserName)) {
                            account.put("userName", twitterAccounts[i].name);

                            final Account twitterAccount = twitterAccounts[i];

                            accountManager.getAuthToken(twitterAccount, "com.twitter.android.oauth.token", null,
                                    false, new AccountManagerCallback<Bundle>() {
                                        @Override
                                        public void run(AccountManagerFuture<Bundle> accountManagerFuture) {
                                            try {
                                                Bundle bundle = accountManagerFuture.getResult();

                                                if (bundle.containsKey(AccountManager.KEY_INTENT)) {
                                                    Intent intent = bundle
                                                            .getParcelable(AccountManager.KEY_INTENT);

                                                    //clear the new task flag just in case, since a result is expected
                                                    int flags = intent.getFlags();
                                                    flags &= ~Intent.FLAG_ACTIVITY_NEW_TASK;
                                                    intent.setFlags(flags);

                                                    requestedTwitterAccountName = networkUserName;

                                                    cordova.getActivity().startActivityForResult(intent,
                                                            TWITTER_OAUTH_REQUEST);
                                                } else {
                                                    account.put("oauth_token",
                                                            bundle.getString(AccountManager.KEY_AUTHTOKEN));

                                                    accountManager.getAuthToken(twitterAccount,
                                                            "com.twitter.android.oauth.token.secret", null,
                                                            false, new AccountManagerCallback<Bundle>() {
                                                                @Override
                                                                public void run(
                                                                        AccountManagerFuture<Bundle> accountManagerFuture) {
                                                                    try {
                                                                        Bundle bundle = accountManagerFuture
                                                                                .getResult();

                                                                        if (bundle.containsKey(
                                                                                AccountManager.KEY_INTENT)) {
                                                                            Intent intent = bundle
                                                                                    .getParcelable(
                                                                                            AccountManager.KEY_INTENT);

                                                                            //clear the new task flag just in case, since a result is expected
                                                                            int flags = intent.getFlags();
                                                                            flags &= ~Intent.FLAG_ACTIVITY_NEW_TASK;
                                                                            intent.setFlags(flags);

                                                                            requestedTwitterAccountName = networkUserName;

                                                                            cordova.getActivity()
                                                                                    .startActivityForResult(
                                                                                            intent,
                                                                                            TWITTER_OAUTH_REQUEST);
                                                                        } else {
                                                                            account.put("oauth_token_secret",
                                                                                    bundle.getString(
                                                                                            AccountManager.KEY_AUTHTOKEN));

                                                                            json.put("data", account);

                                                                            Log.v(TAG, "Account data: "
                                                                                    + json.toString());

                                                                            PluginResult pluginResult = new PluginResult(
                                                                                    PluginResult.Status.OK,
                                                                                    json);
                                                                            pluginResult.setKeepCallback(true);
                                                                            callbackContext.sendPluginResult(
                                                                                    pluginResult);
                                                                        }

                                                                    } catch (Exception e) {
                                                                        PluginResult pluginResult = new PluginResult(
                                                                                PluginResult.Status.ERROR,
                                                                                e.getLocalizedMessage());
                                                                        pluginResult.setKeepCallback(true);
                                                                        callbackContext
                                                                                .sendPluginResult(pluginResult);
                                                                    }
                                                                }
                                                            }, null);
                                                }

                                            } catch (Exception e) {
                                                PluginResult pluginResult = new PluginResult(
                                                        PluginResult.Status.ERROR, e.getLocalizedMessage());
                                                pluginResult.setKeepCallback(true);
                                                callbackContext.sendPluginResult(pluginResult);
                                            }
                                        }
                                    }, null);
                        }
                    }
                } else {
                    json.put("code", "0");
                    json.put("message", "no have twitter accounts");

                    pluginResult = new PluginResult(PluginResult.Status.ERROR, json);
                    pluginResult.setKeepCallback(true);
                    callbackContext.sendPluginResult(pluginResult);
                }
            } catch (JSONException e) {
                pluginResult = new PluginResult(PluginResult.Status.ERROR, e.getLocalizedMessage());
                pluginResult.setKeepCallback(true);
                callbackContext.sendPluginResult(pluginResult);
            }
        }
    });
}

From source file:org.creativecommons.thelist.utils.ListUser.java

/**
 * Get auth token for existing account, if the account doesnt exist, create new CCID account
 * You must already have a valid ID/*w  w  w .j  av  a  2 s . c o  m*/
 */
public void getAuthed(final AuthCallback callback) {
    Log.d(TAG, "Getting session token");
    //sessionComplete = false;

    if (isTempUser()) {
        addNewAccount(AccountGeneral.ACCOUNT_TYPE, AccountGeneral.AUTHTOKEN_TYPE_FULL_ACCESS,
                new AuthCallback() {
                    @Override
                    public void onSuccess(String authtoken) {
                        Log.v(TAG, "> getAuthed > addNewAccount token: " + authtoken);
                        callback.onSuccess(authtoken);
                    }
                });

    } else {
        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, "> getAuthed > getAuthToken from existing account: " + authtoken);
                            callback.onSuccess(authtoken);
                        } catch (OperationCanceledException e) {
                            e.printStackTrace();
                        } catch (IOException e) {
                            e.printStackTrace();
                        } catch (AuthenticatorException e) {
                            e.printStackTrace();
                        }
                    }
                }, null);
    }
}

From source file:com.jdom.get.stuff.done.android.AndroidSyncStrategy.java

private String getToken() {
    long start = System.currentTimeMillis();
    SharedPreferences prefs = activity.getSharedPreferences(Constants.AUTH_TOKEN_TYPE, Activity.MODE_PRIVATE);
    String token = prefs.getString(Constants.AUTH_TOKEN_TYPE, null);
    long lastTokenRetrievalTime = prefs.getLong(Constants.TOKEN_RETRIEVAL_TIME, 0);

    long timeSinceRetrievedLastToken = System.currentTimeMillis() - lastTokenRetrievalTime;
    long timeStillValid = Constants.TOKEN_VALID_DURATION - timeSinceRetrievedLastToken;
    if (token == null || timeStillValid < 1) {
        long portionStart = System.currentTimeMillis();
        Log.d(CLASS_NAME, "Token is no longer valid.");
        GoogleAccountManager accountManager = new GoogleAccountManager(activity);
        Account account = getAccount();//from   www. ja v a  2  s  . c o  m

        accountManager.manager.invalidateAuthToken(account.type, token);
        AccountManagerFuture<Bundle> future = accountManager.manager.getAuthToken(account,
                Constants.AUTH_TOKEN_TYPE, null, activity, null, null);
        try {
            Bundle result = future.getResult();
            token = result.getString(AccountManager.KEY_AUTHTOKEN);

            Editor editor = prefs.edit();
            editor.putString(Constants.AUTH_TOKEN_TYPE, token);
            editor.putLong(Constants.TOKEN_RETRIEVAL_TIME, System.currentTimeMillis());
            editor.commit();

        } catch (Exception e) {
            handleException(e);
        }
        AndroidSyncStrategy.logTimeTaken("Retrieving new token", portionStart);
    } else {
        Log.d(CLASS_NAME, "Token is still valid for [" + timeStillValid + "] ms.");
    }

    AndroidSyncStrategy.logTimeTaken("Retrieving token", start);
    return token;
}

From source file:com.nhvu.cordova.AccountManagerPlugin.java

@Override
public boolean execute(String action, JSONArray args, CallbackContext callbackContext) throws JSONException {
    if (manager == null) {
        manager = AccountManager.get(cordova.getActivity());
    }//from  www  . j  a  v a 2s.  c o  m

    try {
        if ("getAccountsByType".equals(action)) {
            Account[] account_list = manager.getAccountsByType(args.isNull(0) ? null : args.getString(0));
            JSONArray result = new JSONArray();

            for (Account account : account_list) {
                Integer index = indexForAccount(account);
                accounts.put(index, account);

                JSONObject account_object = new JSONObject();
                account_object.put("_index", (int) index);
                account_object.put("name", account.name);
                account_object.put("type", account.type);
                result.put(account_object);
            }

            callbackContext.success(result);
            return true;
        } else if ("addAccountExplicitly".equals(action)) {
            if (args.isNull(0) || args.getString(0).length() == 0) {
                callbackContext.error("accountType can not be null or empty");
                return true;
            } else if (args.isNull(1) || args.getString(1).length() == 0) {
                callbackContext.error("username can not be null or empty");
                return true;
            } else if (args.isNull(2) || args.getString(2).length() == 0) {
                callbackContext.error("password can not be null or empty");
                return true;
            }

            Account account = new Account(args.getString(1), args.getString(0));
            Integer index = indexForAccount(account);

            Bundle userdata = new Bundle();
            if (!args.isNull(3)) {
                JSONObject userdata_json = args.getJSONObject(3);
                if (userdata_json != null) {
                    Iterator<String> keys = userdata_json.keys();
                    while (keys.hasNext()) {
                        String key = keys.next();
                        userdata.putString(key, userdata_json.getString(key));
                    }
                }
            }

            if (false == manager.addAccountExplicitly(account, args.getString(2), userdata)) {
                callbackContext.error("Account with username already exists!");
                return true;
            }

            accounts.put(index, account);

            JSONObject result = new JSONObject();
            result.put("_index", (int) index);
            result.put("name", account.name);
            result.put("type", account.type);

            callbackContext.success(result);
            return true;
        } else if ("updateCredentials".equals(action)) {
            if (args.isNull(0)) {
                callbackContext.error("account can not be null");
                return true;
            }

            Account account = accounts.get(args.getInt(0));
            if (account == null) {
                callbackContext.error("Invalid account");
                return true;
            }

            callbackContext.error("Not yet implemented");
            return true;
        } else if ("clearPassword".equals(action)) {
            if (args.isNull(0)) {
                callbackContext.error("account can not be null");
                return true;
            }

            Account account = accounts.get(args.getInt(0));
            if (account == null) {
                callbackContext.error("Invalid account");
                return true;
            }

            manager.clearPassword(account);
            callbackContext.success();
            return true;
        } else if ("removeAccount".equals(action)) {
            if (args.isNull(0)) {
                callbackContext.error("account can not be null");
                return true;
            }

            int index = args.getInt(0);
            Account account = accounts.get(index);
            if (account == null) {
                callbackContext.error("Invalid account");
                return true;
            }

            // TODO: Add support for AccountManager (callback)
            AccountManagerFuture<Boolean> future = manager.removeAccount(account, null, null);
            try {
                if (future.getResult() == true) {
                    accounts.remove(index);
                    callbackContext.success();
                } else {
                    callbackContext.error("Failed to remove account");
                }
            } catch (OperationCanceledException e) {
                callbackContext.error("Operation canceled: " + e.getLocalizedMessage());
            } catch (AuthenticatorException e) {
                callbackContext.error("Authenticator error: " + e.getLocalizedMessage());
            } catch (IOException e) {
                callbackContext.error("IO error: " + e.getLocalizedMessage());
            }

            return true;
        } else if ("setAuthToken".equals(action)) {
            if (args.isNull(0)) {
                callbackContext.error("account can not be null");
                return true;
            } else if (args.isNull(1) || args.getString(1).length() == 0) {
                callbackContext.error("authTokenType can not be null or empty");
                return true;
            } else if (args.isNull(2) || args.getString(2).length() == 0) {
                callbackContext.error("authToken can not be null or empty");
                return true;
            }

            Account account = accounts.get(args.getInt(0));
            if (account == null) {
                callbackContext.error("Invalid account");
                return true;
            }

            manager.setAuthToken(account, args.getString(1), args.getString(2));
            callbackContext.success();
            return true;
        } else if ("peekAuthToken".equals(action)) {
            if (args.isNull(0)) {
                callbackContext.error("account can not be null");
                return true;
            } else if (args.isNull(1) || args.getString(1).length() == 0) {
                callbackContext.error("authTokenType can not be null or empty");
                return true;
            }

            Account account = accounts.get(args.getInt(0));
            if (account == null) {
                callbackContext.error("Invalid account");
                return true;
            }

            JSONObject result = new JSONObject();
            result.put("value", manager.peekAuthToken(account, args.getString(1)));
            callbackContext.success(result);
            return true;
        } else if ("getAuthToken".equals(action)) {
            if (args.isNull(0)) {
                callbackContext.error("account can not be null");
                return true;
            } else if (args.isNull(1) || args.getString(1).length() == 0) {
                callbackContext.error("authTokenType can not be null or empty");
                return true;
            } else if (args.isNull(3)) {
                callbackContext.error("notifyAuthFailure can not be null");
                return true;
            }

            Account account = accounts.get(args.getInt(0));
            if (account == null) {
                callbackContext.error("Invalid account");
                return true;
            }

            Bundle options = new Bundle();
            // TODO: Options support (will be relevent when we support AccountManagers)

            // TODO: AccountManager support
            AccountManagerFuture<Bundle> future = manager.getAuthToken(account, args.getString(1), options,
                    args.getBoolean(3), null, null);
            try {
                JSONObject result = new JSONObject();
                result.put("value", future.getResult().getString(AccountManager.KEY_AUTHTOKEN));
                callbackContext.success(result);
            } catch (OperationCanceledException e) {
                callbackContext.error("Operation canceled: " + e.getLocalizedMessage());
            } catch (AuthenticatorException e) {
                callbackContext.error("Authenticator error: " + e.getLocalizedMessage());
            } catch (IOException e) {
                callbackContext.error("IO error: " + e.getLocalizedMessage());
            }

            return true;
        } else if ("setPassword".equals(action)) {
            if (args.isNull(0)) {
                callbackContext.error("account can not be null");
                return true;
            } else if (args.isNull(1) || args.getString(1).length() == 0) {
                callbackContext.error("password can not be null or empty");
                return true;
            }

            Account account = accounts.get(args.getInt(0));
            if (account == null) {
                callbackContext.error("Invalid account");
                return true;
            }

            manager.setPassword(account, args.getString(1));
            callbackContext.success();
            return true;
        } else if ("getPassword".equals(action)) {
            if (args.isNull(0)) {
                callbackContext.error("account can not be null");
                return true;
            }

            Account account = accounts.get(args.getInt(0));
            if (account == null) {
                callbackContext.error("Invalid account");
                return true;
            }

            JSONObject result = new JSONObject();
            result.put("value", manager.getPassword(account));
            callbackContext.success(result);
            return true;
        } else if ("setUserData".equals(action)) {
            if (args.isNull(0)) {
                callbackContext.error("account can not be null");
                return true;
            } else if (args.isNull(1) || args.getString(1).length() == 0) {
                callbackContext.error("key can not be null or empty");
                return true;
            } else if (args.isNull(2) || args.getString(2).length() == 0) {
                callbackContext.error("value can not be null or empty");
                return true;
            }

            Account account = accounts.get(args.getInt(0));
            if (account == null) {
                callbackContext.error("Invalid account");
                return true;
            }

            manager.setUserData(account, args.getString(1), args.getString(2));
            callbackContext.success();
            return true;
        } else if ("getUserData".equals(action)) {
            if (args.isNull(0)) {
                callbackContext.error("account can not be null");
                return true;
            } else if (args.isNull(1) || args.getString(1).length() == 0) {
                callbackContext.error("key can not be null or empty");
                return true;
            }

            Account account = accounts.get(args.getInt(0));
            if (account == null) {
                callbackContext.error("Invalid account");
                return true;
            }

            JSONObject result = new JSONObject();
            result.put("value", manager.getUserData(account, args.getString(1)));
            callbackContext.success(result);
            return true;
        }
    } catch (SecurityException e) {
        callbackContext.error("Access denied");
        return true;
    }

    return false;
}

From source file:org.creativecommons.thelist.utils.ListUser.java

/**
 * Show all the accounts registered on the account manager. Request an auth token upon user select.
 *///from   w  ww .  jav a  2  s  . co  m
public void showAccountPicker(final AuthCallback callback) {
    //@param final boolean invalidate, final String authTokenType // mInvalidate = invalidate;
    final Account availableAccounts[] = am.getAccountsByType(AccountGeneral.ACCOUNT_TYPE);

    if (availableAccounts.length == 0) {
        //TODO: Show other dialog to add account
        addNewAccount(AccountGeneral.ACCOUNT_TYPE, AccountGeneral.AUTHTOKEN_TYPE_FULL_ACCESS,
                new AuthCallback() {
                    @Override
                    public void onSuccess(String authtoken) {
                        Log.d(TAG, " > showAccountPicker (no accounts) > addNewAccount, " + "token received: "
                                + authtoken);
                    }
                });
    } else {
        String name[] = new String[availableAccounts.length];
        for (int i = 0; i < availableAccounts.length; i++) {
            name[i] = availableAccounts[i].name;
        }

        // Account picker
        mAlertDialog = new AlertDialog.Builder(mContext).setTitle("Pick Account").setCancelable(true)
                .setPositiveButton("Add New", new OkOnClickListener())
                .setNegativeButton("Cancel", new CancelOnClickListener())
                .setAdapter(new ArrayAdapter<String>(mContext, android.R.layout.simple_list_item_1, name),
                        new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {

                                //                    TODO: do we need this?
                                //                    if(invalidate)
                                //                        invalidateAuthToken(availableAccounts[which], authTokenType);
                                //                    else
                                //                        getExistingAccountAuthToken(availableAccounts[which], authTokenType);

                                am.getAuthToken(availableAccounts[which],
                                        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,
                                                            " > showAccountPicker > getAuthToken from existing account: "
                                                                    + authtoken);
                                                    callback.onSuccess(authtoken);
                                                } catch (OperationCanceledException e) {
                                                    e.printStackTrace();
                                                } catch (IOException e) {
                                                    e.printStackTrace();
                                                } catch (AuthenticatorException e) {
                                                    e.printStackTrace();
                                                }
                                            }
                                        }, null);
                            }
                        })
                .create();
        mAlertDialog.show();
    }
}