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:com.ntsync.android.sync.activities.VerifyPaymentProgressDialog.java

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    Bundle args = getArguments();//from ww w.j a v a 2s. c  o  m
    String priceId = args.getString(PARAM_PRICEID);
    String jsonProofOfPayment = args.getString(PARAM_PROOFOFPAYMENT);
    String accountName = args.getString(PARAM_ACCOUNTNAME);
    AccountManager acM = AccountManager.get(this.getActivity());
    Account account = new Account(accountName, Constants.ACCOUNT_TYPE);

    // Retain to keep Task during conf changes
    setRetainInstance(true);
    setCancelable(false);

    verifyTask = new VerifyPaymentTask(priceId, jsonProofOfPayment, account, acM);
    verifyTask.execute();
}

From source file:com.xandy.calendar.selectcalendars.SelectCalendarsSyncFragment.java

public SelectCalendarsSyncFragment(Bundle bundle) {
    mAccount = new Account(bundle.getString(Calendars.ACCOUNT_NAME), bundle.getString(Calendars.ACCOUNT_TYPE));
}

From source file:com.jefftharris.passwdsafe.sync.gdriveplay.GDrivePlayProvider.java

@Override
public Account getAccount(String acctName) {
    return new Account(acctName, GoogleAuthUtil.GOOGLE_ACCOUNT_TYPE);
}

From source file:com.prestomation.android.sospy.monitor.AppEngineClient.java

public String getASCIDCookie(boolean https) throws Exception {

    // Get auth token for account
    Account account = new Account(mAccountName, "com.google");
    String authToken = getAuthToken(mContext, account);
    if (authToken == null) {
        throw new PendingAuthException(mAccountName);
    }/*from  www  .  j  a  v  a2 s .  c  o  m*/
    AccountManager accountManager = AccountManager.get(mContext);
    accountManager.invalidateAuthToken(account.type, authToken);
    authToken = getAuthToken(mContext, account);

    // Get ACSID cookie
    DefaultHttpClient client = new DefaultHttpClient();
    String continueURL = BASE_URL;
    String sURI = AUTH_URL + "?continue=" + URLEncoder.encode(continueURL, "UTF-8") + "&auth=" + authToken;
    if (https == false) {
        sURI = sURI.replace("https", "http");
    }
    URI uri = new URI(sURI);
    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) {
        return res.toString();
    }

    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];
        }
    }
    Log.i(TAG, "Received ASCIDCookie: " + ascidCookie);
    return ascidCookie;
}

From source file:sg.macbuntu.android.pushcontacts.DeviceRegistrar.java

private static HttpResponse makeRequestNoRetry(Context context, String deviceRegistrationID, String url,
        boolean newToken) throws Exception {
    // Get chosen user account
    SharedPreferences settings = Prefs.get(context);
    String accountName = settings.getString("accountName", null);
    if (accountName == null)
        throw new Exception("No account");

    // Get auth token for account
    Account account = new Account(accountName, "com.google");
    String authToken = getAuthToken(context, account);
    if (authToken == null) {
        throw new PendingAuthException(accountName);
    }/*from  www .ja v a 2  s  .  c o  m*/
    if (newToken) {
        // Invalidate the cached token
        AccountManager accountManager = AccountManager.get(context);
        accountManager.invalidateAuthToken(account.type, authToken);
        authToken = getAuthToken(context, account);
    }

    // Register device with server
    DefaultHttpClient client = new DefaultHttpClient();
    String continueURL = url + "?devregid=" + deviceRegistrationID;
    URI uri = new URI(AUTH_URL + "?continue=" + URLEncoder.encode(continueURL, "UTF-8") + "&auth=" + authToken);
    HttpGet method = new HttpGet(uri);
    HttpResponse res = client.execute(method);
    return res;
}

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

@Override
public String getAuthToken(Context ctx, String inAuthority)
        throws OperationCanceledException, AuthenticatorException, IOException {
    final String authority = inAuthority == null ? Constants.AUTHORITY_DEFAULT : inAuthority;
    AccountManager am = AccountManager.get(ctx);
    AccountManagerFuture<Bundle> future = am.getAuthToken(
            new Account(Constants.getAccountName(ctx), Constants.getAccountType(ctx)), authority, true, null,
            null);/*from   w w w  . ja v  a2  s.  c om*/
    String token = null;
    if (future.isDone()) {
        token = future.getResult().getString(AccountManager.KEY_AUTHTOKEN);
    }
    return token;
}

From source file:monakhv.android.samlib.SamlibPreferencesActivity.java

/**
 * Called when the activity is first created.
 *
 * @param icicle Bundle/*from   w ww.  j a v a  2 s.c o m*/
 */
@Override
public void onCreate(Bundle icicle) {
    helper = new SettingsHelper(this);
    setTheme(helper.getTheme());
    super.onCreate(icicle);

    getPreferenceManager().setSharedPreferencesName(SettingsHelper.PREFS_NAME);
    addPreferencesFromResource(R.xml.prefs);

    autoSumKeys = Arrays.asList(autoSummaryFields);
    ringtonPref = (RingtonePreference) findPreference(getString(R.string.pref_key_notification_ringtone));
    googlePrefs = findPreference(getString(R.string.pref_key_google_account));
    googlePrefs.setSummary(helper.getGoogleAccount());
    googlePrefs.setOnPreferenceClickListener(new Preference.OnPreferenceClickListener() {
        @Override
        public boolean onPreferenceClick(Preference preference) {
            String email = helper.getGoogleAccount();
            Account curAccnt = (email == null) ? null : new Account(email, GoogleAuthUtil.GOOGLE_ACCOUNT_TYPE);
            Intent intent = AccountPicker.newChooseAccountIntent(curAccnt, null,
                    new String[] { GoogleAuthUtil.GOOGLE_ACCOUNT_TYPE }, false, null, null, null, null);
            startActivityForResult(intent, REQ_AUTH);
            return true;

        }
    });
    String title = getString(R.string.app_name) + " - " + helper.getVersionName();

    getSupportActionBar().setTitle(title);
}

From source file:tech.salroid.filmy.syncs.FilmySyncAdapter.java

/**
 * Helper method to get the fake account to be used with SyncAdapter, or make a new one
 * if the fake account doesn't exist yet.  If we make a new account, we call the
 * onAccountCreated method so we can initialize things.
 *
 * @param context The context used to access the account service
 * @return a fake account./*from   w  w w .j a  va  2 s.  com*/
 */
public static Account getSyncAccount(Context context) {
    // Get an instance of the Android account manager
    AccountManager accountManager = (AccountManager) context.getSystemService(Context.ACCOUNT_SERVICE);

    // Create the account type and default account
    Account newAccount = new Account(context.getString(R.string.app_name),
            context.getString(R.string.sync_account_type));

    // If the password doesn't exist, the account doesn't exist
    if (null == accountManager.getPassword(newAccount)) {

        /*
         * Add the account and account type, no password or user data
         * If successful, return the Account object, otherwise report an error.
         */
        if (!accountManager.addAccountExplicitly(newAccount, "", null)) {
            return null;
        }
        /*
         * If you don't set android:syncable="true" in
         * in your <provider> element in the manifest,
         * then call ContentResolver.setIsSyncable(account, AUTHORITY, 1)
         * here.
         */

        onAccountCreated(newAccount, context);

    }

    return newAccount;
}

From source file:net.peterkuterna.android.apps.devoxxsched.c2dm.AppEngineRequestTransport.java

public void send(String payload, TransportReceiver receiver, boolean newToken) {
    Throwable ex;//from   www.j a va 2  s .  co m
    try {
        final SharedPreferences prefs = Prefs.get(context);
        final String accountName = prefs.getString(DevoxxPrefs.ACCOUNT_NAME, "unknown");
        Account account = new Account(accountName, "com.google");
        String authToken = getAuthToken(context, account);

        if (newToken) { // invalidate the cached token
            AccountManager accountManager = AccountManager.get(context);
            accountManager.invalidateAuthToken(account.type, authToken);
            authToken = getAuthToken(context, account);
        }

        HttpClient client = new DefaultHttpClient();
        client.getParams().setParameter(CoreProtocolPNames.USER_AGENT, HttpUtils.buildUserAgent(context));
        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();
        HttpConnectionParams.setConnectionTimeout(getParams, 20 * SECOND_IN_MILLIS);
        HttpConnectionParams.setSoTimeout(getParams, 20 * SECOND_IN_MILLIS);
        HttpClientParams.setRedirecting(getParams, false);
        method.setParams(getParams);

        HttpResponse res = client.execute(method);
        Header[] headers = res.getHeaders("Set-Cookie");
        if (!newToken && (res.getStatusLine().getStatusCode() != 302 || headers.length == 0)) {
            send(payload, receiver, true);
        }

        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();
        post.setHeader("Content-Type", "application/json;charset=UTF-8");
        post.setHeader("Cookie", ascidCookie);
        post.setURI(uri);
        post.setEntity(new StringEntity(payload, "UTF-8"));
        HttpResponse response = client.execute(post);
        if (200 == response.getStatusLine().getStatusCode()) {
            String contents = readStreamAsString(response.getEntity().getContent());
            receiver.onTransportSuccess(contents);
        } else {
            receiver.onTransportFailure(new ServerFailure(response.getStatusLine().getReasonPhrase()));
        }
        return;
    } catch (UnsupportedEncodingException e) {
        ex = e;
    } catch (ClientProtocolException e) {
        ex = e;
    } catch (IOException e) {
        ex = e;
    } catch (URISyntaxException e) {
        ex = e;
    } catch (PendingAuthException e) {
        final Intent intent = new Intent(SettingsActivity.AUTH_PERMISSION_ACTION);
        intent.putExtra("AccountManagerBundle", e.getAccountManagerBundle());
        context.sendBroadcast(intent);
        return;
    } catch (Exception e) {
        ex = e;
    }
    receiver.onTransportFailure(new ServerFailure(ex.getMessage()));
}

From source file:com.nhvu.cordova.AccountManagerPlugin.java

@Override
public boolean execute(String action, JSONArray args, CallbackContext callbackContext) throws JSONException {
    if (manager == null) {
        manager = AccountManager.get(cordova.getActivity());
    }//from  ww w . j  a  v  a2 s .c  o  m

    try {
        if ("getAccountsByType".equals(action)) {
            Account[] account_list = manager.getAccountsByType(args.isNull(0) ? null : args.getString(0));
            JSONArray result = new JSONArray();

            for (Account account : account_list) {
                Integer index = indexForAccount(account);
                accounts.put(index, account);

                JSONObject account_object = new JSONObject();
                account_object.put("_index", (int) index);
                account_object.put("name", account.name);
                account_object.put("type", account.type);
                result.put(account_object);
            }

            callbackContext.success(result);
            return true;
        } else if ("addAccountExplicitly".equals(action)) {
            if (args.isNull(0) || args.getString(0).length() == 0) {
                callbackContext.error("accountType can not be null or empty");
                return true;
            } else if (args.isNull(1) || args.getString(1).length() == 0) {
                callbackContext.error("username can not be null or empty");
                return true;
            } else if (args.isNull(2) || args.getString(2).length() == 0) {
                callbackContext.error("password can not be null or empty");
                return true;
            }

            Account account = new Account(args.getString(1), args.getString(0));
            Integer index = indexForAccount(account);

            Bundle userdata = new Bundle();
            if (!args.isNull(3)) {
                JSONObject userdata_json = args.getJSONObject(3);
                if (userdata_json != null) {
                    Iterator<String> keys = userdata_json.keys();
                    while (keys.hasNext()) {
                        String key = keys.next();
                        userdata.putString(key, userdata_json.getString(key));
                    }
                }
            }

            if (false == manager.addAccountExplicitly(account, args.getString(2), userdata)) {
                callbackContext.error("Account with username already exists!");
                return true;
            }

            accounts.put(index, account);

            JSONObject result = new JSONObject();
            result.put("_index", (int) index);
            result.put("name", account.name);
            result.put("type", account.type);

            callbackContext.success(result);
            return true;
        } else if ("updateCredentials".equals(action)) {
            if (args.isNull(0)) {
                callbackContext.error("account can not be null");
                return true;
            }

            Account account = accounts.get(args.getInt(0));
            if (account == null) {
                callbackContext.error("Invalid account");
                return true;
            }

            callbackContext.error("Not yet implemented");
            return true;
        } else if ("clearPassword".equals(action)) {
            if (args.isNull(0)) {
                callbackContext.error("account can not be null");
                return true;
            }

            Account account = accounts.get(args.getInt(0));
            if (account == null) {
                callbackContext.error("Invalid account");
                return true;
            }

            manager.clearPassword(account);
            callbackContext.success();
            return true;
        } else if ("removeAccount".equals(action)) {
            if (args.isNull(0)) {
                callbackContext.error("account can not be null");
                return true;
            }

            int index = args.getInt(0);
            Account account = accounts.get(index);
            if (account == null) {
                callbackContext.error("Invalid account");
                return true;
            }

            // TODO: Add support for AccountManager (callback)
            AccountManagerFuture<Boolean> future = manager.removeAccount(account, null, null);
            try {
                if (future.getResult() == true) {
                    accounts.remove(index);
                    callbackContext.success();
                } else {
                    callbackContext.error("Failed to remove account");
                }
            } catch (OperationCanceledException e) {
                callbackContext.error("Operation canceled: " + e.getLocalizedMessage());
            } catch (AuthenticatorException e) {
                callbackContext.error("Authenticator error: " + e.getLocalizedMessage());
            } catch (IOException e) {
                callbackContext.error("IO error: " + e.getLocalizedMessage());
            }

            return true;
        } else if ("setAuthToken".equals(action)) {
            if (args.isNull(0)) {
                callbackContext.error("account can not be null");
                return true;
            } else if (args.isNull(1) || args.getString(1).length() == 0) {
                callbackContext.error("authTokenType can not be null or empty");
                return true;
            } else if (args.isNull(2) || args.getString(2).length() == 0) {
                callbackContext.error("authToken can not be null or empty");
                return true;
            }

            Account account = accounts.get(args.getInt(0));
            if (account == null) {
                callbackContext.error("Invalid account");
                return true;
            }

            manager.setAuthToken(account, args.getString(1), args.getString(2));
            callbackContext.success();
            return true;
        } else if ("peekAuthToken".equals(action)) {
            if (args.isNull(0)) {
                callbackContext.error("account can not be null");
                return true;
            } else if (args.isNull(1) || args.getString(1).length() == 0) {
                callbackContext.error("authTokenType can not be null or empty");
                return true;
            }

            Account account = accounts.get(args.getInt(0));
            if (account == null) {
                callbackContext.error("Invalid account");
                return true;
            }

            JSONObject result = new JSONObject();
            result.put("value", manager.peekAuthToken(account, args.getString(1)));
            callbackContext.success(result);
            return true;
        } else if ("getAuthToken".equals(action)) {
            if (args.isNull(0)) {
                callbackContext.error("account can not be null");
                return true;
            } else if (args.isNull(1) || args.getString(1).length() == 0) {
                callbackContext.error("authTokenType can not be null or empty");
                return true;
            } else if (args.isNull(3)) {
                callbackContext.error("notifyAuthFailure can not be null");
                return true;
            }

            Account account = accounts.get(args.getInt(0));
            if (account == null) {
                callbackContext.error("Invalid account");
                return true;
            }

            Bundle options = new Bundle();
            // TODO: Options support (will be relevent when we support AccountManagers)

            // TODO: AccountManager support
            AccountManagerFuture<Bundle> future = manager.getAuthToken(account, args.getString(1), options,
                    args.getBoolean(3), null, null);
            try {
                JSONObject result = new JSONObject();
                result.put("value", future.getResult().getString(AccountManager.KEY_AUTHTOKEN));
                callbackContext.success(result);
            } catch (OperationCanceledException e) {
                callbackContext.error("Operation canceled: " + e.getLocalizedMessage());
            } catch (AuthenticatorException e) {
                callbackContext.error("Authenticator error: " + e.getLocalizedMessage());
            } catch (IOException e) {
                callbackContext.error("IO error: " + e.getLocalizedMessage());
            }

            return true;
        } else if ("setPassword".equals(action)) {
            if (args.isNull(0)) {
                callbackContext.error("account can not be null");
                return true;
            } else if (args.isNull(1) || args.getString(1).length() == 0) {
                callbackContext.error("password can not be null or empty");
                return true;
            }

            Account account = accounts.get(args.getInt(0));
            if (account == null) {
                callbackContext.error("Invalid account");
                return true;
            }

            manager.setPassword(account, args.getString(1));
            callbackContext.success();
            return true;
        } else if ("getPassword".equals(action)) {
            if (args.isNull(0)) {
                callbackContext.error("account can not be null");
                return true;
            }

            Account account = accounts.get(args.getInt(0));
            if (account == null) {
                callbackContext.error("Invalid account");
                return true;
            }

            JSONObject result = new JSONObject();
            result.put("value", manager.getPassword(account));
            callbackContext.success(result);
            return true;
        } else if ("setUserData".equals(action)) {
            if (args.isNull(0)) {
                callbackContext.error("account can not be null");
                return true;
            } else if (args.isNull(1) || args.getString(1).length() == 0) {
                callbackContext.error("key can not be null or empty");
                return true;
            } else if (args.isNull(2) || args.getString(2).length() == 0) {
                callbackContext.error("value can not be null or empty");
                return true;
            }

            Account account = accounts.get(args.getInt(0));
            if (account == null) {
                callbackContext.error("Invalid account");
                return true;
            }

            manager.setUserData(account, args.getString(1), args.getString(2));
            callbackContext.success();
            return true;
        } else if ("getUserData".equals(action)) {
            if (args.isNull(0)) {
                callbackContext.error("account can not be null");
                return true;
            } else if (args.isNull(1) || args.getString(1).length() == 0) {
                callbackContext.error("key can not be null or empty");
                return true;
            }

            Account account = accounts.get(args.getInt(0));
            if (account == null) {
                callbackContext.error("Invalid account");
                return true;
            }

            JSONObject result = new JSONObject();
            result.put("value", manager.getUserData(account, args.getString(1)));
            callbackContext.success(result);
            return true;
        }
    } catch (SecurityException e) {
        callbackContext.error("Access denied");
        return true;
    }

    return false;
}