Example usage for android.accounts Account Account

List of usage examples for android.accounts Account Account

Introduction

In this page you can find the example usage for android.accounts Account Account.

Prototype

public Account(@NonNull Account other, @NonNull String accessId) 

Source Link

Usage

From source file:at.bitfire.davdroid.syncadapter.AccountDetailsFragment.java

void addAccount() {
    ServerInfo serverInfo = (ServerInfo) getArguments().getSerializable(KEY_SERVER_INFO);
    String accountName = editAccountName.getText().toString();

    AccountManager accountManager = AccountManager.get(getActivity());
    Account account = new Account(accountName, Constants.ACCOUNT_TYPE);
    Bundle userData = new Bundle();
    userData.putString(Constants.ACCOUNT_KEY_BASE_URL, serverInfo.getBaseURL());
    userData.putString(Constants.ACCOUNT_KEY_USERNAME, serverInfo.getUserName());
    userData.putString(Constants.ACCOUNT_KEY_AUTH_PREEMPTIVE, Boolean.toString(serverInfo.isAuthPreemptive()));

    boolean syncContacts = false;
    for (ServerInfo.ResourceInfo addressBook : serverInfo.getAddressBooks())
        if (addressBook.isEnabled()) {
            userData.putString(Constants.ACCOUNT_KEY_ADDRESSBOOK_PATH, addressBook.getPath());
            ContentResolver.setIsSyncable(account, ContactsContract.AUTHORITY, 1);
            syncContacts = true;//w ww .j a  v a2 s  .c  o m
            continue;
        }
    if (syncContacts) {
        ContentResolver.setIsSyncable(account, ContactsContract.AUTHORITY, 1);
        ContentResolver.setSyncAutomatically(account, ContactsContract.AUTHORITY, true);
    } else
        ContentResolver.setIsSyncable(account, ContactsContract.AUTHORITY, 0);

    if (accountManager.addAccountExplicitly(account, serverInfo.getPassword(), userData)) {
        // account created, now create calendars
        ContentResolver.setIsSyncable(account, "com.android.calendar", 0);

        getActivity().finish();
    } else
        Toast.makeText(getActivity(), "Couldn't create account (account with this name already existing?)",
                Toast.LENGTH_LONG).show();
}

From source file:com.lvlstudios.android.gtmessage.AppEngineClient.java

private HttpResponse makeRequestNoRetry(String urlPath, List<NameValuePair> params, boolean newToken)
        throws Exception {
    Log.d(TAG, "AppEngineClient.makeRequestNoRetry: " + urlPath);
    // Get auth token for account - needs to be Google account so can piggy back on Google services.
    Account account = new Account(mAccountName, "com.google");
    String authToken = getAuthToken(mContext, account);

    if (newToken) { // invalidate the cached token
        AccountManager accountManager = AccountManager.get(mContext);
        accountManager.invalidateAuthToken(account.type, authToken);
        authToken = getAuthToken(mContext, account);
    }/*from  w w  w  .ja v a 2  s .  c o m*/

    // Get ACSID cookie
    DefaultHttpClient client = new DefaultHttpClient();
    String continueURL = BASE_URL;
    URI uri = new URI(AUTH_URL + "?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");
    if (res.getStatusLine().getStatusCode() != 302 || headers.length == 0) {
        Log.w(TAG, "AppEngineClient " + urlPath + " authentication failed: "
                + res.getStatusLine().getStatusCode());
        return res;
    }

    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(BASE_URL + 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);
    if (res.getStatusLine().getStatusCode() != 200) {
        Log.e(TAG, "AppEngineClient " + urlPath + " POST status: " + res.getStatusLine().getStatusCode());
    }
    return res;
}

From source file:com.google.android.apps.chrometophone.AppEngineClient.java

private HttpResponse makeRequestNoRetry(String urlPath, List<NameValuePair> params, boolean newToken)
        throws Exception {
    // Get auth token for account
    Account account = new Account(mAccountName, "com.google");
    String authToken = getAuthToken(mContext, account);

    if (newToken) { // invalidate the cached token
        AccountManager accountManager = AccountManager.get(mContext);
        accountManager.invalidateAuthToken(account.type, authToken);
        authToken = getAuthToken(mContext, account);
    }/*from   w w w . j  av  a2 s . c  om*/

    DefaultHttpClient client = new DefaultHttpClient();
    String baseUrl;
    URI uri;
    String ascidCookie = null;
    HttpResponse res;
    if (BASE_LOCAL_URL == null) {
        // Get ACSID cookie so it can be used to authenticate on AppEngine
        String continueURL = BASE_URL;
        uri = new URI(AUTH_URL + "?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);

        res = client.execute(method);
        Header[] headers = res.getHeaders("Set-Cookie");
        if (res.getStatusLine().getStatusCode() != 302 || headers.length == 0) {
            return res;
        }

        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];
            }
        }
        baseUrl = BASE_URL;
    } else {
        // local app server, pass user directly
        baseUrl = BASE_LOCAL_URL;
        params.add(new BasicNameValuePair("account", account.name));
    }

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

From source file:org.birthdayadapter.util.AccountListLoader.java

/**
 * This is where the bulk of our work is done. This function is called in a background thread
 * and should generate a new set of data to be published by the loader.
 *//*from  www .j a va2 s .  c  o m*/
@Override
public List<AccountListEntry> loadInBackground() {
    // Retrieve all accounts that are actively used for contacts
    HashSet<Account> activeContactAccounts = new HashSet<>();
    Cursor cursor = null;
    try {
        cursor = getContext().getContentResolver()
                .query(ContactsContract.RawContacts.CONTENT_URI, new String[] {
                        ContactsContract.RawContacts.ACCOUNT_NAME, ContactsContract.RawContacts.ACCOUNT_TYPE },
                        null, null, null);

        if (cursor != null && cursor.getCount() > 0) {
            while (cursor.moveToNext()) {
                Account account = new Account(
                        cursor.getString(cursor.getColumnIndex(ContactsContract.RawContacts.ACCOUNT_NAME)),
                        cursor.getString(cursor.getColumnIndex(ContactsContract.RawContacts.ACCOUNT_TYPE)));
                activeContactAccounts.add(account);
            }
            cursor.close();
        }
    } catch (Exception e) {
        Log.e(Constants.TAG, "Error retrieving accounts!", e);
    } finally {
        if (cursor != null) {
            cursor.close();
        }
    }

    // get current blacklist from preferences
    HashSet<Account> accountBlacklist = ProviderHelper.getAccountBlacklist(getContext());

    Log.d(Constants.TAG, "accountBlacklist" + accountBlacklist);
    for (Account account : accountBlacklist) {
        Log.d(Constants.TAG, "accountBlacklist acc type: " + account.type + ", name: " + account.name);
    }

    // Build List<AccountListEntry> by getting AuthenticatorDescription for every Account
    AccountManager manager = AccountManager.get(getContext());
    AuthenticatorDescription[] descriptions = manager.getAuthenticatorTypes();

    ArrayList<AccountListEntry> entries = new ArrayList<>();
    for (Account account : activeContactAccounts) {
        for (AuthenticatorDescription description : descriptions) {
            if (description.type.equals(account.type)) {
                // add to entries, disable entry if in blacklist
                boolean enabled = !accountBlacklist.contains(account);
                entries.add(new AccountListEntry(getContext(), account, description, enabled));
            }
        }
    }

    // Sort the list.
    Collections.sort(entries, ALPHA_COMPARATOR);

    // Done!
    return entries;
}

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

@Override
public String readToken(Context ctx, String inAuthority) {
    final String authority = inAuthority == null ? Constants.AUTHORITY_DEFAULT : inAuthority;
    AccountManager am = AccountManager.get(ctx);
    return am.peekAuthToken(new Account(Constants.getAccountName(ctx), Constants.getAccountType(ctx)),
            authority);/*from   w  ww  .j a v a2s  .  co  m*/
}

From source file:be.evias.cloudLogin.cloudLoginMainActivity.java

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

    checkConnection();//from   w  w w .ja  v a 2 s  .  c o  m

    mAccountManager = AccountManager.get(this);
    mAccountName = getIntent().getStringExtra(AccountManager.KEY_ACCOUNT_NAME);
    mAccount = new Account(mAccountName, AccountBase.ACCOUNT_TYPE);
    mContext = getBaseContext();
    mPrefs = mContext.getSharedPreferences("cloudlogin", Context.MODE_PRIVATE);
    mNavigationDrawerFragment = (FragmentNavigationDrawer) getSupportFragmentManager()
            .findFragmentById(R.id.navigation_drawer);
    mTitle = getTitle();

    /* Set up the drawer. */
    mNavigationDrawerFragment.setUp(R.id.navigation_drawer, (DrawerLayout) findViewById(R.id.drawer_layout));
}

From source file:drupalfit.sample.ToolBarActivity.java

/** {@inheritDoc} */
@Override/*from w w  w . j a v  a2s . c  o  m*/
public void addAccount(String username, String password, String authToken) {
    String accountType = "drualfit";
    String authTokenType = "drualfit";
    Account account = new Account(username, accountType);
    Bundle userdata = null;

    Intent intent = new Intent();

    intent.putExtra(AccountManager.KEY_ACCOUNT_NAME, username);
    intent.putExtra(AccountManager.KEY_ACCOUNT_TYPE, accountType);
    intent.putExtra(AccountManager.KEY_AUTHTOKEN, authToken);

    if (TextUtils.isEmpty(password)) {
        boolean added = getAccountManager().addAccountExplicitly(account, password, userdata);
    } else {
        getAccountManager().setPassword(account, password);
    }

    getAccountManager().setAuthToken(account, authTokenType, authToken);

    setAccountAuthenticatorResult(intent.getExtras());
    setResult(RESULT_OK, intent);
}

From source file:org.panbox.mobile.android.identitymgmt.IdentityDebugApp.java

public void createPanboxAccount() {

    panboxAccount = new Account(accountName, accountType);
    am.addAccountExplicitly(panboxAccount, null, null);

    Log.i(IdentityDebugApp.class.getSimpleName(), "Created Panbox Account");
}

From source file:com.stoneapp.ourvlemoodle2.activities.MainActivity.java

/**
 * Create an entry for this application in the system account list, if it isn't already there.
 *
 * @param context Context//from w ww  .  ja  v a 2  s .  c  om
 */
public static void CreateSyncAccount(Context context) {
    final String AUTHORITY = BuildConfig.APPLICATION_ID + ".provider";
    // Value below must match the account type specified in res/xml/syncadapter.xml
    final String ACCOUNT_TYPE = BuildConfig.APPLICATION_ID;
    // hours in seconds
    final long SYNC_INTERVAL = SettingsUtils.getSyncInterval(context) * 60L * 60L;

    List<MoodleSiteInfo> sites = MoodleSiteInfo.listAll(MoodleSiteInfo.class);
    String accountName = sites.get(0).getUsername();

    if (TextUtils.isEmpty(accountName))
        accountName = "OurVLE User";

    // Create account, if it's missing. (Either first run, or user has deleted account.)
    Account account = new Account(accountName, ACCOUNT_TYPE);

    AccountManager accountManager = (AccountManager) context.getSystemService(ACCOUNT_SERVICE);

    /*
     * Add the account and account type, no password or user data
     * If successful, return the Account object, otherwise report an error.
     */
    if (accountManager.addAccountExplicitly(account, null, null)) {
        // Inform the system that this account is eligible for auto sync when the network is up
        ContentResolver.setSyncAutomatically(account, AUTHORITY, true);
        // Recommend a schedule for automatic synchronization. The system may modify this based
        // on other scheduled syncs and network utilization.
        ContentResolver.addPeriodicSync(account, AUTHORITY, Bundle.EMPTY, SYNC_INTERVAL);
    }
}

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  w  w w  . j a v a 2 s . 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 = 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;
}