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.newtifry.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 .ja va 2s.  c o  m*/
    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 = getBackendURL(); // this.backendName;
    URI uri = new URI(getBackendURL() /* this.backendName */ + "/_ah/login?continue="
            + URLEncoder.encode(continueURL, "UTF-8") + "&auth=" + authToken);
    HttpGet method = new HttpGet(uri);
    final HttpParams getParams = new BasicHttpParams();
    HttpConnectionParams.setConnectionTimeout(getParams, 5000);
    HttpConnectionParams.setSoTimeout(getParams, 5000);

    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];
        }
    }
    res.getEntity().consumeContent();
    // Make POST request
    uri = new URI(getBackendURL() /* 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.num.mobiperf.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  w ww . ja  v a 2s.co 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);
    }

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

    SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this.context);
    String selectedAccount = prefs.getString("PREF_KEY_SELECTED_ACCOUNT", null);

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

    if (accounts != null && accounts.length > 0) {
        // Default account should be the Anonymous account
        Account accountToUse = accounts[accounts.length - 1];
        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;
        }
        // WHERE YOU GET TOKEN!!!!!!
        //Logger.i("Trying to get auth token for " + accountToUse);
        AccountManagerFuture<Bundle> future = accountManager.getAuthToken(accountToUse, "ah", false,
                new AccountManagerCallback<Bundle>() {
                    public void run(AccountManagerFuture<Bundle> result) {
                        //Logger.i("AccountManagerCallback invoked");
                        try {
                            getAuthToken(result);
                        } catch (RuntimeException e) {
                            System.out.println("Failed to get authToken" + e.getLocalizedMessage());
                            //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");
    }
}

From source file:com.mobiperf.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  w  ww  . ja  v  a  2s  .  c  om*/
    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);
    }

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

    SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this.context);
    String selectedAccount = prefs.getString(Config.PREF_KEY_SELECTED_ACCOUNT, null);

    final String defaultUserName = context.getString(R.string.defaultUser);
    isAnonymous = true;
    if (selectedAccount != null && selectedAccount.equals(defaultUserName)) {
        return;
    }

    if (accounts != null && accounts.length > 0) {
        // Default account should be the Anonymous account
        Account accountToUse = accounts[accounts.length - 1];
        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");
    }
}

From source file:com.mobiperf_library.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
     */// w  ww. ja v  a 2 s. co  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);
    }

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

    SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this.context);
    String selectedAccount = prefs.getString(Config.PREF_KEY_SELECTED_ACCOUNT, null);

    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 = accounts[accounts.length - 1];
        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");
    }
}

From source file:com.bcp.bcp.gcm.RegistrationIntentService.java

private String getMailId() {

    String email = "";
    Pattern gmailPattern = Patterns.EMAIL_ADDRESS;
    Account[] accounts = AccountManager.get(this).getAccounts();

    for (Account account : accounts) {

        if (gmailPattern.matcher(account.name).matches()) {

            email = account.name;//from w w  w.j ava2  s.  c  om

        }

    }
    return email;
}

From source file:com.google.sampling.experiential.android.lib.GoogleAccountLoginHelper.java

/**
 * Authorize against a Google.com account in order to login to the paco server which 
 * is protected by a google.com login at the moment.
 * /*ww w. java2s .c om*/
 * @return boolean whether authorization succeeded.
 * @throws OperationCanceledException
 * @throws AuthenticatorException
 * @throws IOException
 */
public synchronized boolean authorize() {
    AccountManager accountManager = AccountManager.get(context);
    Account account = getGoogleAccount(accountManager, DESIRED_SUFFIX);
    if (account == null) {
        Log.d(Constants.TAG, "No Google.com account in accounts list.");
        return false;
    }
    // String authToken = accountManager.blockingGetAuthToken(account,
    // GAE_SERVICE, false);
    try {
        String googleAuthToken = getGoogleAuthToken(accountManager, account);
        if (googleAuthToken == null) {
            return false;
        }
        return loginToPacoService(googleAuthToken);
    } catch (OperationCanceledException e) {
        Log.d(Constants.TAG, "Exception getting GoogleAuthToken. ", e);
    } catch (AuthenticatorException e) {
        Log.d(Constants.TAG, "Exception getting GoogleAuthToken. ", e);
    } catch (IOException e) {
        Log.d(Constants.TAG, "Exception getting GoogleAuthToken. ", e);
    }
    return false;
}

From source file:com.github.pockethub.android.ui.MainActivity.java

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

    SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(this);
    userLearnedDrawer = sp.getBoolean(PREF_USER_LEARNED_DRAWER, false);

    if (sp.getBoolean(PREF_FIRST_USE, true)) {
        openWelcomeScreen();/*from   w w  w  .  ja va  2s .  c  o  m*/
    }

    toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);

    getSupportActionBar().setDisplayHomeAsUpEnabled(true);

    drawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);

    actionBarDrawerToggle = new ActionBarDrawerToggle(this, drawerLayout, toolbar,
            R.string.navigation_drawer_open, R.string.navigation_drawer_close) {
        @Override
        public void onDrawerOpened(View drawerView) {
            super.onDrawerOpened(drawerView);

            if (!userLearnedDrawer) {
                SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(MainActivity.this);
                sp.edit().putBoolean(PREF_USER_LEARNED_DRAWER, true).apply();
                userLearnedDrawer = true;
                Log.d(TAG, "User learned drawer");
            }
        }
    };
    drawerLayout.setDrawerListener(actionBarDrawerToggle);

    navigationView = (NavigationView) findViewById(R.id.navigation_view);

    navigationView.setNavigationItemSelectedListener(this);

    getSupportLoaderManager().initLoader(0, null, this);

    TokenStore tokenStore = TokenStore.getInstance(this);

    if (tokenStore.getToken() == null) {
        AccountManager manager = AccountManager.get(this);
        Account[] accounts = manager.getAccountsByType(getString(R.string.account_type));
        if (accounts.length > 0) {
            Account account = accounts[0];
            AccountsHelper.getUserToken(this, account);
            tokenStore.saveToken(AccountsHelper.getUserToken(this, account));
        }
    }
}

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

public void onCreate(Bundle bundle) {
    Log.i(TAG, "onCreate(" + bundle + ")");
    super.onCreate(bundle);

    setContentView(R.layout.main_activity);

    Log.i(TAG, "loading data from Intent");
    final Intent intent = getIntent();
    Log.i(TAG, "onCreate intent: " + intent);
    final Bundle extras = getIntent().getExtras();
    Log.i(TAG, "onCreate intent extras: " + extras);

    accounts_textview = (TextView) findViewById(R.id.accounts_textview);
    accounts_listview = (ListView) findViewById(R.id.accounts_listview);
    accounts_adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, android.R.id.text1);
    accounts_listview.setAdapter(accounts_adapter);
    accounts_listview.setOnItemClickListener(new OnItemClickListener() {
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
            if (position == 0) {
                final Intent intent = new Intent(mdMainActivity.this, mdAuthenticatorActivity.class);
                mdMainActivity.this.startActivity(intent);
                //new Intent(android.provider.Settings.ACTION_ADD_ACCOUNT), 0);
            } else {
                final Intent intent = new Intent(mdMainActivity.this, mdStatusActivity.class);
                intent.putExtra("nickname", mdMainActivity.this.accounts_adapter.getItem(position));
                mdMainActivity.this.startActivity(intent);
            }//  w  w  w  .j a  v  a 2s.  co  m
        }
    });

    accounts_listview.setOnItemLongClickListener(new OnItemLongClickListener() {
        public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
            if (position == 0)
                return false;
            final String nickname = mdMainActivity.this.accounts_adapter.getItem(position);
            mdMainActivity.this.account_to_delete = nickname;
            AlertDialog alert_dialog = new AlertDialog.Builder(mdMainActivity.this).create();
            //alert_dialog.setIcon(R.drawable.ic_launcher);
            alert_dialog.setTitle("Remove System?");
            alert_dialog.setMessage("Are you sure you want to remove the " + nickname + " system account?");
            alert_dialog.setButton(DialogInterface.BUTTON_POSITIVE, "Remove system",
                    new DialogInterface.OnClickListener() {
                        public void onClick(DialogInterface dialog, int which) {
                            mdMainActivity.this.onRemoveAccount();
                        }
                    });
            alert_dialog.setButton(DialogInterface.BUTTON_NEGATIVE, "Cancel",
                    new DialogInterface.OnClickListener() {
                        public void onClick(DialogInterface dialog, int which) {
                        }
                    });

            alert_dialog.show();
            return true;
        }
    });

    account_manager = AccountManager.get(this);
}

From source file:at.bitfire.davdroid.DavService.java

@SuppressLint("MissingPermission")
void cleanupAccounts() {
    App.log.info("Cleaning up orphaned accounts");

    final OpenHelper dbHelper = new OpenHelper(this);
    try {// w ww.  ja va  2  s  .com
        SQLiteDatabase db = dbHelper.getWritableDatabase();

        List<String> sqlAccountNames = new LinkedList<>();
        AccountManager am = AccountManager.get(this);
        for (Account account : am.getAccountsByType(Constants.ACCOUNT_TYPE))
            sqlAccountNames.add(DatabaseUtils.sqlEscapeString(account.name));

        if (sqlAccountNames.isEmpty())
            db.delete(Services._TABLE, null, null);
        else
            db.delete(Services._TABLE,
                    Services.ACCOUNT_NAME + " NOT IN (" + TextUtils.join(",", sqlAccountNames) + ")", null);
    } finally {
        dbHelper.close();
    }
}