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:de.msal.shoutemo.connector.GetPostsService.java

/**
 *
 *///www  .  j a  v  a  2s .c  o m
private void startGetPostsTask() {
    mAccountManager.getAuthToken(mAccount, LoginActivity.PARAM_AUTHTOKEN_TYPE, null, false,
            new AccountManagerCallback<Bundle>() {
                @Override
                public void run(AccountManagerFuture<Bundle> result) {
                    Bundle bundle;
                    try {
                        bundle = result.getResult();
                    } catch (OperationCanceledException e) {
                        e.printStackTrace();
                        return;
                    } catch (AuthenticatorException e) {
                        e.printStackTrace();
                        return;
                    } catch (IOException e) {
                        e.printStackTrace();
                        return;
                    }
                    mAuthToken = bundle.getString(AccountManager.KEY_AUTHTOKEN);
                    Log.v(TAG, "Received authentication token=" + mAuthToken);
                    // now get messages!
                    if (worker == null || worker.isShutdown()) {
                        worker = Executors.newSingleThreadScheduledExecutor();
                    }
                    // fix (possible) wrong time-setting on autemo.com
                    worker.execute(new SetTimezoneTask());
                    // only now recieve messages (with right time)
                    worker.scheduleAtFixedRate(new GetPostsTask(), 0, INTERVAL, TimeUnit.MILLISECONDS);
                }
            }, null);
}

From source file:com.example.jumpnote.android.jsonrpc.AuthenticatedJsonRpcJavaClient.java

public static void ensureHasTokenWithUI(Activity activity, Account account,
        final EnsureHasTokenWithUICallback callback) {
    AccountManager am = AccountManager.get(activity);
    am.getAuthToken(account, APPENGINE_SERVICE_NAME, null, activity, new AccountManagerCallback<Bundle>() {
        public void run(AccountManagerFuture<Bundle> authBundleFuture) {
            Bundle authBundle = null;/* w w w .j  ava 2 s  .c  o  m*/
            try {
                authBundle = authBundleFuture.getResult();
            } catch (OperationCanceledException e) {
                callback.onAuthDenied();
                return;
            } catch (AuthenticatorException e) {
                callback.onError(e);
                return;
            } catch (IOException e) {
                callback.onError(e);
                return;
            }

            if (authBundle.containsKey(AccountManager.KEY_AUTHTOKEN)) {
                callback.onHasToken((String) authBundle.get(AccountManager.KEY_AUTHTOKEN));
            } else {
                callback.onError(
                        new IllegalStateException("No auth token available, but operation not canceled."));
            }
        }
    }, null);
}

From source file:com.google.wireless.speed.speedometer.AccountSelector.java

/** Starts an authentication request  */
public void authenticate() throws OperationCanceledException, AuthenticatorException, IOException {
    Log.i(SpeedometerApp.TAG, "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  ww w .j a  va  2  s  .c  o  m
    long authTimeLast = this.getLastAuthTime();
    long timeSinceLastAuth = System.currentTimeMillis() - authTimeLast;
    if (!this.shouldAuthImmediately() && authTimeLast != 0 && (timeSinceLastAuth < AUTHENTICATE_PERIOD_MSEC)) {
        return;
    }

    Log.i(SpeedometerApp.TAG,
            "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
        Log.i(SpeedometerApp.TAG, "Invalidating token");
        accountManager.invalidateAuthToken(ACCOUNT_TYPE, this.authToken);
    }

    Account[] accounts = accountManager.getAccountsByType(ACCOUNT_TYPE);
    Log.i(SpeedometerApp.TAG, "Got " + accounts.length + " accounts");

    if (accounts != null && accounts.length > 0) {
        // TODO(mdw): If multiple accounts, need to pick the correct one
        Account accountToUse = accounts[0];
        // We prefer google's corporate account to personal accounts such as somebody@gmail.com
        for (Account account : accounts) {
            if (account.name.toLowerCase().trim().endsWith(ACCOUNT_NAME)) {
                Log.i(SpeedometerApp.TAG, "Using the preferred google.com account: " + account.name);
                accountToUse = account;
                break;
            }
        }

        Log.i(SpeedometerApp.TAG, "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) {
                        Log.i(SpeedometerApp.TAG, "AccountManagerCallback invoked");
                        try {
                            getAuthToken(result);
                        } catch (RuntimeException e) {
                            Log.e(SpeedometerApp.TAG, "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);
        Log.i(SpeedometerApp.TAG, "AccountManager.getAuthToken returned " + future);
    } else {
        throw new RuntimeException("No google account found");
    }
}

From source file:net.vleu.par.android.rpc.Transceiver.java

/**
 * Ensures that application has a fresh permission from the user to use his
 * account//from   ww w  . j a  v a 2s. c o m
 * 
 * @param activity
 *            The Activity context to use for launching a new sub-Activity
 *            to prompt the user for a password if necessary; used only to
 *            call startActivity(); must not be null.
 * @param onUserResponse
 *            If not null, will be called in the main thread after the user
 *            answered
 */
public static void askUserForSinglePermissionIfNecessary(final Activity activity, final Runnable onUserResponse,
        final Account account) {
    final AccountManager am = AccountManager.get(activity);
    final AccountManagerCallback<Bundle> callback = new AccountManagerCallback<Bundle>() {
        @Override
        public void run(final AccountManagerFuture<Bundle> bundle) {
            if (onUserResponse != null)
                activity.runOnUiThread(onUserResponse);
        }
    };
    am.getAuthToken(account, APPENGINE_TOKEN_TYPE, null, activity, callback, null);
}

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/*from   w  w w  . j  av  a 2s . co 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.mobiperf.speedometer.AccountSelector.java

/** Starts an authentication request */
public void authenticate() throws OperationCanceledException, AuthenticatorException, IOException {
    Logger.i("AccountSelector.authenticate() running");
    /*/*www . j  ava 2 s . c om*/
     * 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
     */
    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);
    }

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

    // get selected account
    SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this.context);
    String selectedAccount = prefs.getString(Config.PREF_KEY_SELECTED_ACCOUNT, null);

    if (accounts != null && accounts.length > 0 && selectedAccount != null) {
        Account accountToUse = null;
        for (Account account : accounts) {
            // if (account.name.toLowerCase().trim().endsWith(ACCOUNT_NAME)) {
            Logger.i("account list: " + account.name + " " + account.type + " " + account.toString());
            // If one of the available accounts is the one selected by user, use that
            if (account.name.equals(selectedAccount)) {
                accountToUse = account;
                Logger.i("selected account: " + account.name + " " + account.type + " " + account.toString());
            }
        }

        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 or no google account selected");
    }
}

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

void gotAccount() {
    Account account = accountManager.getAccountByName(accountName);
    if (account == null) {
        chooseAccount();/* ww  w.j  ava  2s  .co  m*/
        return;
    }
    if (authToken != null) {
        //Ya tengo elegido mi cuenta.
        //Solo si no tengo datos en la DB, lo pido, sino cargo lo que hay
        //y actualizo solo a peticion del usuario
        DatabaseAdapter dbAdapter = null;
        try {
            dbAdapter = new DatabaseAdapter(this);
            dbAdapter.open();
            if (dbAdapter.fetchCountEvents() <= 0) {
                onAuthToken();
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                dbAdapter.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return;
    }
    accountManager.getAccountManager().getAuthToken(account, AUTH_TOKEN_TYPE, true,
            new AccountManagerCallback<Bundle>() {

                public void run(AccountManagerFuture<Bundle> future) {
                    try {
                        Bundle bundle = future.getResult();
                        if (bundle.containsKey(AccountManager.KEY_INTENT)) {
                            Intent intent = bundle.getParcelable(AccountManager.KEY_INTENT);
                            intent.setFlags(intent.getFlags() & ~Intent.FLAG_ACTIVITY_NEW_TASK);
                            startActivityForResult(intent, REQUEST_AUTHENTICATE);
                        } else if (bundle.containsKey(AccountManager.KEY_AUTHTOKEN)) {
                            setAuthToken(bundle.getString(AccountManager.KEY_AUTHTOKEN));
                            onAuthToken();
                        }
                    } catch (Exception e) {
                        Log.e(TAG, e.getMessage(), e);
                    }
                }
            }, null);
}

From source file:com.num.mobiperf.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
     *///  w w  w . j  a v  a 2  s .c  o  m
    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);
    }

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

    SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this.context);
    String selectedAccount = prefs.getString("PREF_KEY_SELECTED_ACCOUNT", null);

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

    if (accounts != null && accounts.length > 0) {
        // Default account should be the Anonymous account
        Account accountToUse = accounts[accounts.length - 1];
        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;
        }
        // WHERE YOU GET TOKEN!!!!!!
        //Logger.i("Trying to get auth token for " + accountToUse);
        AccountManagerFuture<Bundle> future = accountManager.getAuthToken(accountToUse, "ah", false,
                new AccountManagerCallback<Bundle>() {
                    public void run(AccountManagerFuture<Bundle> result) {
                        //Logger.i("AccountManagerCallback invoked");
                        try {
                            getAuthToken(result);
                        } catch (RuntimeException e) {
                            System.out.println("Failed to get authToken" + e.getLocalizedMessage());
                            //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:com.mobiperf_library.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
     *//*www .java2 s .co m*/
    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);
    }

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

    SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this.context);
    String selectedAccount = prefs.getString(Config.PREF_KEY_SELECTED_ACCOUNT, null);

    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 = accounts[accounts.length - 1];
        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:com.mobiperf.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
     */// www  . ja  v  a 2  s . c o m
    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);
    }

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

    SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this.context);
    String selectedAccount = prefs.getString(Config.PREF_KEY_SELECTED_ACCOUNT, null);

    final String defaultUserName = context.getString(R.string.defaultUser);
    isAnonymous = true;
    if (selectedAccount != null && selectedAccount.equals(defaultUserName)) {
        return;
    }

    if (accounts != null && accounts.length > 0) {
        // Default account should be the Anonymous account
        Account accountToUse = accounts[accounts.length - 1];
        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");
    }
}