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.sefford.beauthentic.activities.LoginActivity.java

void performLogin() {
    final AccountManager am = AccountManager.get(this);
    final Bundle data = new Bundle();
    data.putString(AuthenticAuthenticator.EXTRA_PASSWORD, etPassword.getText().toString());
    data.putInt(AuthenticAuthenticator.EXTRA_TYPE, AuthenticAuthenticator.Type.PASSWORD.ordinal());
    final Account account = new Account(etUsername.getText().toString(), AuthenticAuthenticator.ACCOUNT_TYPE);
    am.getAuthToken(account, "", data, true, new AccountManagerCallback<Bundle>() {
        @Override//w w  w  .  ja v  a  2s .  co  m
        public void run(AccountManagerFuture<Bundle> future) {
            try {
                final Bundle result = future.getResult();
                if (result.getBoolean(AccountManager.KEY_BOOLEAN_RESULT)) {
                    Sessions.addAccount(am, account, etPassword.getText().toString(), Bundle.EMPTY);
                    am.setAuthToken(account, AuthenticAuthenticator.AUTHTOKEN_TYPE,
                            result.getString(AccountManager.KEY_AUTHTOKEN));
                    am.setUserData(account, AuthenticAuthenticator.EXTRA_TYPE,
                            Integer.toString(AuthenticAuthenticator.Type.PASSWORD.ordinal()));
                    notifyLoginToGCM(AuthenticAuthenticator.Type.PASSWORD.ordinal(), account.name,
                            etPassword.getText().toString(), result.getString(AccountManager.KEY_AUTHTOKEN));
                    googleApi
                            .saveCredential(
                                    new Credential.Builder(account.name)
                                            .setPassword(etPassword.getText().toString()).build(),
                                    new SmartlockCredentialCallback());
                } else {
                    Snackbar.make(vLoginForm, R.string.error_invalid_credentials, Snackbar.LENGTH_LONG).show();
                }
            } catch (OperationCanceledException e) {
                Snackbar.make(vLoginForm, R.string.error_operation_cancelled, Snackbar.LENGTH_LONG).show();
            } catch (IOException e) {
                Snackbar.make(vLoginForm, R.string.error_not_connected_to_internet, Snackbar.LENGTH_LONG)
                        .show();
            } catch (AuthenticatorException e) {
                Snackbar.make(vLoginForm, R.string.error_invalid_credentials, Snackbar.LENGTH_LONG).show();
            }
        }

    }, null);
}

From source file:at.software2014.trackme.MainActivity.java

public String getEmailAddress() {
    String emailAddress = "";

    Pattern emailPattern = Patterns.EMAIL_ADDRESS;
    Account[] accounts = AccountManager.get(getBaseContext()).getAccounts();

    for (Account account : accounts) {
        if (emailPattern.matcher(account.name).matches() && account.name.endsWith("gmail.com")) {
            emailAddress = account.name;
            break;
        }/*w  w  w. j  av a 2s  .c o  m*/
    }

    return emailAddress;
}

From source file:com.gaba.alex.trafficincidents.MainActivity.java

private Account createSyncAccount() {
    Account appAccount = new Account(mAccountName, mAccountType);
    AccountManager accountManager = AccountManager.get(this);
    if (accountManager.addAccountExplicitly(appAccount, null, null)) {
        ContentResolver.setMasterSyncAutomatically(true);
        ContentResolver.setSyncAutomatically(appAccount, AUTHORITY, true);
    }//from w  w  w .j  a  v  a  2s.c  o  m
    return appAccount;
}

From source file:com.owncloud.android.ui.activity.ManageAccountsActivity.java

@Override
public void createAccount() {
    AccountManager am = AccountManager.get(getApplicationContext());
    am.addAccount(MainApp.getAccountType(), null, null, null, this, new AccountManagerCallback<Bundle>() {
        @Override/*from  w  w w.  ja v a2s .c om*/
        public void run(AccountManagerFuture<Bundle> future) {
            if (future != null) {
                try {
                    Bundle result = future.getResult();
                    String name = result.getString(AccountManager.KEY_ACCOUNT_NAME);
                    AccountUtils.setCurrentOwnCloudAccount(getApplicationContext(), name);
                    mAccountListAdapter = new AccountListAdapter(ManageAccountsActivity.this,
                            getAccountListItems(), mTintedCheck);
                    mListView.setAdapter(mAccountListAdapter);
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            mAccountListAdapter.notifyDataSetChanged();
                        }
                    });
                } catch (OperationCanceledException e) {
                    Log_OC.d(TAG, "Account creation canceled");
                } catch (Exception e) {
                    Log_OC.e(TAG, "Account creation finished in exception: ", e);
                }
            }
        }
    }, mHandler);
}

From source file:uk.ac.horizon.aestheticodes.controllers.ExperienceListUpdater.java

private HttpResponse put(String url, String data) throws Exception {
    HttpClient client = new DefaultHttpClient();
    HttpPut put = new HttpPut(new URL(url).toURI());
    put.addHeader("content-type", "application/json");
    put.setEntity(new StringEntity(data));

    String token = null;/*ww w.  j a  v a 2 s . c  o m*/
    try {
        AccountManager accountManager = AccountManager.get(context);
        Account[] accounts = accountManager.getAccountsByType("com.google");
        if (accounts.length >= 1) {
            Log.i("", "Getting token for " + accounts[0].name);
            token = GoogleAuthUtil.getToken(context, accounts[0].name, context.getString(R.string.app_scope));
            put.addHeader("Authorization", "Bearer " + token);
            Log.i("", token);
        }
    } catch (Exception e) {
        Log.e("", e.getMessage(), e);
    }

    Log.i("", "PUT " + url);
    Log.i("", data);
    HttpResponse response = client.execute(put);
    if (response.getStatusLine().getStatusCode() == 401) {
        Log.w("", "Response " + response.getStatusLine().getStatusCode());
        if (token != null) {
            GoogleAuthUtil.invalidateToken(context, token);
        }
    } else if (response.getStatusLine().getStatusCode() != 200) {
        Log.w("", "Response " + response.getStatusLine().getStatusCode() + ": "
                + response.getStatusLine().getReasonPhrase());
    }

    return response;
}

From source file:com.murrayc.galaxyzoo.app.LoginUtils.java

/** Don't call this from the main UI thread.
 *
 * @param context//from   w w  w . j  a  v a 2s. co m
 */
public static void removeAccount(final Context context, final String accountName) {
    final AccountManager accountManager = AccountManager.get(context);
    final Account account = new Account(accountName, LoginUtils.ACCOUNT_TYPE);

    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP_MR1) {
        //Trying to call this on an older Android version results in a
        //NoSuchMethodError exception.
        //There is no AppCompat version of the AccountManager API to
        //avoid the need for this version check at runtime.
        accountManager.removeAccount(account, null, null, null);
    } else {
        //noinspection deprecation
        //Note that this needs the MANAGE_ACCOUNT permission on
        //SDK <=22.
        //noinspection deprecation
        accountManager.removeAccount(account, null, null);
    }
}

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

/**
 * Restore the client cookies from accountName
 * @param accountName//from  w  w w. j av  a 2 s.  com
 * @param client
 * @param context
 */
public static void restoreCookies(String accountName, KeloudClient client, Context context) {
    Log_OC.d(TAG, "Restoring cookies for " + accountName);

    // Account Manager
    AccountManager am = AccountManager.get(context.getApplicationContext());

    // Get account
    Account account = null;
    Account accounts[] = am.getAccounts();
    for (Account a : accounts) {
        if (a.name.equals(accountName)) {
            account = a;
            break;
        }
    }

    // Restoring cookies
    if (account != null) {
        restoreCookies(account, client, context);
    }
}

From source file:com.digitalarx.android.authentication.AuthenticatorActivity.java

/**
 * {@inheritDoc}//from   w  ww.  j a v a  2 s.c  om
 * 
 * IMPORTANT ENTRY POINT 1: activity is shown to the user
 */
@Override
protected void onCreate(Bundle savedInstanceState) {
    //Log_OC.wtf(TAG,  "onCreate init");
    super.onCreate(savedInstanceState);
    getWindow().requestFeature(Window.FEATURE_NO_TITLE);

    // bind to Operations Service
    mOperationsServiceConnection = new OperationsServiceConnection();
    if (!bindService(new Intent(this, OperationsService.class), mOperationsServiceConnection,
            Context.BIND_AUTO_CREATE)) {
        Toast.makeText(this, R.string.error_cant_bind_to_operations_service, Toast.LENGTH_LONG).show();
        finish();
    }

    /// init activity state
    mAccountMgr = AccountManager.get(this);
    mNewCapturedUriFromOAuth2Redirection = null;

    /// get input values
    mAction = getIntent().getByteExtra(EXTRA_ACTION, ACTION_CREATE);
    mAccount = getIntent().getExtras().getParcelable(EXTRA_ACCOUNT);
    if (savedInstanceState == null) {
        initAuthTokenType();
    } else {
        mAuthTokenType = savedInstanceState.getString(KEY_AUTH_TOKEN_TYPE);
        mWaitingForOpId = savedInstanceState.getLong(KEY_WAITING_FOR_OP_ID);
    }

    /// load user interface
    setContentView(R.layout.account_setup);

    /// initialize general UI elements
    initOverallUi(savedInstanceState);

    mOkButton = findViewById(R.id.buttonOK);

    /// initialize block to be moved to single Fragment to check server and get info about it 
    initServerPreFragment(savedInstanceState);

    /// initialize block to be moved to single Fragment to retrieve and validate credentials 
    initAuthorizationPreFragment(savedInstanceState);

    //Log_OC.wtf(TAG,  "onCreate end");
}

From source file:com.myandroidremote.AccountsActivity.java

/**
 * Registers for C2DM messaging with the given account name.
 * //from   w  ww . ja v a2  s  .  c om
 * @param accountName
 *            a String containing a Google account name
 */
private void register(final String accountName) {
    // Store the account name in shared preferences
    final SharedPreferences prefs = Util.getSharedPreferences(mContext);
    SharedPreferences.Editor editor = prefs.edit();
    editor.putString(Util.ACCOUNT_NAME, accountName);
    editor.putString(Util.AUTH_COOKIE, null);
    editor.commit();

    // Obtain an auth token and register
    final AccountManager mgr = AccountManager.get(mContext);
    Account[] accts = mgr.getAccountsByType("com.google");
    for (Account acct : accts) {
        if (acct.name.equals(accountName)) {
            if (Util.isDebug(mContext)) {
                // Use a fake cookie for the dev mode app engine server
                // The cookie has the form email:isAdmin:userId
                // We set the userId to be the same as the account name
                String authCookie = "dev_appserver_login=" + accountName + ":false:" + accountName;
                boolean result = prefs.edit().putString(Util.AUTH_COOKIE, authCookie).commit();
                C2DMessaging.register(mContext, Setup.SENDER_ID);
            } else {
                // Get the auth token from the AccountManager and convert
                // it into a cookie for the appengine server
                mgr.getAuthToken(acct, "ah", null, this, new AccountManagerCallback<Bundle>() {
                    public void run(AccountManagerFuture<Bundle> future) {
                        try {
                            Bundle authTokenBundle = future.getResult();
                            String authToken = authTokenBundle.get(AccountManager.KEY_AUTHTOKEN).toString();
                            String authCookie = getAuthCookie(authToken);
                            if (authCookie == null) {
                                mgr.invalidateAuthToken("com.google", authToken);
                            }
                            prefs.edit().putString(Util.AUTH_COOKIE, authCookie).commit();

                            C2DMessaging.register(mContext, Setup.SENDER_ID);
                        } catch (AuthenticatorException e) {
                            Log.w(TAG, "Got AuthenticatorException " + e);
                            Log.w(TAG, Log.getStackTraceString(e));
                        } catch (IOException e) {
                            Log.w(TAG, "Got IOException " + Log.getStackTraceString(e));
                            Log.w(TAG, Log.getStackTraceString(e));
                        } catch (OperationCanceledException e) {
                            Log.w(TAG, "Got OperationCanceledException " + e);
                            Log.w(TAG, Log.getStackTraceString(e));
                        }
                    }
                }, null);
            }
            break;
        }
    }
}

From source file:com.nest5.businessClient.AccountsActivity.java

/**
 * Registers for C2DM messaging with the given account name.
 * /*from www. j a v a2s. c  o  m*/
 * @param accountName a String containing a Google account name
 */
private void register(final String accountName) {
    // Store the account name in shared preferences
    final SharedPreferences prefs = Util.getSharedPreferences(mContext);
    SharedPreferences.Editor editor = prefs.edit();
    editor.putString(Util.ACCOUNT_NAME, accountName);
    editor.remove(Util.AUTH_COOKIE);
    editor.remove(Util.DEVICE_REGISTRATION_ID);
    editor.commit();

    // Obtain an auth token and register
    final AccountManager mgr = AccountManager.get(mContext);
    Account[] accts = mgr.getAccountsByType("com.google");
    for (Account acct : accts) {
        final Account account = acct;
        if (account.name.equals(accountName)) {

            // Get the auth token from the AccountManager and convert
            // it into a cookie for the appengine server
            final Activity activity = this;
            mgr.getAuthToken(account, "ah", null, activity, new AccountManagerCallback<Bundle>() {
                public void run(AccountManagerFuture<Bundle> future) {
                    String authToken = getAuthToken(future);
                    // Ensure the token is not expired by invalidating it and
                    // obtaining a new one
                    mgr.invalidateAuthToken(account.type, authToken);
                    mgr.getAuthToken(account, "ah", null, activity, new AccountManagerCallback<Bundle>() {
                        public void run(AccountManagerFuture<Bundle> future) {
                            String authToken = getAuthToken(future);
                            // Convert the token into a cookie for future use
                            String authCookie = getAuthCookie(authToken);
                            Editor editor = prefs.edit();
                            editor.putString(Util.AUTH_COOKIE, authCookie);
                            editor.commit();
                            C2DMessaging.register(mContext, Setup.SENDER_ID);
                        }
                    }, null);
                }
            }, null);

            break;
        }
    }
}