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.saarang.samples.apps.iosched.ui.BaseActivity.java

/**
 * Sets up the account box. The account box is the area at the top of the nav drawer that
 * shows which account the user is logged in as, and lets them switch accounts. It also
 * shows the user's Google+ cover photo as background.
 *//*from w  w w  .  j  a  v a  2  s. c o m*/
private void setupAccountBox() {
    mAccountListContainer = (LinearLayout) findViewById(com.saarang.samples.apps.iosched.R.id.account_list);

    if (mAccountListContainer == null) {
        //This activity does not have an account box
        return;
    }

    final View chosenAccountView = findViewById(com.saarang.samples.apps.iosched.R.id.chosen_account_view);
    Account chosenAccount = AccountUtils.getActiveAccount(this);
    if (chosenAccount == null) {
        // No account logged in; hide account box
        chosenAccountView.setVisibility(View.GONE);
        mAccountListContainer.setVisibility(View.GONE);
        return;
    } else {
        chosenAccountView.setVisibility(View.VISIBLE);
        mAccountListContainer.setVisibility(View.INVISIBLE);
    }

    AccountManager am = AccountManager.get(this);
    Account[] accountArray = am.getAccountsByType(GoogleAuthUtil.GOOGLE_ACCOUNT_TYPE);
    List<Account> accounts = new ArrayList<Account>(Arrays.asList(accountArray));
    accounts.remove(chosenAccount);

    ImageView coverImageView = (ImageView) chosenAccountView
            .findViewById(com.saarang.samples.apps.iosched.R.id.profile_cover_image);
    ImageView profileImageView = (ImageView) chosenAccountView
            .findViewById(com.saarang.samples.apps.iosched.R.id.profile_image);
    TextView nameTextView = (TextView) chosenAccountView
            .findViewById(com.saarang.samples.apps.iosched.R.id.profile_name_text);
    TextView email = (TextView) chosenAccountView
            .findViewById(com.saarang.samples.apps.iosched.R.id.profile_email_text);
    mExpandAccountBoxIndicator = (ImageView) findViewById(
            com.saarang.samples.apps.iosched.R.id.expand_account_box_indicator);

    String name = AccountUtils.getPlusName(this);
    if (name == null) {
        nameTextView.setVisibility(View.GONE);
    } else {
        nameTextView.setVisibility(View.VISIBLE);
        nameTextView.setText(name);
    }

    String imageUrl = AccountUtils.getPlusImageUrl(this);
    if (imageUrl != null) {
        mImageLoader.loadImage(imageUrl, profileImageView);
    }

    String coverImageUrl = AccountUtils.getPlusCoverUrl(this);
    if (coverImageUrl != null) {
        mImageLoader.loadImage(coverImageUrl, coverImageView);
    } else {
        coverImageView.setImageResource(R.drawable.bg_cover_2016);
    }

    email.setText(chosenAccount.name);

    if (accounts.isEmpty()) {
        // There's only one account on the device, so no need for a switcher.
        mExpandAccountBoxIndicator.setVisibility(View.GONE);
        mAccountListContainer.setVisibility(View.GONE);
        chosenAccountView.setEnabled(false);
        return;
    }

    chosenAccountView.setEnabled(true);

    mExpandAccountBoxIndicator.setVisibility(View.VISIBLE);
    chosenAccountView.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            mAccountBoxExpanded = !mAccountBoxExpanded;
            setupAccountBoxToggle();
        }
    });
    setupAccountBoxToggle();

    populateAccountList(accounts);
}

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

/**
 * populates the avatar drawer array with the first three ownCloud {@link Account}s while the first element is
 * always the current account./*from   w w w  . ja  va  2 s  .c  o m*/
 */
private void populateDrawerOwnCloudAccounts() {
    mAccountsWithAvatars = new Account[3];
    Account[] accountsAll = AccountManager.get(this).getAccountsByType(MainApp.getAccountType());
    Account currentAccount = AccountUtils.getCurrentOwnCloudAccount(this);

    mAccountsWithAvatars[0] = currentAccount;
    int j = 0;
    for (int i = 1; i <= 2 && i < accountsAll.length && j < accountsAll.length; j++) {
        if (!currentAccount.equals(accountsAll[j])) {
            mAccountsWithAvatars[i] = accountsAll[j];
            i++;
        }
    }
}

From source file:com.ntsync.android.sync.client.NetworkUtilities.java

/**
 * /*from   www .  j a v  a 2  s  . c  o m*/
 * @param authtoken
 * @return KeySalt and KeyCheck. null if server was returning nothing
 * @throws IOException
 * @throws AuthenticationException
 * @throws AuthenticatorException
 * @throws OperationCanceledException
 * @throws ServerException
 * @throws NetworkErrorException
 */
public static byte[] getKeySalt(Context context, String accountName, String authtoken)
        throws AuthenticationException, OperationCanceledException, ServerException, NetworkErrorException {

    boolean retry;
    int retryCount = 0;
    String currAuthtoken = authtoken;
    byte[] pwdSalt = null;
    do {
        retry = false;
        final HttpGet get = new HttpGet(PWDSALT_URI);
        HttpEntity entity = null;
        try {
            final HttpResponse resp = getHttpClient(context).execute(get,
                    createHttpContext(accountName, currAuthtoken));
            entity = resp.getEntity();
            int statusCode = resp.getStatusLine().getStatusCode();
            if (statusCode == HttpStatus.SC_OK) {
                byte[] respBytes = EntityUtils.toByteArray(entity);
                if (BuildConfig.DEBUG) {
                    Log.v(TAG, "Get Response-Lenght:" + (respBytes != null ? respBytes.length : "null"));
                }
                pwdSalt = respBytes == null || respBytes.length == 0 ? null : respBytes;
            } else if (statusCode == HttpStatus.SC_UNAUTHORIZED) {
                AccountManager accountManager = AccountManager.get(context);
                currAuthtoken = retryAuthentification(retryCount, accountManager, currAuthtoken, accountName,
                        resp);
                retry = true;
            } else {
                throw new ServerException("Server error in query getPwdSalt: " + resp.getStatusLine());
            }
        } catch (IOException ex) {
            throw new NetworkErrorException(ex);
        } finally {
            consumeContent(entity);
        }
        retryCount++;
    } while (retry);
    return pwdSalt;
}

From source file:com.google.android.apps.paco.ExperimentExecutorCustomRendering.java

private String findAccount(String userEmail) {
    String domainName = null;/*from w w w . j  av a  2  s . co  m*/
    if (userEmail.startsWith("@")) {
        domainName = userEmail.substring(1);
    }
    Account[] accounts = AccountManager.get(this).getAccounts();
    for (Account account : accounts) {
        if (userEmail == null || userEmail.length() == 0) {
            return account.name; // return first
        }

        if (domainName != null) {
            int atIndex = account.name.indexOf('@');
            if (atIndex != -1) {
                String accountDomain = account.name.substring(atIndex + 1);
                if (accountDomain.equals(domainName)) {
                    return account.name;
                }
            }
        }
    }
    return "";
}

From source file:com.microsoft.windowsazure.mobileservices.MobileServiceClient.java

/**
 * Invokes Microsoft Azure Mobile Service authentication using a the Google
 * account registered in the device//from  ww  w.  j  a  v  a2 s . co  m
 *
 * @param activity The activity that triggered the authentication
 * @param scopes   The scopes used as authentication token type for login
 */
public ListenableFuture<MobileServiceUser> loginWithGoogleAccount(Activity activity, String scopes) {
    AccountManager acMgr = AccountManager.get(activity.getApplicationContext());
    Account[] accounts = acMgr.getAccountsByType(GOOGLE_ACCOUNT_TYPE);

    Account account;
    if (accounts.length == 0) {
        account = null;
    } else {
        account = accounts[0];
    }

    return loginWithGoogleAccount(activity, account, scopes);
}

From source file:mobile.tiis.appv2.LoginActivity.java

/**
 * This method will take the url built to use the webservice
 * and will try to parse JSON from the webservice stream to get
 * the user and password if they are correct or not. In case correct, fills
 * the Android Account Manager./*from ww  w .  j  a v  a 2 s  .com*/
 *
 * <p>This method will throw a Toast message when user and password
 * are not valid
 *
 */

protected void startWebService(final CharSequence loginURL, final String username, final String password) {
    client.setBasicAuth(username, password, true);

    //new handler in case of login error in the thread
    handler = new Handler();

    Thread thread = new Thread(new Runnable() {
        public void run() {
            try {
                int balanceCounter = 0;
                DefaultHttpClient httpClient = new DefaultHttpClient();
                HttpGet httpGet = new HttpGet(loginURL.toString());
                Utils.writeNetworkLogFileOnSD(
                        Utils.returnDeviceIdAndTimestamp(getApplicationContext()) + loginURL.toString());
                httpGet.setHeader("Authorization", "Basic "
                        + Base64.encodeToString((username + ":" + password).getBytes(), Base64.NO_WRAP));
                HttpResponse httpResponse = httpClient.execute(httpGet);
                InputStream inputStream = httpResponse.getEntity().getContent();
                Log.d("", loginURL.toString());

                ByteArrayInputStream bais = Utils.getMultiReadInputStream(inputStream);
                Utils.writeNetworkLogFileOnSD(Utils.returnDeviceIdAndTimestamp(getApplicationContext())
                        + Utils.getStringFromInputStreamAndLeaveStreamOpen(bais));
                bais.reset();
                JsonFactory factory = new JsonFactory();
                JsonParser jsonParser = factory.createJsonParser(bais);
                JsonToken token = jsonParser.nextToken();

                if (token == JsonToken.START_OBJECT) {
                    balanceCounter++;
                    boolean idNextToHfId = false;
                    while (!(balanceCounter == 0)) {
                        token = jsonParser.nextToken();

                        if (token == JsonToken.START_OBJECT) {
                            balanceCounter++;
                        } else if (token == JsonToken.END_OBJECT) {
                            balanceCounter--;
                        } else if (token == JsonToken.FIELD_NAME) {
                            String object = jsonParser.getCurrentName();
                            switch (object) {
                            case "HealthFacilityId":
                                token = jsonParser.nextToken();
                                app.setLoggedInUserHealthFacilityId(jsonParser.getText());
                                Log.d("", "healthFacilityId is: " + jsonParser.getText());
                                idNextToHfId = true;
                                break;
                            case "Firstname":
                                token = jsonParser.nextToken();
                                app.setLoggedInFirstname(jsonParser.getText());
                                Log.d("", "firstname is: " + jsonParser.getText());
                                break;
                            case "Lastname":
                                token = jsonParser.nextToken();
                                app.setLoggedInLastname(jsonParser.getText());
                                Log.d("", "lastname is: " + jsonParser.getText());
                                break;
                            case "Username":
                                token = jsonParser.nextToken();
                                app.setLoggedInUsername(jsonParser.getText());
                                Log.d("", "username is: " + jsonParser.getText());
                                break;
                            case "Lastlogin":
                                token = jsonParser.nextToken();
                                Log.d("", "lastlogin is: " + jsonParser.getText());
                                break;
                            case "Id":
                                if (idNextToHfId) {
                                    token = jsonParser.nextToken();
                                    app.setLoggedInUserId(jsonParser.getText());
                                    Log.d("", "Id is: " + jsonParser.getText());
                                }
                                break;
                            default:
                                break;
                            }
                        }
                    }

                    Account account = new Account(username, ACCOUNT_TYPE);
                    AccountManager accountManager = AccountManager.get(LoginActivity.this);
                    //                        boolean accountCreated = accountManager.addAccountExplicitly(account, LoginActivity.this.password, null);
                    boolean accountCreated = accountManager.addAccountExplicitly(account, password, null);

                    Bundle extras = LoginActivity.this.getIntent().getExtras();
                    if (extras != null) {
                        if (accountCreated) { //Pass the new account back to the account manager
                            AccountAuthenticatorResponse response = extras
                                    .getParcelable(AccountManager.KEY_ACCOUNT_AUTHENTICATOR_RESPONSE);
                            Bundle res = new Bundle();
                            res.putString(AccountManager.KEY_ACCOUNT_NAME, username);
                            res.putString(AccountManager.KEY_ACCOUNT_TYPE, ACCOUNT_TYPE);
                            res.putString(AccountManager.KEY_PASSWORD, password);
                            response.onResult(res);
                        }
                    }

                    SharedPreferences prefs = PreferenceManager
                            .getDefaultSharedPreferences(getApplicationContext());
                    SharedPreferences.Editor editor = prefs.edit();
                    editor.putBoolean("secondSyncNeeded", true);
                    editor.commit();

                    ContentValues values = new ContentValues();
                    values.put(SQLHandler.SyncColumns.UPDATED, 1);
                    values.put(SQLHandler.UserColumns.FIRSTNAME, app.getLOGGED_IN_FIRSTNAME());
                    values.put(SQLHandler.UserColumns.LASTNAME, app.getLOGGED_IN_LASTNAME());
                    values.put(SQLHandler.UserColumns.HEALTH_FACILITY_ID, app.getLOGGED_IN_USER_HF_ID());
                    values.put(SQLHandler.UserColumns.ID, app.getLOGGED_IN_USER_ID());
                    values.put(SQLHandler.UserColumns.USERNAME, app.getLOGGED_IN_USERNAME());
                    values.put(SQLHandler.UserColumns.PASSWORD, password);
                    databaseHandler.addUser(values);

                    Log.d(TAG, "initiating offline for " + username + " password = " + password);
                    app.initializeOffline(username, password);

                    Intent intent;
                    if (prefs.getBoolean("synchronization_needed", true)) {
                        Log.d("supportLog", "call the loggin second time before the account was found");
                        intent = new Intent(LoginActivity.this, LotSettingsActivity.class);
                    } else {
                        Log.d("supportLog", "call the loggin second time before the account was found");
                        intent = new Intent(LoginActivity.this, LotSettingsActivity.class);
                        evaluateIfFirstLogin(app.getLOGGED_IN_USER_ID());
                    }
                    app.setUsername(username);

                    startActivity(intent);
                }
                //if login failed show error
                else {
                    handler.post(new Runnable() {
                        public void run() {
                            progressDialog.show();
                            progressDialog.dismiss();
                            toastMessage("Login failed.\nPlease check your details!");
                            loginButton.setEnabled(true);
                        }
                    });
                }
            } catch (Exception e) {
                handler.post(new Runnable() {
                    public void run() {
                        progressDialog.show();
                        progressDialog.dismiss();
                        toastMessage("Login failed Login failed.\n"
                                + "Please check your details or your web connectivity");
                        loginButton.setEnabled(true);

                    }
                });
                e.printStackTrace();
            }
        }
    });
    thread.start();

}

From source file:com.pindroid.activity.Main.java

private List<String> getAccountNames() {

    List<String> accountNames = new ArrayList<String>();

    for (Account account : AccountManager.get(this).getAccountsByType(Constants.ACCOUNT_TYPE)) {
        accountNames.add(account.name);/* w  w w  . j  a  va2s  .co  m*/
    }

    return accountNames;
}

From source file:edu.stanford.mobisocial.dungbeetle.DBHelper.java

private String getUserEmail() {
    Account[] accounts = AccountManager.get(mContext).getAccounts();
    String possibleEmail = "NA";
    for (Account account : accounts) {
        if (account.name.length() > 0) {
            possibleEmail = account.name;
        }/*from  w  w w.  j  ava  2 s  .co  m*/
    }
    return possibleEmail;
}

From source file:com.cerema.cloud2.ui.activity.FileActivity.java

/**
 * Invalidates the credentials stored for the current OC account and requests new credentials to the user,
 * navigating to {@link AuthenticatorActivity}
 *
 * @param context   Android Context needed to access the {@link AccountManager}. Received as a parameter
 *                  to make the method accessible to {@link android.content.BroadcastReceiver}s.
 *///from   w  w  w.  j a va 2s  . com
protected void requestCredentialsUpdate(Context context) {

    try {
        /// step 1 - invalidate credentials of current account
        OwnCloudClient client;
        OwnCloudAccount ocAccount = new OwnCloudAccount(getAccount(), context);
        client = (OwnCloudClientManagerFactory.getDefaultSingleton().removeClientFor(ocAccount));
        if (client != null) {
            OwnCloudCredentials cred = client.getCredentials();
            if (cred != null) {
                AccountManager am = AccountManager.get(context);
                if (cred.authTokenExpires()) {
                    am.invalidateAuthToken(getAccount().type, cred.getAuthToken());
                } else {
                    am.clearPassword(getAccount());
                }
            }
        }

        /// step 2 - request credentials to user
        Intent updateAccountCredentials = new Intent(this, AuthenticatorActivity.class);
        updateAccountCredentials.putExtra(AuthenticatorActivity.EXTRA_ACCOUNT, getAccount());
        updateAccountCredentials.putExtra(AuthenticatorActivity.EXTRA_ACTION,
                AuthenticatorActivity.ACTION_UPDATE_EXPIRED_TOKEN);
        updateAccountCredentials.addFlags(Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS);
        startActivity(updateAccountCredentials);

    } catch (com.cerema.cloud2.lib.common.accounts.AccountUtils.AccountNotFoundException e) {
        Toast.makeText(context, R.string.auth_account_does_not_exist, Toast.LENGTH_SHORT).show();
    }

}

From source file:com.ntsync.android.sync.syncadapter.SyncAdapter.java

private void notifyUserPhotoNotSynced(String accountName) {
    Account account = new Account(accountName, Constants.ACCOUNT_TYPE);
    AccountManager acm = AccountManager.get(mContext);
    String synced = acm.getUserData(account, NOTIF_SHOWN_PHOTO_SYNCED);
    if (synced == null) {
        Intent shopIntent = new Intent(mContext, ShopActivity.class);
        shopIntent.putExtra(ShopActivity.PARM_ACCOUNT_NAME, accountName);
        TaskStackBuilder stackBuilder = TaskStackBuilder.create(mContext);
        stackBuilder.addParentStack(ShopActivity.class);
        stackBuilder.addNextIntent(shopIntent);

        NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(mContext)
                .setSmallIcon(Constants.NOTIF_ICON)
                .setContentTitle(getText(R.string.notif_photonotsynced_title)).setContentText(accountName)
                .setAutoCancel(true)/*from   w  ww.  j a v a2  s .com*/
                .setContentIntent(stackBuilder.getPendingIntent(0, PendingIntent.FLAG_UPDATE_CURRENT))
                .setOnlyAlertOnce(true);
        NotificationManager mNotificationManager = (NotificationManager) mContext
                .getSystemService(Context.NOTIFICATION_SERVICE);
        mNotificationManager.notify(Constants.NOTIF_PHOTO_NOT_SYNCED, mBuilder.build());
        acm.setUserData(account, NOTIF_SHOWN_PHOTO_SYNCED, String.valueOf(System.currentTimeMillis()));
    }
}