Example usage for android.accounts AccountManager get

List of usage examples for android.accounts AccountManager get

Introduction

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

Prototype

public static AccountManager get(Context context) 

Source Link

Document

Gets an AccountManager instance associated with a Context.

Usage

From source file:com.NotifyMe.auth.SignInActivity.java

private String[] getAccountNames() {
    mAccountManager = AccountManager.get(this);
    Account[] accounts = mAccountManager.getAccountsByType(GoogleAuthUtil.GOOGLE_ACCOUNT_TYPE);
    String[] names = new String[accounts.length];
    for (int i = 0; i < names.length; i++) {
        names[i] = accounts[i].name;//  w ww  .  ja  va 2  s .c  o m
    }
    return names;
}

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  w  ww.j  av a 2s  .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:com.mrcaps.taskswidget.TasksHelper.java

public static void refreshAuthTokenImpl5(final Context context, final boolean invalidate,
        final Runnable continuation) {
    final Handler handl = getHandler();

    new Thread(new Runnable() {
        public void run() {
            AccountManager mgr = AccountManager.get(context);
            Account[] accts = mgr.getAccountsByType(ACCOUNT_TYPE);
            if (accts.length < 1) {
                handl.post(new Runnable() {
                    public void run() {
                        Toast.makeText(context, "Error: could not find a Google account on this phone",
                                Toast.LENGTH_SHORT).show();
                    }/*w  ww  . ja va 2 s  .  co  m*/
                });
                return;
            }

            Account acct = accts[0];

            if (invalidate) {
                long now = System.currentTimeMillis();
                Log.v(TAG, "I5 Auth Token Invalidation Requested");
                if (now - lastInvalidation > invalidationDelta) {
                    Log.v(TAG, "I5 Invalidating Auth Token");
                    try {
                        String token = mgr.blockingGetAuthToken(acct, SERVICE_NAME, true);
                        mgr.invalidateAuthToken(ACCOUNT_TYPE, token);
                    } catch (Exception e) {
                        Log.e(TAG, "I5 couldn't invalidate token", e);
                    }
                }
            }

            try {
                String token = mgr.blockingGetAuthToken(acct, SERVICE_NAME, true);
                Log.v(TAG, "I5 got auth token: " + token);
                authToken = token;
            } catch (Exception e) {
                Log.e(TAG, "I5 couldn't authenticate", e);
                handl.post(new Runnable() {
                    @Override
                    public void run() {
                        Toast.makeText(context, "Error: I5 could not authenticate with Google account",
                                Toast.LENGTH_SHORT).show();
                    }
                });
            }

            continuation.run();
        }
    }).start();
}

From source file:at.bitfire.davdroid.ui.setup.AccountDetailsFragment.java

protected boolean createAccount(String accountName, DavResourceFinder.Configuration config) {
    Account account = new Account(accountName, Constants.ACCOUNT_TYPE);

    // create Android account
    Bundle userData = AccountSettings.initialUserData(config.userName);
    App.log.log(Level.INFO, "Creating Android account with initial config", new Object[] { account, userData });

    AccountManager accountManager = AccountManager.get(getContext());
    if (!accountManager.addAccountExplicitly(account, config.password, userData))
        return false;

    // add entries for account to service DB
    App.log.log(Level.INFO, "Writing account configuration to database", config);
    @Cleanup/*from w  w  w  .  j a  v a 2 s  .c  o  m*/
    OpenHelper dbHelper = new OpenHelper(getContext());
    SQLiteDatabase db = dbHelper.getWritableDatabase();
    try {
        AccountSettings settings = new AccountSettings(getContext(), account);

        Intent refreshIntent = new Intent(getActivity(), DavService.class);
        refreshIntent.setAction(DavService.ACTION_REFRESH_COLLECTIONS);

        if (config.cardDAV != null) {
            // insert CardDAV service
            long id = insertService(db, accountName, Services.SERVICE_CARDDAV, config.cardDAV);

            // start CardDAV service detection (refresh collections)
            refreshIntent.putExtra(DavService.EXTRA_DAV_SERVICE_ID, id);
            getActivity().startService(refreshIntent);

            // initial CardDAV account settings
            int idx = spnrGroupMethod.getSelectedItemPosition();
            String groupMethodName = getResources()
                    .getStringArray(R.array.settings_contact_group_method_values)[idx];
            settings.setGroupMethod(GroupMethod.valueOf(groupMethodName));

            // enable contact sync
            ContentResolver.setIsSyncable(account, ContactsContract.AUTHORITY, 1);
            settings.setSyncInterval(ContactsContract.AUTHORITY, DEFAULT_SYNC_INTERVAL);
        } else
            // disable contact sync when CardDAV is not available
            ContentResolver.setIsSyncable(account, ContactsContract.AUTHORITY, 0);

        if (config.calDAV != null) {
            // insert CalDAV service
            long id = insertService(db, accountName, Services.SERVICE_CALDAV, config.calDAV);

            // start CalDAV service detection (refresh collections)
            refreshIntent.putExtra(DavService.EXTRA_DAV_SERVICE_ID, id);
            getActivity().startService(refreshIntent);

            // enable calendar sync
            ContentResolver.setIsSyncable(account, CalendarContract.AUTHORITY, 1);
            settings.setSyncInterval(CalendarContract.AUTHORITY, DEFAULT_SYNC_INTERVAL);

            // enable task sync, if possible
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                /* Android >=6, it's possible to gain OpenTasks permissions dynamically, so
                 * OpenTasks sync will be enabled by default. Setting the sync interval to "manually"
                 * if OpenTasks is not installed avoids the "sync error" in Android settings / Accounts. */
                ContentResolver.setIsSyncable(account, TaskProvider.ProviderName.OpenTasks.authority, 1);
                settings.setSyncInterval(TaskProvider.ProviderName.OpenTasks.authority,
                        LocalTaskList.tasksProviderAvailable(getContext()) ? DEFAULT_SYNC_INTERVAL
                                : AccountSettings.SYNC_INTERVAL_MANUALLY);
            } else {
                // Android <6: enable task sync according to whether OpenTasks is accessible
                if (LocalTaskList.tasksProviderAvailable(getContext())) {
                    ContentResolver.setIsSyncable(account, TaskProvider.ProviderName.OpenTasks.authority, 1);
                    settings.setSyncInterval(TaskProvider.ProviderName.OpenTasks.authority,
                            DEFAULT_SYNC_INTERVAL);
                } else
                    // Android <6 only: disable OpenTasks sync forever when OpenTasks is not installed
                    // because otherwise, there will be a non-catchable SecurityException as soon as OpenTasks is installed
                    ContentResolver.setIsSyncable(account, TaskProvider.ProviderName.OpenTasks.authority, 0);
            }
        } else {
            // disable calendar and task sync when CalDAV is not available
            ContentResolver.setIsSyncable(account, CalendarContract.AUTHORITY, 0);
            ContentResolver.setIsSyncable(account, TaskProvider.ProviderName.OpenTasks.authority, 0);
        }

    } catch (InvalidAccountException e) {
        App.log.log(Level.SEVERE, "Couldn't access account settings", e);
    }

    return true;
}

From source file:edu.mit.mobile.android.locast.sync.LocastSyncService.java

@Override
public void onDestroy() {
    super.onDestroy();
    AccountManager.get(this).removeOnAccountsUpdatedListener(getSyncAdapter());
}

From source file:com.alphabetbloc.accessmrs.utilities.NetworkUtils.java

private static void getServerCredentials() {
    final AccountManager am = AccountManager.get(App.getApp());
    Account[] accounts = am.getAccountsByType(App.getApp().getString(R.string.app_account_type));

    if (App.DEBUG)
        Log.v(TAG, "accounts.length =" + accounts.length);
    if (accounts.length <= 0) {
        if (App.DEBUG)
            Log.v(TAG, "no accounts have been set up");

    } else {//from   w  w  w .j a  va  2  s. com

        mUsername = accounts[0].name;
        String encPwd = am.getPassword(accounts[0]);
        mPassword = EncryptionUtil.decryptString(encPwd);
    }

}

From source file:edu.mit.mobile.android.locast.accounts.Authenticator.java

/**
 * {@inheritDoc}/*from  w  w w.  j  av a2 s. c o  m*/
 */
@Override
public Bundle getAuthToken(AccountAuthenticatorResponse response, Account account, String authTokenType,
        Bundle loginOptions) {
    if (!authTokenType.equals(AuthenticationService.AUTHTOKEN_TYPE)) {
        final Bundle result = new Bundle();
        result.putString(AccountManager.KEY_ERROR_MESSAGE, "invalid authTokenType");
        return result;
    }
    final AccountManager am = AccountManager.get(mContext);
    final String password = am.getPassword(account);
    if (password != null) {
        final Bundle accountData = onlineConfirmPassword(account, password);
        if (accountData != null) {
            final Bundle result = new Bundle();

            result.putString(AccountManager.KEY_ACCOUNT_NAME, account.name);
            result.putString(AccountManager.KEY_ACCOUNT_TYPE, AuthenticationService.ACCOUNT_TYPE);
            result.putString(AccountManager.KEY_AUTHTOKEN, password);
            return result;
        }
    }
    // the password was missing or incorrect, return an Intent to an
    // Activity that will prompt the user for the password.
    final Intent intent = new Intent(mContext, AuthenticatorActivity.class);
    intent.putExtra(AuthenticatorActivity.EXTRA_USERNAME, account.name);
    intent.putExtra(AuthenticatorActivity.EXTRA_AUTHTOKEN_TYPE, authTokenType);
    intent.putExtra(AccountManager.KEY_ACCOUNT_AUTHENTICATOR_RESPONSE, response);
    final Bundle bundle = new Bundle();
    bundle.putParcelable(AccountManager.KEY_INTENT, intent);
    return bundle;
}

From source file:com.notifry.android.ChooseAccount.java

/** Called when the activity is first created. */
@Override//www  .  j av a  2s . c o  m
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    AccountManager accountManager = AccountManager.get(getApplicationContext());

    // Sync our database. Only on create.
    NotifryAccount.FACTORY.syncAccountList(this, accountManager);

    // Set the layout, and allow text filtering.
    setContentView(R.layout.screen_accounts);
    getListView().setTextFilterEnabled(true);
}

From source file:org.gege.caldavsyncadapter.syncadapter.SyncAdapter.java

public SyncAdapter(Context context, boolean autoInitialize) {
    super(context, autoInitialize);
    //android.os.Debug.waitForDebugger();
    mAccountManager = AccountManager.get(context);
    try {/* w  ww .  j  a  v  a  2 s. co  m*/
        mVersion = context.getPackageManager().getPackageInfo(context.getPackageName(), 0).versionName;
    } catch (NameNotFoundException e) {
        e.printStackTrace();
    }
    //      mContext = context;
}

From source file:com.owncloud.android.network.OwnCloudClientUtils.java

public static WebdavClient createOwnCloudClient(Account account, Context appContext, Activity currentActivity)
        throws OperationCanceledException, AuthenticatorException, IOException, AccountNotFoundException {
    Uri uri = Uri.parse(AccountUtils.constructFullURLForAccount(appContext, account));
    AccountManager am = AccountManager.get(appContext);
    boolean isOauth2 = am.getUserData(account, AccountAuthenticator.KEY_SUPPORTS_OAUTH2) != null; // TODO avoid calling to getUserData here
    boolean isSamlSso = am.getUserData(account, AccountAuthenticator.KEY_SUPPORTS_SAML_WEB_SSO) != null;
    WebdavClient client = createOwnCloudClient(uri, appContext, !isSamlSso);

    if (isOauth2) { // TODO avoid a call to getUserData here
        AccountManagerFuture<Bundle> future = am.getAuthToken(account,
                AccountAuthenticator.AUTH_TOKEN_TYPE_ACCESS_TOKEN, null, currentActivity, null, null);
        Bundle result = future.getResult();
        String accessToken = result.getString(AccountManager.KEY_AUTHTOKEN);
        if (accessToken == null)
            throw new AuthenticatorException("WTF!");
        client.setBearerCredentials(accessToken); // TODO not assume that the access token is a bearer token

    } else if (isSamlSso) { // TODO avoid a call to getUserData here
        AccountManagerFuture<Bundle> future = am.getAuthToken(account,
                AccountAuthenticator.AUTH_TOKEN_TYPE_SAML_WEB_SSO_SESSION_COOKIE, null, currentActivity, null,
                null);/*from w  w w.  j a  va  2s. com*/
        Bundle result = future.getResult();
        String accessToken = result.getString(AccountManager.KEY_AUTHTOKEN);
        if (accessToken == null)
            throw new AuthenticatorException("WTF!");
        client.setSsoSessionCookie(accessToken);

    } else {
        String username = account.name.substring(0, account.name.lastIndexOf('@'));
        //String password = am.getPassword(account);
        //String password = am.blockingGetAuthToken(account, AccountAuthenticator.AUTH_TOKEN_TYPE_PASSWORD, false);
        AccountManagerFuture<Bundle> future = am.getAuthToken(account,
                AccountAuthenticator.AUTH_TOKEN_TYPE_PASSWORD, null, currentActivity, null, null);
        Bundle result = future.getResult();
        String password = result.getString(AccountManager.KEY_AUTHTOKEN);
        client.setBasicCredentials(username, password);
    }

    return client;
}