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.activiti.android.app.fragments.account.SignInFragment.java

@Override
public void onActivityCreated(Bundle savedInstanceState) {
    super.onActivityCreated(savedInstanceState);

    if (getArguments() != null) {
        hostname = getArguments().getString(ARGUMENT_HOSTNAME);
        https = getArguments().getBoolean(ARGUMENT_HTTPS);
        String url = ServerFragment.createHostnameURL(hostname, https);
        endpoint = TextUtils.isEmpty(url) ? null : Uri.parse(url);
    }//w w w.j  a v a2  s  . c o  m

    // We retrieve emails from accounts.
    mEmailView = (MaterialAutoCompleteTextView) viewById(R.id.username);
    Account[] accounts = AccountManager.get(getActivity()).getAccounts();
    List<String> names = new ArrayList<>(accounts.length);
    String accountName;
    for (int i = 0; i < accounts.length; i++) {
        accountName = accounts[i].name;
        if (!TextUtils.isEmpty(accountName) && !names.contains(accountName)) {
            names.add(accounts[i].name);
        }
    }
    ArrayAdapter adapter = new ArrayAdapter(getActivity(), android.R.layout.simple_list_item_1, names);
    mEmailView.setAdapter(adapter);

    mPasswordView = (EditText) viewById(R.id.password);

    Button mEmailSignInButton = (Button) viewById(R.id.email_sign_in_button);
    mEmailSignInButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            attemptLogin();
        }
    });

    mProgressView = viewById(R.id.login_progress);
    mFormView = viewById(R.id.login_form);

    // Server part
    httpsView = (CheckBox) viewById(R.id.signing_https);
    httpsView.setChecked(https);
    hostnameView = (MaterialEditText) viewById(R.id.signing_hostname);
    hostnameView.setText(hostname);
}

From source file:com.kiddobloom.bucketlist.AuthenticatorActivity.java

/**
 * {@inheritDoc}//from   w w w. j  a v a2  s.c  om
 */
@Override
public void onCreate(Bundle icicle) {

    Intent intent = getIntent();
    bucketListTab = intent.getIntExtra("com.kiddobloom.bucketlist.current_tab", 0);

    //Log.d("tagaa", "authenticator activity oncreate - bucketListTab: " + bucketListTab);
    requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS);
    super.onCreate(icicle);
    setProgressBarIndeterminateVisibility(false);

    uiHelper = new UiLifecycleHelper(this, callback);
    uiHelper.onCreate(icicle);

    //getActionBar().setTitle(getResources().getString(R.string.app_name));
    getActionBar().setTitle("Bucket List");
    getActionBar().setSubtitle("by kiddoBLOOM");

    sp = getSharedPreferences(getString(R.string.pref_name), MODE_PRIVATE);
    am = AccountManager.get(this);
    myApp = (MyApplication) getApplication();

    // reset the sync flag to trigger re-sync
    saveInitialSynced(false);
}

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

/**
 * Ensures that application has a fresh permission from the user to use his
 * account/*w ww  .j  av a 2 s .  c om*/
 * 
 * @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:com.ntsync.android.sync.activities.PaymentVerificationService.java

/**
 * Checks for a pending PaymentVerification
 *///from w w  w. ja v a  2  s . co  m
private void checkForPaymentVerification(Context context) {
    AccountManager acm = AccountManager.get(context);
    Account[] accounts = acm.getAccountsByType(Constants.ACCOUNT_TYPE);
    for (Account account : accounts) {
        // Don't verify is already a Verification is in Progress
        if (SyncUtils.isPaymentVerificationStarted()) {
            LogHelper.logD(TAG, "PaymentVerification skipped, because another verifcation is running", null);
            break;
        }

        PaymentData paymentData = SyncUtils.getPayment(account, acm);
        if (paymentData != null) {
            PayPalConfirmationResult result = null;
            try {
                LogHelper.logI(TAG, "PaymentVerification started for account " + account.name);
                String authtoken = NetworkUtilities.blockingGetAuthToken(acm, account, null);
                if (authtoken == null) {
                    continue;
                }
                result = NetworkUtilities.verifyPayPalPayment(context, account, paymentData.priceId.toString(),
                        paymentData.paymentConfirmation.toString(), authtoken, acm);
            } catch (NetworkErrorException e) {
                result = PayPalConfirmationResult.NETWORK_ERROR;
                LogHelper.logWCause(TAG, "Verifying PayPalPayment failed.", e);
            } catch (AuthenticationException e) {
                result = PayPalConfirmationResult.AUTHENTICATION_FAILED;
                LogHelper.logWCause(TAG, "Verifying PayPalPayment failed.", e);
            } catch (OperationCanceledException e) {
                result = PayPalConfirmationResult.AUTHENTICATION_FAILED;
                LogHelper.logD(TAG, "Verifying canceled.", e);
            } catch (ServerException e) {
                result = PayPalConfirmationResult.VERIFIER_ERROR;
                LogHelper.logWCause(TAG, "Verifying PayPalPayment failed.", e);
            }
            if (result != null) {
                processResult(context, acm, account, result);
            }
        }
    }
}

From source file:com.jose.castsocialconnector.main.MainActivity.java

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    typeFaceNormal = Typeface.createFromAsset(getAssets(), "font/DroidSans.ttf");
    typeFaceBold = Typeface.createFromAsset(getAssets(), "font/DroidSans-Bold.ttf");

    // Configure Cast device discovery
    mMediaRouter = MediaRouter.getInstance(getApplicationContext());
    mMediaRouteSelector = new MediaRouteSelector.Builder().addControlCategory(
            CastMediaControlIntent.categoryForCast(getResources().getString(R.string.app_id))).build();
    mMediaRouterCallback = new MyMediaRouterCallback();

    writeTempFile();/*from  ww  w .  j av  a  2 s . c o m*/

    // set contacts from xml file
    xmlContacts = XmlParser.parseContactsXml();
    userContact = XmlParser.parseOwnerXml();

    // connect to email
    getEmailService = new GetEmailService(this);
    accountManager = AccountManager.get(this);
    Account[] accounts = accountManager.getAccountsByType("com.google");
    onAccountSelected(accounts[0]);

    // instagram
    instagramApi = new InstagramApi(this);

    // get instagram token
    settings = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
    getInstagramInfo();

    //New Photos
    newPhotosService = new NewPhotosService(this);
    startCheckNewDataService();

    // default fragment
    showConnectWarningFragment();
}

From source file:com.afwsamples.testdpc.EnableProfileActivity.java

private boolean isAccountMigrated(String addedAccount) {
    Account[] accounts = AccountManager.get(this).getAccounts();
    for (Account account : accounts) {
        if (addedAccount.equalsIgnoreCase(account.name)) {
            return true;
        }/*from ww  w. j a v  a2s  .c  om*/
    }
    return false;
}

From source file:com.cerema.cloud2.lib.common.accounts.AccountUtils.java

/**
 * //from w w w .  j  av a  2  s.co  m
 * @return
 * @throws IOException 
 * @throws AuthenticatorException 
 * @throws OperationCanceledException 
 */
public static OwnCloudCredentials getCredentialsForAccount(Context context, Account account)
        throws OperationCanceledException, AuthenticatorException, IOException {

    OwnCloudCredentials credentials = null;
    AccountManager am = AccountManager.get(context);

    boolean isOauth2 = am.getUserData(account, AccountUtils.Constants.KEY_SUPPORTS_OAUTH2) != null;

    boolean isSamlSso = am.getUserData(account, AccountUtils.Constants.KEY_SUPPORTS_SAML_WEB_SSO) != null;

    String username = account.name.substring(0, account.name.lastIndexOf('@'));

    if (isOauth2) {
        String accessToken = am.blockingGetAuthToken(account,
                AccountTypeUtils.getAuthTokenTypeAccessToken(account.type), false);

        credentials = OwnCloudCredentialsFactory.newBearerCredentials(accessToken);

    } else if (isSamlSso) {
        String accessToken = am.blockingGetAuthToken(account,
                AccountTypeUtils.getAuthTokenTypeSamlSessionCookie(account.type), false);

        credentials = OwnCloudCredentialsFactory.newSamlSsoCredentials(username, accessToken);

    } else {
        String password = am.blockingGetAuthToken(account, AccountTypeUtils.getAuthTokenTypePass(account.type),
                false);

        credentials = OwnCloudCredentialsFactory.newBasicCredentials(username, password);
    }

    return credentials;

}

From source file:com.owncloud.android.lib.common.accounts.AccountUtils.java

/**
 * /*from w  ww .j a va 2  s.  c  o m*/
 * @return
 * @throws IOException 
 * @throws AuthenticatorException 
 * @throws OperationCanceledException 
 */
public static OwnCloudCredentials getCredentialsForAccount(Context context, Account account)
        throws OperationCanceledException, AuthenticatorException, IOException {

    OwnCloudCredentials credentials = null;
    AccountManager am = AccountManager.get(context);

    boolean isOauth2 = am.getUserData(account, AccountUtils.Constants.KEY_SUPPORTS_OAUTH2) != null;

    boolean isSamlSso = am.getUserData(account, AccountUtils.Constants.KEY_SUPPORTS_SAML_WEB_SSO) != null;

    if (isOauth2) {
        String accessToken = am.blockingGetAuthToken(account,
                AccountTypeUtils.getAuthTokenTypeAccessToken(account.type), false);

        credentials = OwnCloudCredentialsFactory.newBearerCredentials(accessToken);

    } else if (isSamlSso) {
        String accessToken = am.blockingGetAuthToken(account,
                AccountTypeUtils.getAuthTokenTypeSamlSessionCookie(account.type), false);

        credentials = OwnCloudCredentialsFactory.newSamlSsoCredentials(accessToken);

    } else {
        String username = account.name.substring(0, account.name.lastIndexOf('@'));
        String password = am.blockingGetAuthToken(account, AccountTypeUtils.getAuthTokenTypePass(account.type),
                false);

        credentials = OwnCloudCredentialsFactory.newBasicCredentials(username, password);
    }

    return credentials;

}

From source file:com.gmail.nagamatu.radiko.installer.RadikoInstallerActivity.java

private void getEmailAndPasswd() {
    final AccountManager am = AccountManager.get(this);
    mAccounts = am.getAccountsByType("com.google");
    mAccount = null;//w w  w  . ja  va 2s  .com

    switch (mAccounts.length) {
    case 0:
        updateMessage(R.string.error_download, getResources().getString(R.string.no_google_account));
        break;
    case 1:
        mAccount = mAccounts[0];
        showDialog(DIALOG_PASSWD);
        break;
    default:
        showDialog(DIALOG_SELECT_ACCOUNT);
        break;
    }
}

From source file:com.mobilyzer.AccountSelector.java

/** Starts an authentication request  */
public void authenticate() throws OperationCanceledException, AuthenticatorException, IOException {
    Logger.i("AccountSelector.authenticate() running");
    /* We only need to authenticate every AUTHENTICATE_PERIOD_MILLI milliseconds, during
     * which we can reuse the cookie. If authentication fails due to expired
     * authToken, the client of AccountSelector can call authImmedately() to request
     * authenticate() upon the next checkin
     *///from ww 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);
    }
    if (!hasGetAccountsPermission(context)) {
        isAnonymous = true;
        return;
    }

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

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

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

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

        isAnonymous = accountToUse.name.equals(defaultUserName);

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

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