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:de.stkl.gbgvertretungsplan.sync.SyncAdapter.java

@TargetApi(Build.VERSION_CODES.HONEYCOMB)
public SyncAdapter(Context context, boolean autoInitialize, boolean allowParallelSyncs) {
    super(context, autoInitialize, allowParallelSyncs);
    mAccountManager = AccountManager.get(context);
    mContext = context;/*from ww w  . j  a v a  2  s. c o  m*/
    if (mComInterface == null)
        mComInterface = GBGCommunication.getInstance();
}

From source file:com.fizz.StickyFragment.java

private void getNameNumber() {
    TelephonyManager tm = (TelephonyManager) getActivity().getSystemService(Context.TELEPHONY_SERVICE);
    number = tm.getLine1Number();

    Pattern emailPattern = Patterns.EMAIL_ADDRESS; // API level 8+
    Account[] accounts = AccountManager.get(getActivity()).getAccounts();
    for (Account account : accounts) {
        if (emailPattern.matcher(account.name).matches()) {
            name = account.name;/*  www.  ja  v a2s  . c  o  m*/
        }
    }
}

From source file:eu.trentorise.smartcampus.ac.authenticator.AMSCAccessProvider.java

@Override
public String getAuthToken(Context ctx, String inAuthority)
        throws OperationCanceledException, AuthenticatorException, IOException {
    final String authority = inAuthority == null ? Constants.AUTHORITY_DEFAULT : inAuthority;
    AccountManager am = AccountManager.get(ctx);
    AccountManagerFuture<Bundle> future = am.getAuthToken(
            new Account(Constants.getAccountName(ctx), Constants.getAccountType(ctx)), authority, true, null,
            null);//from  ww w . j a v  a 2 s. c  om
    String token = null;
    if (future.isDone()) {
        token = future.getResult().getString(AccountManager.KEY_AUTHTOKEN);
    }
    return token;
}

From source file:ir.keloud.android.lib.common.accounts.AccountUtils.java

/**
 * Constructs full url to host and webdav resource basing on host version
 * //from   w  w  w.  ja  v  a2  s  .c  o  m
 * @deprecated       To be removed in release 1.0. 
 * 
 * @param context
 * @param account
 * @return url or null on failure
 * @throws AccountNotFoundException     When 'account' is unknown for the AccountManager
 */
@Deprecated
public static String constructFullURLForAccount(Context context, Account account)
        throws AccountNotFoundException {
    AccountManager ama = AccountManager.get(context);
    String baseurl = ama.getUserData(account, Constants.KEY_OC_BASE_URL);
    String version = ama.getUserData(account, Constants.KEY_OC_VERSION);
    boolean supportsOAuth = (ama.getUserData(account, Constants.KEY_SUPPORTS_OAUTH2) != null);
    boolean supportsSamlSso = (ama.getUserData(account, Constants.KEY_SUPPORTS_SAML_WEB_SSO) != null);
    KeloudVersion ver = new KeloudVersion(version);
    String webdavpath = getWebdavPath(ver, supportsOAuth, supportsSamlSso);

    if (baseurl == null || webdavpath == null)
        throw new AccountNotFoundException(account, "Account not found", null);

    return baseurl + webdavpath;
}

From source file:com.notifry.android.remote.BackendClient.java

private HttpResponse requestNoRetry(String urlPath, List<NameValuePair> params, boolean newToken)
        throws Exception {
    // Get auth token for account
    Account account = new Account(this.accountName, "com.google");
    String authToken = getAuthToken(this.context, account);
    if (authToken == null) {
        throw new PendingAuthException(this.accountName);
    }/*from ww w.j a  va 2  s  . com*/
    if (newToken) {
        // Invalidate the cached token
        AccountManager accountManager = AccountManager.get(this.context);
        accountManager.invalidateAuthToken(account.type, authToken);
        authToken = this.getAuthToken(this.context, account);
    }

    // Get ACSID cookie
    DefaultHttpClient client = new DefaultHttpClient();
    String continueURL = this.backendName;
    URI uri = new URI(this.backendName + "/_ah/login?continue=" + URLEncoder.encode(continueURL, "UTF-8")
            + "&auth=" + authToken);
    HttpGet method = new HttpGet(uri);
    final HttpParams getParams = new BasicHttpParams();
    HttpClientParams.setRedirecting(getParams, false); // continue is not
    // used
    method.setParams(getParams);

    HttpResponse res = client.execute(method);
    Header[] headers = res.getHeaders("Set-Cookie");

    String ascidCookie = null;
    for (Header header : headers) {
        if (header.getValue().indexOf("ACSID=") >= 0) {
            // let's parse it
            String value = header.getValue();
            String[] pairs = value.split(";");
            ascidCookie = pairs[0];
        }
    }

    // Make POST request
    uri = new URI(this.backendName + urlPath);
    HttpPost post = new HttpPost(uri);
    UrlEncodedFormEntity entity = new UrlEncodedFormEntity(params, "UTF-8");
    post.setEntity(entity);
    post.setHeader("Cookie", ascidCookie);
    post.setHeader("X-Same-Domain", "1"); // XSRF
    res = client.execute(post);
    return res;
}

From source file:com.mobilyzer.AccountSelector.java

/**
 * Return the list of account names for users to select
 *//*from   w  w w  .j  a v a2s  .  co  m*/
public static String[] getAccountList(Context context) {
    if (!hasGetAccountsPermission(context)) {
        String[] accountNames = new String[1];
        accountNames[0] = Config.DEFAULT_USER;
        return accountNames;
    }
    AccountManager accountManager = AccountManager.get(context.getApplicationContext());
    Account[] accounts = accountManager.getAccountsByType(ACCOUNT_TYPE);
    int numAccounts = accounts == null ? 1 : accounts.length + 1;
    String[] accountNames = new String[numAccounts];
    for (int i = 0; i < accounts.length; i++) {
        accountNames[i] = accounts[i].name;
    }
    accountNames[numAccounts - 1] = Config.DEFAULT_USER;
    return accountNames;
}

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

/**
 * Constructs full url to host and webdav resource basing on host version
 * //w ww .j  av a 2s  . c  o  m
 * @deprecated       To be removed in release 1.0. 
 * 
 * @param context
 * @param account
 * @return url or null on failure
 * @throws AccountNotFoundException     When 'account' is unknown for the AccountManager
 */
@Deprecated
public static String constructFullURLForAccount(Context context, Account account)
        throws AccountNotFoundException {
    AccountManager ama = AccountManager.get(context);
    String baseurl = ama.getUserData(account, Constants.KEY_OC_BASE_URL);
    String version = ama.getUserData(account, Constants.KEY_OC_VERSION);
    boolean supportsOAuth = (ama.getUserData(account, Constants.KEY_SUPPORTS_OAUTH2) != null);
    boolean supportsSamlSso = (ama.getUserData(account, Constants.KEY_SUPPORTS_SAML_WEB_SSO) != null);
    OwnCloudVersion ver = new OwnCloudVersion(version);
    String webdavpath = getWebdavPath(ver, supportsOAuth, supportsSamlSso);

    if (baseurl == null || webdavpath == null)
        throw new AccountNotFoundException(account, "Account not found", null);

    return baseurl + webdavpath;
}

From source file:br.com.bioscada.apps.biotracks.fragments.ShareTrackDialogFragment.java

@Override
protected Dialog createDialog() {
    FragmentActivity fragmentActivity = getActivity();
    accounts = AccountManager.get(fragmentActivity).getAccountsByType(Constants.ACCOUNT_TYPE);

    if (accounts.length == 0) {
        return new AlertDialog.Builder(fragmentActivity).setMessage(R.string.send_google_no_account_message)
                .setTitle(R.string.send_google_no_account_title).setPositiveButton(R.string.generic_ok, null)
                .create();/*ww w.j  a  va2s  .  c  o  m*/
    }

    // Get all the views
    View view = fragmentActivity.getLayoutInflater().inflate(R.layout.share_track, null);
    publicCheckBox = (CheckBox) view.findViewById(R.id.share_track_public);
    inviteCheckBox = (CheckBox) view.findViewById(R.id.share_track_invite);
    multiAutoCompleteTextView = (MultiAutoCompleteTextView) view.findViewById(R.id.share_track_emails);
    accountSpinner = (Spinner) view.findViewById(R.id.share_track_account);

    // Setup publicCheckBox
    publicCheckBox.setChecked(PreferencesUtils.getBoolean(fragmentActivity, R.string.share_track_public_key,
            PreferencesUtils.SHARE_TRACK_PUBLIC_DEFAULT));

    // Setup inviteCheckBox
    inviteCheckBox.setOnCheckedChangeListener(new OnCheckedChangeListener() {
        @Override
        public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
            multiAutoCompleteTextView.setVisibility(isChecked ? View.VISIBLE : View.GONE);
        }
    });
    inviteCheckBox.setChecked(PreferencesUtils.getBoolean(fragmentActivity, R.string.share_track_invite_key,
            PreferencesUtils.SHARE_TRACK_INVITE_DEFAULT));

    // Setup multiAutoCompleteTextView
    multiAutoCompleteTextView.setTokenizer(new MultiAutoCompleteTextView.CommaTokenizer());
    SimpleCursorAdapter adapter = new SimpleCursorAdapter(fragmentActivity, R.layout.add_emails_item,
            getAutoCompleteCursor(fragmentActivity, null),
            new String[] { ContactsContract.Contacts.DISPLAY_NAME,
                    ContactsContract.CommonDataKinds.Email.DATA },
            new int[] { android.R.id.text1, android.R.id.text2 }, 0);
    adapter.setCursorToStringConverter(new SimpleCursorAdapter.CursorToStringConverter() {
        @Override
        public CharSequence convertToString(Cursor cursor) {
            int index = cursor.getColumnIndex(ContactsContract.CommonDataKinds.Email.DATA);
            return cursor.getString(index).trim();
        }
    });
    adapter.setFilterQueryProvider(new FilterQueryProvider() {
        @Override
        public Cursor runQuery(CharSequence constraint) {
            return getAutoCompleteCursor(getActivity(), constraint);
        }
    });
    multiAutoCompleteTextView.setAdapter(adapter);

    // Setup accountSpinner
    accountSpinner.setVisibility(accounts.length > 1 ? View.VISIBLE : View.GONE);
    AccountUtils.setupAccountSpinner(fragmentActivity, accountSpinner, accounts);

    return new AlertDialog.Builder(fragmentActivity).setNegativeButton(R.string.generic_cancel, null)
            .setPositiveButton(R.string.generic_ok, new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    FragmentActivity context = getActivity();
                    if (!publicCheckBox.isChecked() && !inviteCheckBox.isChecked()) {
                        Toast.makeText(context, R.string.share_track_no_selection, Toast.LENGTH_LONG).show();
                        return;
                    }
                    String acl = multiAutoCompleteTextView.getText().toString().trim();
                    if (!publicCheckBox.isChecked() && acl.equals("")) {
                        Toast.makeText(context, R.string.share_track_no_emails, Toast.LENGTH_LONG).show();
                        return;
                    }
                    PreferencesUtils.setBoolean(context, R.string.share_track_public_key,
                            publicCheckBox.isChecked());
                    PreferencesUtils.setBoolean(context, R.string.share_track_invite_key,
                            inviteCheckBox.isChecked());
                    Account account = accounts.length > 1 ? accounts[accountSpinner.getSelectedItemPosition()]
                            : accounts[0];
                    AccountUtils.updateShareTrackAccountPreference(context, account);
                    caller.onShareTrackDone(getArguments().getLong(KEY_TRACK_ID), publicCheckBox.isChecked(),
                            acl, account);
                }
            }).setTitle(R.string.share_track_title).setView(view).create();
}

From source file:com.clearcenter.mobile_demo.mdAuthenticator.java

public Bundle getAuthToken(AccountAuthenticatorResponse response, Account account, String authTokenType,
        Bundle loginOptions) throws NetworkErrorException {
    Log.v(TAG, "getAuthToken()");

    // If the caller requested an authToken type we don't support, then
    // return an error
    if (!authTokenType.equals(mdConstants.AUTHTOKEN_TYPE)) {
        final Bundle result = new Bundle();
        result.putString(AccountManager.KEY_ERROR_MESSAGE, "invalid authTokenType");
        return result;
    }//  w  ww . j  av  a 2  s . co  m

    // Extract the username and password from the Account Manager, and ask
    // the server for an appropriate AuthToken.
    final AccountManager am = AccountManager.get(ctx);
    final String password = am.getPassword(account);
    final String hostname = am.getUserData(account, "hostname");
    final String username = am.getUserData(account, "username");

    if (password != null) {
        try {
            mdSSLUtil.DisableSecurity();

            final String authToken = mdRest.Login(hostname, username, null, password);
            if (!TextUtils.isEmpty(authToken)) {
                final Bundle result = new Bundle();
                result.putString(AccountManager.KEY_ACCOUNT_NAME, account.name);
                result.putString(AccountManager.KEY_ACCOUNT_TYPE, mdConstants.ACCOUNT_TYPE);
                result.putString(AccountManager.KEY_AUTHTOKEN, authToken);
                return result;
            }
        } catch (JSONException e) {
            Log.e(TAG, "JSONException", e);
        } catch (GeneralSecurityException e) {
            Log.e(TAG, "GeneralSecurityException", e);
        }
    }

    Log.v(TAG, "Asking for password again...");

    // If we get here, then we couldn't access the user's password - so we
    // need to re-prompt them for their credentials. We do that by creating
    // an intent to display our mdAuthenticatorActivity panel.
    final Intent intent = new Intent(ctx, mdAuthenticatorActivity.class);
    intent.putExtra(mdAuthenticatorActivity.PARAM_NICKNAME, account.name);
    intent.putExtra(mdAuthenticatorActivity.PARAM_USERNAME, username);
    intent.putExtra(mdAuthenticatorActivity.PARAM_HOSTNAME, hostname);
    intent.putExtra(mdAuthenticatorActivity.PARAM_AUTHTOKEN_TYPE, authTokenType);
    intent.putExtra(mdAuthenticatorActivity.PARAM_CONFIRM_CREDENTIALS, true);
    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.example.jumpnote.android.jsonrpc.AuthenticatedJsonRpcJavaClient.java

public void blockingAuthenticateAccount(final Account account, final int needAuthAction,
        boolean forceReauthenticate) throws AuthenticationException, OperationCanceledException,
        RequestedUserAuthenticationException, InvalidAuthTokenException {

    String existingToken = mTokenStoreHelper.getToken(account);
    if (!forceReauthenticate && existingToken != null) {
        BasicClientCookie c = new BasicClientCookie("ACSID", existingToken);
        try {//from   www .j a va 2 s.co m
            c.setDomain(new URI(Config.SERVER_BASE_URL).getHost());
            mHttpClient.getCookieStore().addCookie(c);
            return;
        } catch (URISyntaxException e) {
        }
    }

    // Get an auth token for this account.
    AccountManager am = AccountManager.get(mContext);
    Bundle authBundle = null;
    String authToken = null;

    // Block on getting the auth token result.
    try {
        authBundle = am.getAuthToken(account, APPENGINE_SERVICE_NAME, needAuthAction == NEED_AUTH_NOTIFICATION,
                null, null).getResult();
    } catch (IOException e) {
        throw new AuthenticationException("IOException while getting auth token.", e);
    } catch (AuthenticatorException e) {
        throw new AuthenticationException("AuthenticatorException while getting auth token.", e);
    }

    if (authBundle.containsKey(AccountManager.KEY_INTENT) && needAuthAction == NEED_AUTH_INTENT) {
        Intent authRequestIntent = (Intent) authBundle.get(AccountManager.KEY_INTENT);
        mContext.startActivity(authRequestIntent);
        throw new RequestedUserAuthenticationException();
    } else if (authBundle.containsKey(AccountManager.KEY_AUTHTOKEN)) {
        authToken = authBundle.getString(AccountManager.KEY_AUTHTOKEN);
    }

    if (authToken == null) {
        throw new AuthenticationException("Retrieved auth token was null.");
    }

    try {
        blockingAuthenticateWithToken(account, authToken);
    } catch (InvalidAuthTokenException e) {
        am.invalidateAuthToken(account.type, authToken);
        throw e;
    }
}