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.google.android.gm.ay.java

public static boolean w(final Context context, final String s) {
    return a(new android.accounts.Account(s, "com.google"),
            AccountManager.get(context).getAccountsByType("com.google"));
}

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

/**
 * This method will get called when the user presses the login
 * button./*from ww  w  .j a  v a  2s  .co  m*/
 *
 * <p>This method will check with checkRequiredFields to make
 * sure if it will process the click.
 */

public void onClick(View v) {
    Log.d(TAG, "clicked login");
    //get inserted username and password
    username = usernameEditText.getText().toString().trim();
    password = passwordEditText.getText().toString().trim();

    //check if required fields are not empty
    if (checkRequiredFields()) {
        Log.d(TAG, "check passed");
        progressDialog.setMessage("Signing in. \nPlease wait ...");
        progressDialog.setCanceledOnTouchOutside(false);
        progressDialog.setCancelable(false);
        progressDialog.show();

        loginButton.setEnabled(false);
        //continue with device online
        if (Utils.isOnline(LoginActivity.this)) {

            boolean loggedIn = false;
            if (databaseHandler.getAllUsers().size() != 0) {
                //Checking if the user had once logged in
                //check if user is already registered with AccountManager
                AccountManager accountManager = AccountManager.get(LoginActivity.this);
                Account[] accounts = accountManager.getAccountsByType(ACCOUNT_TYPE);

                //go through all accounts found in Account Manager
                for (Account account : accounts) {
                    //if there is a match set login as true and go to Home Activity
                    if (account.name.equalsIgnoreCase(username)
                            && accountManager.getPassword(account).equals(password)) {
                        //Activity mobile.tiis.app.LoginActivity has leaked window error was showing
                        //this piece of code handles it, nonetheless in prod time the error  would not show
                        if (progressDialog != null && progressDialog.isShowing()) {
                            progressDialog.dismiss();
                        }

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

                        Intent intent = new Intent(LoginActivity.this, LotSettingsActivity.class);

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

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

                        app.setUsername(username);
                        Log.d("supportLog", "call the loggin first time before the account was found");
                        startActivity(intent);
                        loggedIn = true;
                    }
                }
            } else {
                SharedPreferences preferenceManager = PreferenceManager
                        .getDefaultSharedPreferences(getApplicationContext());
                preferenceManager.edit().putBoolean("synchronization_needed", true);
            }
            if (!loggedIn) {

                //build webservice url
                StringBuilder webServiceLoginURL = createWebServiceLoginURL(username, password, regId);

                //call web service to pull user info and send to account manager
                try {
                    startWebService(webServiceLoginURL, username, password);
                } catch (NullPointerException e) {
                    startWebService(webServiceLoginURL, username, password);
                }
            }

        } else {

            //check if user is already registered with AccountManager
            AccountManager accountManager = AccountManager.get(LoginActivity.this);
            Account[] accounts = accountManager.getAccountsByType(ACCOUNT_TYPE);
            boolean loggedIn = false;
            if (databaseHandler.getAllUsers().size() != 0) {

                //go through all accounts found in AM
                for (Account account : accounts) {
                    //if there is a match set login as true and go to Home Activity
                    if (account.name.equalsIgnoreCase(username)
                            && accountManager.getPassword(account).equals(password)) {
                        //Activity mobile.tiis.app.LoginActivity has leaked window error was showing
                        //this piece of code handles it, nonetheless in prod time the error  would not show
                        if (progressDialog != null && progressDialog.isShowing()) {
                            progressDialog.dismiss();
                        }

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

                        Intent intent = new Intent(LoginActivity.this, LotSettingsActivity.class);
                        app.setUsername(username);
                        Log.d(TAG, "initiating offline for " + username + " password = " + password);
                        app.initializeOffline(username, password);
                        startActivity(intent);
                        loggedIn = true;
                    }
                }
            } else {
                SharedPreferences preferenceManager = PreferenceManager
                        .getDefaultSharedPreferences(getApplicationContext());
                preferenceManager.edit().putBoolean("synchronization_needed", true);
            }
            //if login failed, show error
            if (!loggedIn) {
                progressDialog.dismiss();
                toastMessage("Login failed.\nPlease check your details or be online for first login!");
                loginButton.setEnabled(true);
            }
        }
    }
}

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

@Override
public void onCompleted(GraphUser user, Response response) {
    // TODO Auto-generated method stub
    //Log.d("tagaa", "FacebookGetMe: oncomplete me request");

    if (response != null) {

        FacebookRequestError error = response.getError();
        if (error != null) {
            // failed to get user info from facebook - TOAST
            //Log.d("tagaa", "FacebookGetMe: failed to get user info from facebook: " + error);

            Toast.makeText(getApplicationContext(),
                    "Failed to retrieve information from Facebook - OFFLINE mode", Toast.LENGTH_SHORT).show();

            saveState(StateMachine.OFFLINE_STATE);
            saveStatus(StateMachine.ERROR_STATUS);
            saveError(StateMachine.FB_GET_ME_FAILED_ERROR);
            goToBucketListActivity();//from  w  w w. j  a va2 s  . com
            return;
        }
    }

    if (user != null) {

        boolean registered = false;
        final Account account;

        // if we get to this point, we know that the network is OK
        // we can continue server registration

        //Log.d("tagaa", "FacebookGetMe: me = " + user);

        // check whether (com.kidobloom) type account has been created for the fb-userid
        // if account db is empty - create a new account using the fb-userid
        // else if an account already exists, check to see if it matches the current fb-userid
        // if account exists and matches the fb-userid, do nothing
        // otherwise replace the account with the new fb-userid
        AccountManager accountManager = AccountManager.get(getApplicationContext());
        Account[] accounts = accountManager.getAccountsByType("com.kiddobloom");

        if (accounts.length <= 0) {
            //Log.d("tagaa", "FacebookGetMe: no account exists");
            // create a new account
            account = new Account(user.getId(), Constants.ACCOUNT_TYPE);
            am.addAccountExplicitly(account, null, null);
            ContentResolver.setSyncAutomatically(account, MyContentProvider.AUTHORITY, true);
            registered = false;
        } else {
            // get the first account
            //Log.d("tagaa", "FacebookGetMe: account = " + accounts[0].name);

            if (accounts[0].name.equals(user.getId())) {
                registered = true;
                //Log.d("tagaa", "FacebookGetMe: account for facebookId = " + user.getId() + " already created");
            } else {
                //Log.d("tag", "FacebookGetMe: user switched account");
                // remove the account first
                am.removeAccount(accounts[0], null, null);

                // add new account with the new facebook userid
                account = new Account(user.getId(), Constants.ACCOUNT_TYPE);
                am.addAccountExplicitly(account, null, null);
                ContentResolver.setSyncAutomatically(account, MyContentProvider.AUTHORITY, true);

                // update the registered flag so facebook ID gets re-registered
                registered = false;
            }
        }

        // at this point, an account should already be created
        // store the userid and registered boolean in preferences db
        saveFbUserId(user.getId());
        saveUserIdRegistered(registered);

        saveState(StateMachine.FB_GET_FRIENDS_STATE);
        saveStatus(StateMachine.TRANSACTING_STATUS);
        saveError(StateMachine.NO_ERROR);

        // request facebook friends list
        Request.executeMyFriendsRequestAsync(response.getRequest().getSession(), this);

    } else {
        // throw an exception here - facebook does not indicate error but user is null 
        //Log.d("tagaa", "FacebookGetMe: failed to get user info from facebook - OFFLINE mode");

        Toast.makeText(getApplicationContext(), "Failed to retrieve information from Facebook",
                Toast.LENGTH_SHORT).show();

        saveState(StateMachine.OFFLINE_STATE);
        saveStatus(StateMachine.ERROR_STATUS);
        saveError(StateMachine.FB_GET_ME_FAILED_ERROR);
        goToBucketListActivity();
    }
}

From source file:com.xiaomi.account.utils.SysHelper.java

public static boolean deleteBindedDevice(Context context, String devId) {
    boolean z = false;
    Account account = ExtraAccountManager.getXiaomiAccount(context);
    if (account != null) {
        AccountManager am = AccountManager.get(context);
        int count = 0;
        while (count < 2) {
            String authToken = getAuthToken(am, account, com.xiaomi.account.Constants.DEVICE_INFO_SID);
            ExtendedAuthToken extendedAuthToken = ExtendedAuthToken.parse(authToken);
            if (extendedAuthToken == null) {
                break;
            }/*  w  w  w . j a  va 2s  .  co m*/
            String serviceToken = extendedAuthToken.authToken;
            String security = extendedAuthToken.security;
            if (serviceToken == null || security == null) {
                break;
            }
            try {
                z = CloudHelper.deleteBindedDevice(account.name,
                        am.getUserData(account, Constants.KEY_ENCRYPTED_USER_ID), devId, serviceToken,
                        security);
                break;
            } catch (AuthenticationFailureException e) {
                Log.e(TAG, "auth failure when delete device", e);
                am.invalidateAuthToken(account.type, authToken);
                count++;
            }
        }
    } else {
        Log.w(TAG, "no Xiaomi account");
    }
    return z;
}

From source file:ru.orangesoftware.financisto2.activity.FlowzrSyncActivity.java

protected void restoreUIFromPref() {
    SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
    lastSyncLocalTimestamp = preferences.getLong(FlowzrSyncOptions.PROPERTY_LAST_SYNC_TIMESTAMP, 0);
    AccountManager accountManager = AccountManager.get(getApplicationContext());
    Account[] accounts = accountManager.getAccountsByType("com.google");
    for (Account account : accounts) {
        if (preferences.getString(FlowzrSyncOptions.PROPERTY_USE_CREDENTIAL, "").equals(account.name)) {
            useCredential = account;/*from w  w  w  .  j  a  va 2s  .c om*/
        }
    }
    TextView tv = (TextView) findViewById(R.id.sync_was);
    tv.setText(getString(R.string.flowzr_sync_was) + " " + new Date(lastSyncLocalTimestamp).toLocaleString());
}

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

/**
 * depending on the #mIsAccountChooserActive flag shows the account chooser or the standard menu.
 *///  w ww.  j  av  a2 s  . com
private void showMenu() {
    if (mNavigationView != null) {
        final int accountCount = AccountManager.get(this).getAccountsByType(MainApp.getAccountType()).length;

        if (mIsAccountChooserActive) {
            mAccountChooserToggle.setImageResource(R.drawable.ic_up);
            mNavigationView.getMenu().setGroupVisible(R.id.drawer_menu_accounts, true);
            mNavigationView.getMenu().setGroupVisible(R.id.drawer_menu_standard, false);
            mNavigationView.getMenu().setGroupVisible(R.id.drawer_menu_settings_etc, false);
            if (mDrawerLogo != null && accountCount > USER_ITEMS_ALLOWED_BEFORE_REMOVING_CLOUD)
                mDrawerLogo.setVisibility(View.GONE);
        } else {
            mAccountChooserToggle.setImageResource(R.drawable.ic_down);
            mNavigationView.getMenu().setGroupVisible(R.id.drawer_menu_accounts, false);
            mNavigationView.getMenu().setGroupVisible(R.id.drawer_menu_standard, true);
            mNavigationView.getMenu().setGroupVisible(R.id.drawer_menu_settings_etc, true);
            if (mDrawerLogo != null)
                mDrawerLogo.setVisibility(View.VISIBLE);
        }
    }
}

From source file:com.mikecorrigan.bohrium.pubsub.RegistrationClient.java

public static List<String> getAccounts(final Context context, final String accountType) {
    Log.v(TAG, "getAccountsByType: accountType=" + accountType);

    final AccountManager mgr = AccountManager.get(context);
    ArrayList<String> result = new ArrayList<>();
    final Account[] accounts = mgr.getAccounts();
    for (final Account account : accounts) {
        Log.v(TAG, "accountName=" + account.name);
        if (account.type.equals(accountType)) {
            result.add(account.name);//from ww w .  ja v  a  2 s  .  co m
        }
    }

    return result;
}

From source file:com.jdom.get.stuff.done.android.AndroidSyncStrategy.java

private Account getAccount() {
    Account[] accounts = AccountManager.get(activity).getAccountsByType(Constants.GOOGLE_ACCOUNT_PREFIX);
    for (Account account : accounts) {
        if (account.name.equals(contextFactory.getDaoFactory().getApplicationDao().getSyncAccount())) {
            return account;
        }//from  w ww . j  av  a  2 s .c  o  m
    }
    return null;
}

From source file:com.xiaomi.account.utils.SysHelper.java

public static boolean uploadInfoToServer(Context context, HashMap<String, Object> uploadInfo, int uploadType,
        String sid) throws InvalidResponseException, CipherException, IOException,
        AuthenticationFailureException, AccessDeniedException {
    Account account = ExtraAccountManager.getXiaomiAccount(context);
    if (account == null) {
        Log.w(TAG, "no Xiaomi account");
        return false;
    }/*from w ww. j  a  v a2s  . c o  m*/
    AccountManager am = AccountManager.get(context);
    ExtendedAuthToken extToken = ExtendedAuthToken.parse(getAuthToken(am, account, sid));
    if (extToken == null) {
        Log.d(TAG, "uploadInfoToServer extToken is null");
        return false;
    }
    String serviceToken = extToken.authToken;
    String security = extToken.security;
    String encryptedUserId = am.getUserData(account, Constants.KEY_ENCRYPTED_USER_ID);
    switch (uploadType) {
    case LicenseActivity.PRIVACY_POLICY /*0*/:
        return CloudHelper.uploadDeviceInfo(account.name, encryptedUserId, serviceToken, security, uploadInfo);
    case SdkReturnCode.LOW_SDK_VERSION /*1*/:
        return CloudHelper.uploadXiaomiUserInfo(account.name, encryptedUserId, serviceToken, security,
                uploadInfo);
    default:
        return false;
    }
}

From source file:com.pindroid.client.PinboardApi.java

/**
 * Performs an api call to Pinboard's http based api methods.
 * /*from  w  ww . j  a  va2 s .  c om*/
 * @param url URL of the api method to call.
 * @param params Extra parameters included in the api call, as specified by different methods.
 * @param account The account being synced.
 * @param context The current application context.
 * @return A String containing the response from the server.
 * @throws IOException If a server error was encountered.
 * @throws AuthenticationException If an authentication error was encountered.
 * @throws TooManyRequestsException 
 * @throws PinboardException 
 */
private static InputStream PinboardApiCall(String url, TreeMap<String, String> params, Account account,
        Context context)
        throws IOException, AuthenticationException, TooManyRequestsException, PinboardException {

    final AccountManager am = AccountManager.get(context);

    if (account == null)
        throw new AuthenticationException();

    final String username = account.name;
    String authtoken = "00000000000000000000"; // need to provide a sane default value, since a token that is too short causes a 500 error instead of 401

    try {
        String tempAuthtoken = am.blockingGetAuthToken(account, Constants.AUTHTOKEN_TYPE, true);
        if (tempAuthtoken != null)
            authtoken = tempAuthtoken;
    } catch (Exception e) {
        e.printStackTrace();
        throw new AuthenticationException("Error getting auth token");
    }

    params.put("auth_token", username + ":" + authtoken);

    final Uri.Builder builder = new Uri.Builder();
    builder.scheme(SCHEME);
    builder.authority(PINBOARD_AUTHORITY);
    builder.appendEncodedPath(url);
    for (String key : params.keySet()) {
        builder.appendQueryParameter(key, params.get(key));
    }

    String apiCallUrl = builder.build().toString();

    Log.d("apiCallUrl", apiCallUrl);
    final HttpGet post = new HttpGet(apiCallUrl);

    post.setHeader("User-Agent", "PinDroid");
    post.setHeader("Accept-Encoding", "gzip");

    final DefaultHttpClient client = (DefaultHttpClient) HttpClientFactory.getThreadSafeClient();

    final HttpResponse resp = client.execute(post);

    final int statusCode = resp.getStatusLine().getStatusCode();

    if (statusCode == HttpStatus.SC_OK) {

        final HttpEntity entity = resp.getEntity();

        InputStream instream = entity.getContent();

        final Header encoding = entity.getContentEncoding();

        if (encoding != null && encoding.getValue().equalsIgnoreCase("gzip")) {
            instream = new GZIPInputStream(instream);
        }

        return instream;
    } else if (statusCode == HttpStatus.SC_UNAUTHORIZED) {
        am.invalidateAuthToken(Constants.AUTHTOKEN_TYPE, authtoken);

        try {
            authtoken = am.blockingGetAuthToken(account, Constants.AUTHTOKEN_TYPE, true);
        } catch (Exception e) {
            e.printStackTrace();
            throw new AuthenticationException("Invalid auth token");
        }

        throw new AuthenticationException();
    } else if (statusCode == Constants.HTTP_STATUS_TOO_MANY_REQUESTS) {
        throw new TooManyRequestsException(300);
    } else if (statusCode == HttpStatus.SC_REQUEST_URI_TOO_LONG) {
        throw new PinboardException();
    } else {
        throw new IOException();
    }
}