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(long timeout, TimeUnit unit) throws OperationCanceledException, IOException, AuthenticatorException;

Source Link

Document

Accessor for the future result the AccountManagerFuture represents.

Usage

From source file:com.jefftharris.passwdsafe.sync.owncloud.OwncloudProvider.java

/**
 * Get the ownCloud authentication for an account. A notification may be
 * presented if authorization is required. Must be called from a background
 * thread./*from w  ww .  j a  va  2 s .  c o  m*/
 */
@SuppressWarnings("deprecation")
private static String getAuthToken(Account account, Context ctx, Activity activity) {
    String authToken = null;
    try {
        AccountManager acctMgr = AccountManager.get(ctx);
        String authType = AccountTypeUtils.getAuthTokenTypePass(SyncDb.OWNCLOUD_ACCOUNT_TYPE);
        AccountManagerFuture<Bundle> fut;
        if ((activity != null) && ApiCompat.canAccountMgrGetAuthTokenWithDialog()) {
            fut = acctMgr.getAuthToken(account, authType, null, activity, null, null);
        } else {
            fut = acctMgr.getAuthToken(account, authType, true, null, null);
        }
        Bundle b = fut.getResult(60, TimeUnit.SECONDS);
        authToken = b.getString(AccountManager.KEY_AUTHTOKEN);
    } catch (Throwable e) {
        PasswdSafeUtil.dbginfo(TAG, e, "getAuthToken");
    }

    PasswdSafeUtil.dbginfo(TAG, "getAuthToken: %b", (authToken != null));
    return authToken;
}

From source file:com.todoroo.astrid.welcome.tutorial.WelcomeWalkthrough.java

private void initializeSimpleUI(final String email) {
    Button simpleLogin = (Button) findViewById(R.id.quick_login_google);
    simpleLogin.setText(getString(R.string.actfm_quick_login, email));
    simpleLogin.setOnClickListener(new OnClickListener() {
        @Override/*  w  ww . j  a  v  a2 s. c  o  m*/
        public void onClick(View v) {
            StatisticsService.reportEvent(StatisticsConstants.ACTFM_LOGIN_SIMPLE);
            final ProgressDialog pd = DialogUtilities.progressDialog(WelcomeWalkthrough.this,
                    getString(R.string.gtasks_GLA_authenticating));
            pd.show();
            getAuthToken(email, pd);
        }

        private void getAuthToken(final String e, final ProgressDialog pd) {
            final GoogleAccountManager accountManager = new GoogleAccountManager(WelcomeWalkthrough.this);
            Account a = accountManager.getAccountByName(e);
            AccountManagerCallback<Bundle> callback = new AccountManagerCallback<Bundle>() {
                public void run(final AccountManagerFuture<Bundle> future) {
                    new Thread() {
                        @Override
                        public void run() {
                            try {
                                Bundle bundle = future.getResult(30, TimeUnit.SECONDS);
                                if (bundle.containsKey(AccountManager.KEY_AUTHTOKEN)) {
                                    authToken = bundle.getString(AccountManager.KEY_AUTHTOKEN);
                                    if (!onSuccess) {
                                        accountManager.manager.invalidateAuthToken(
                                                ActFmGoogleAuthActivity.AUTH_TOKEN_TYPE, authToken);
                                        getAuthToken(e, pd);
                                        onSuccess = true;
                                    } else {
                                        onAuthTokenSuccess(e, authToken);
                                        dismissDialog = true;
                                    }
                                } else {
                                    dismissDialog = true;
                                }
                            } catch (final Exception e) {
                                Log.e("actfm-google-auth", "Login Error", e); //$NON-NLS-1$ //$NON-NLS-2$
                                runOnUiThread(new Runnable() {
                                    @Override
                                    public void run() {
                                        int error = e instanceof IOException ? R.string.gtasks_GLA_errorIOAuth
                                                : R.string.gtasks_GLA_errorAuth;
                                        Toast.makeText(WelcomeWalkthrough.this, error, Toast.LENGTH_LONG)
                                                .show();
                                        onAuthError();
                                    }
                                });
                            } finally {
                                if (dismissDialog)
                                    DialogUtilities.dismissDialog(WelcomeWalkthrough.this, pd);
                            }
                        }
                    }.start();
                }
            };
            accountManager.manager.getAuthToken(a, ActFmGoogleAuthActivity.AUTH_TOKEN_TYPE, null,
                    WelcomeWalkthrough.this, callback, null);
        }
    });

    TextView rejectQuickLogin = (TextView) findViewById(R.id.quick_login_reject);
    rejectQuickLogin.setText(getString(R.string.actfm_quick_login_reject, email));
    rejectQuickLogin.setOnClickListener(new OnClickListener() {
        @Override
        public void onClick(View v) {
            StatisticsService.reportEvent(StatisticsConstants.ACTFM_LOGIN_SIMPLE_REJECTED);
            switchToLoginPage();
        }
    });

    errors = (TextView) findViewById(R.id.error);
}

From source file:org.mozilla.gecko.sync.syncadapter.SyncAdapter.java

@Override
public void onPerformSync(final Account account, final Bundle extras, final String authority,
        final ContentProviderClient provider, final SyncResult syncResult) {
    Utils.reseedSharedRandom(); // Make sure we don't work with the same random seed for too long.

    boolean force = (extras != null) && (extras.getBoolean("force", false));
    long delay = delayMilliseconds();
    if (delay > 0) {
        if (force) {
            Log.i(LOG_TAG, "Forced sync: overruling remaining backoff of " + delay + "ms.");
        } else {/*from  w  ww  . jav  a2 s .  c o m*/
            Log.i(LOG_TAG, "Not syncing: must wait another " + delay + "ms.");
            long remainingSeconds = delay / 1000;
            syncResult.delayUntil = remainingSeconds + BACKOFF_PAD_SECONDS;
            return;
        }
    }

    // TODO: don't clear the auth token unless we have a sync error.
    Log.i(LOG_TAG, "Got onPerformSync. Extras bundle is " + extras);
    Log.i(LOG_TAG, "Account name: " + account.name);

    // TODO: don't always invalidate; use getShouldInvalidateAuthToken.
    // However, this fixes Bug 716815, so it'll do for now.
    Log.d(LOG_TAG, "Invalidating auth token.");
    invalidateAuthToken(account);

    final SyncAdapter self = this;
    final AccountManagerCallback<Bundle> callback = new AccountManagerCallback<Bundle>() {
        @Override
        public void run(AccountManagerFuture<Bundle> future) {
            Log.i(LOG_TAG, "AccountManagerCallback invoked.");
            // TODO: N.B.: Future must not be used on the main thread.
            try {
                Bundle bundle = future.getResult(60L, TimeUnit.SECONDS);
                if (bundle.containsKey("KEY_INTENT")) {
                    Log.w(LOG_TAG, "KEY_INTENT included in AccountManagerFuture bundle. Problem?");
                }
                String username = bundle.getString(Constants.OPTION_USERNAME);
                String syncKey = bundle.getString(Constants.OPTION_SYNCKEY);
                String serverURL = bundle.getString(Constants.OPTION_SERVER);
                String password = bundle.getString(AccountManager.KEY_AUTHTOKEN);
                Log.d(LOG_TAG, "Username: " + username);
                Log.d(LOG_TAG, "Server:   " + serverURL);
                Log.d(LOG_TAG, "Password? " + (password != null));
                Log.d(LOG_TAG, "Key?      " + (syncKey != null));
                if (password == null) {
                    Log.e(LOG_TAG, "No password: aborting sync.");
                    syncResult.stats.numAuthExceptions++;
                    notifyMonitor();
                    return;
                }
                if (syncKey == null) {
                    Log.e(LOG_TAG, "No Sync Key: aborting sync.");
                    syncResult.stats.numAuthExceptions++;
                    notifyMonitor();
                    return;
                }
                KeyBundle keyBundle = new KeyBundle(username, syncKey);

                // Support multiple accounts by mapping each server/account pair to a branch of the
                // shared preferences space.
                String prefsPath = Utils.getPrefsPath(username, serverURL);
                self.performSync(account, extras, authority, provider, syncResult, username, password,
                        prefsPath, serverURL, keyBundle);
            } catch (Exception e) {
                self.handleException(e, syncResult);
                return;
            }
        }
    };

    final Handler handler = null;
    final Runnable fetchAuthToken = new Runnable() {
        @Override
        public void run() {
            getAuthToken(account, callback, handler);
        }
    };
    synchronized (syncMonitor) {
        // Perform the work in a new thread from within this synchronized block,
        // which allows us to be waiting on the monitor before the callback can
        // notify us in a failure case. Oh, concurrent programming.
        new Thread(fetchAuthToken).start();

        Log.i(LOG_TAG, "Waiting on sync monitor.");
        try {
            syncMonitor.wait();
            long next = System.currentTimeMillis() + MINIMUM_SYNC_INTERVAL_MILLISECONDS;
            Log.i(LOG_TAG, "Setting minimum next sync time to " + next);
            extendEarliestNextSync(next);
        } catch (InterruptedException e) {
            Log.i(LOG_TAG, "Waiting on sync monitor interrupted.", e);
        }
    }
}