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.noswap.keyring.MainActivity.java

public void doGCMStuff() {
    GCMRegistrar.checkDevice(this);
    GCMRegistrar.checkManifest(this);

    final String regId = GCMRegistrar.getRegistrationId(this);
    if (regId.equals("")) {
        Log.v(TAG, "Registering");
        GCMRegistrar.register(this, SENDER_ID);
    } else {/*from ww w  . ja  v  a2 s  .  c  o m*/
        Log.v(TAG, "Already registered: " + regId);
    }

    AccountManager am = AccountManager.get(this);
    Account[] accounts = am.getAccountsByType("com.google");
    for (Account account : accounts) {
        Log.v(TAG, "Account: " + account.name + " (" + account.type + ")");
    }

    if (accounts.length > 0) {
        Account account = accounts[0];
        Bundle options = new Bundle();
        am.getAuthToken(account, "Keyring", options, this, new AccountManagerCallback<Bundle>() {
            @Override
            public void run(AccountManagerFuture<Bundle> result) {
                try {
                    Bundle bundle = result.getResult();
                    String token = bundle.getString(AccountManager.KEY_AUTHTOKEN);
                    Intent intent = (Intent) bundle.get(AccountManager.KEY_INTENT);
                    if (intent != null) {
                        startActivityForResult(intent, 0);
                        return;
                    }
                    Log.v(TAG, "onTokenAcquired: " + token);
                } catch (Exception e) {
                    Log.v(TAG, "onTokenAcquired exception: " + e.toString());
                }
            }
        }, new Handler() {
        });

    }
}

From source file:com.ntsync.android.sync.activities.CreatePwdProgressDialog.java

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

    AccountManager accountManager = AccountManager.get(getActivity());
    Bundle args = getArguments();/*from  ww  w .  java  2 s  .c  om*/
    String mUsername = args.getString(KeyPasswordActivity.PARAM_USERNAME);
    byte[] pwdSalt = args.getByteArray(KeyPasswordActivity.PARAM_SALT);
    Account account = new Account(mUsername, Constants.ACCOUNT_TYPE);

    String pwd = args.getString(PARAM_PWD);
    byte[] pwdCheck = args.getByteArray(KeyPasswordActivity.PARAM_CHECK);

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

    if (pwd == null) {
        createTask = new CreatePwdTask(account, accountManager, pwdSalt);
    } else {
        createTask = new RecreateKeyTask(account, accountManager, pwdSalt, pwdCheck, pwd);
    }
    createTask.execute();
}

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

public void send(String payload, TransportReceiver receiver, boolean newToken) {
    Throwable ex;/*w  ww.j ava 2 s  .c  o  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:br.com.bioscada.apps.biotracks.fragments.ExportDialogFragment.java

@Override
protected Dialog createDialog() {
    FragmentActivity fragmentActivity = getActivity();
    accounts = AccountManager.get(fragmentActivity).getAccountsByType(Constants.ACCOUNT_TYPE);

    // Get views//from   w ww .  j a v a2s  .  c  o  m
    View view = fragmentActivity.getLayoutInflater().inflate(R.layout.export, null);
    exportTypeOptions = (Spinner) view.findViewById(R.id.export_type_options);
    exportGoogleMapsOptions = (RadioGroup) view.findViewById(R.id.export_google_maps_options);
    exportGoogleFusionTablesOptions = (RadioGroup) view.findViewById(R.id.export_google_fusion_tables_options);
    exportExternalStorageOptions = (RadioGroup) view.findViewById(R.id.export_external_storage_options);
    accountSpinner = (Spinner) view.findViewById(R.id.export_account);

    // Setup exportTypeOptions
    setupExportTypeOptions(fragmentActivity);

    // Setup exportGoogleMapsOptions
    boolean exportGoogleMapsPublic = PreferencesUtils.getBoolean(fragmentActivity,
            R.string.export_google_maps_public_key, PreferencesUtils.EXPORT_GOOGLE_MAPS_PUBLIC_DEFAULT);
    exportGoogleMapsOptions
            .check(exportGoogleMapsPublic ? R.id.export_google_maps_public : R.id.export_google_maps_unlisted);

    // Setup exportGoogleFusionTablesOptions
    boolean exportGoogleFusionTablesPublic = PreferencesUtils.getBoolean(fragmentActivity,
            R.string.export_google_fusion_tables_public_key,
            PreferencesUtils.EXPORT_GOOGLE_FUSION_TABLES_PUBLIC_DEFAULT);
    exportGoogleFusionTablesOptions
            .check(exportGoogleFusionTablesPublic ? R.id.export_google_fusion_tables_public
                    : R.id.export_google_fusion_tables_private);

    // Setup exportExternalStorageOptions
    setExternalStorageOption((RadioButton) view.findViewById(R.id.export_external_storage_kml),
            TrackFileFormat.KML);
    setExternalStorageOption((RadioButton) view.findViewById(R.id.export_external_storage_gpx),
            TrackFileFormat.GPX);
    setExternalStorageOption((RadioButton) view.findViewById(R.id.export_external_storage_csv),
            TrackFileFormat.CSV);
    setExternalStorageOption((RadioButton) view.findViewById(R.id.export_external_storage_tcx),
            TrackFileFormat.TCX);
    TrackFileFormat trackFileFormat = TrackFileFormat
            .valueOf(PreferencesUtils.getString(fragmentActivity, R.string.export_external_storage_format_key,
                    PreferencesUtils.EXPORT_EXTERNAL_STORAGE_FORMAT_DEFAULT));
    exportExternalStorageOptions.check(getExternalStorageFormatId(trackFileFormat));

    // Setup accountSpinner
    AccountUtils.setupAccountSpinner(fragmentActivity, accountSpinner, accounts);

    return new AlertDialog.Builder(fragmentActivity).setNegativeButton(R.string.generic_cancel, null)
            .setPositiveButton(R.string.menu_export, new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    FragmentActivity context = getActivity();
                    ExportType type = exportTypeOptionsList.get(exportTypeOptions.getSelectedItemPosition());
                    TrackFileFormat format = null;

                    PreferencesUtils.setString(context, R.string.export_type_key, type.name());
                    if (type == ExportType.GOOGLE_MAPS) {
                        PreferencesUtils.setBoolean(context, R.string.export_google_maps_public_key,
                                exportGoogleMapsOptions
                                        .getCheckedRadioButtonId() == R.id.export_google_maps_public);
                    } else if (type == ExportType.GOOGLE_FUSION_TABLES) {
                        PreferencesUtils.setBoolean(context, R.string.export_google_fusion_tables_public_key,
                                exportGoogleFusionTablesOptions
                                        .getCheckedRadioButtonId() == R.id.export_google_fusion_tables_public);
                    } else if (type == ExportType.EXTERNAL_STORAGE) {
                        format = getTrackFileFormat(exportExternalStorageOptions.getCheckedRadioButtonId());
                        PreferencesUtils.setString(context, R.string.export_external_storage_format_key,
                                format.name());
                    }
                    Account account;
                    if (accounts.length == 0) {
                        account = null;
                    } else if (accounts.length == 1) {
                        account = accounts[0];
                    } else {
                        account = accounts[accountSpinner.getSelectedItemPosition()];
                    }
                    AccountUtils.updateShareTrackAccountPreference(context, account);
                    caller.onExportDone(type, format, account);
                }
            }).setTitle(R.string.export_title).setView(view).create();
}

From source file:org.klnusbaum.udj.auth.AuthActivity.java

/**
 * {@inheritDoc}/*from  w ww. j  ava 2  s . c om*/
 */
@Override
public void onCreate(Bundle icicle) {
    super.onCreate(icicle);
    mAccountManager = AccountManager.get(this);
    final Intent intent = getIntent();
    mUsername = intent.getStringExtra(PARAM_USERNAME);
    mRequestNewAccount = mUsername == null;
    mConfirmCredentials = intent.getBooleanExtra(PARAM_CONFIRM_CREDENTIALS, false);
    Log.i(TAG, "    request new: " + mRequestNewAccount);
    requestWindowFeature(Window.FEATURE_LEFT_ICON);
    setContentView(R.layout.login_activity);
    getWindow().setFeatureDrawableResource(Window.FEATURE_LEFT_ICON, android.R.drawable.ic_dialog_alert);
    mMessage = (TextView) findViewById(R.id.message);
    mUsernameEdit = (EditText) findViewById(R.id.username_edit);
    mPasswordEdit = (EditText) findViewById(R.id.password_edit);
    if (!TextUtils.isEmpty(mUsername))
        mUsernameEdit.setText(mUsername);
    mMessage.setText(getMessage());

    TextView signUp = (TextView) findViewById(R.id.signup_text);
    signUp.setText(Html.fromHtml(getString(R.string.dont_have_account)));
    signUp.setMovementMethod(LinkMovementMethod.getInstance());
}

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

@Override
public String getAuthToken(final Activity activity, String inAuthority)
        throws OperationCanceledException, AuthenticatorException, IOException {
    final String authority = inAuthority == null ? Constants.AUTHORITY_DEFAULT : inAuthority;
    final AccountManager am = AccountManager.get(activity);
    String token = am.peekAuthToken(
            new Account(Constants.getAccountName(activity), Constants.getAccountType(activity)), authority);
    if (token == null) {
        final Account a = new Account(Constants.getAccountName(activity), Constants.getAccountType(activity));
        Account[] accounts = am.getAccountsByType(Constants.getAccountType(activity));
        if (accounts == null || accounts.length == 0) {
            am.addAccount(Constants.getAccountType(activity), authority, null, null, null,
                    new Callback(authority, activity), null);
        } else {/*from w  w w .  j  a va  2  s. c o m*/
            am.getAuthToken(a, authority, null, null, new Callback(authority, activity), null);
        }
        return null;
    }
    return token;

}

From source file:edu.mit.mobile.android.locast.sync.AbsLocastAccountSyncService.java

@Override
public void onDestroy() {
    super.onDestroy();
    mProvider = null;/*w w  w . ja  v a 2 s  .c o m*/
    if (mSyncAdapter != null) {
        AccountManager.get(this).removeOnAccountsUpdatedListener(mSyncAdapter);
    }
}

From source file:com.dhara.googlecalendartrial.MainActivity.java

private void getAccounts() {
    accountManager = AccountManager.get(this.getBaseContext());
    Account[] accounts = accountManager.getAccountsByType("com.google");
    account = accounts[0];//from www.  j  av  a 2 s . c  om
    Log.e("tag", "acc : " + account.name + " ");
    accountManager.getAuthToken(account, AUTH_TOKEN_TYPE, null, MainActivity.this,
            new AccountManagerCallback<Bundle>() {
                public void run(AccountManagerFuture<Bundle> future) {
                    try {
                        // If the user has authorized your application to use the tasks API
                        // a token is available.
                        String token = future.getResult().getString(AccountManager.KEY_AUTHTOKEN);
                        // Now you can use the Tasks API...
                        useCalendarAPI(token, account.name);
                    } catch (OperationCanceledException e) {
                        // TODO: The user has denied you access to the API, you should handle that
                    } catch (Exception e) {
                        e.printStackTrace();

                        t.send(new HitBuilders.ExceptionBuilder().setDescription(Utilities.getMessage(e))
                                //.setDescription(new StandardExceptionParser(MainActivity.this, null).getDescription(Thread.currentThread().getName(), e))
                                .setFatal(false).build());
                    }
                }
            }, null);

    // Set screen name.
    // Where path is a String representing the screen name.
    t.setScreenName(getString(R.string.path));

    // Send a screen view.
    t.send(new HitBuilders.AppViewBuilder().build());
}

From source file:pt.up.mobile.authenticator.Authenticator.java

@Override
public Bundle getAuthToken(AccountAuthenticatorResponse response, Account account, String authTokenType,
        Bundle loginOptions) throws NetworkErrorException {
    Log.v(TAG, "getAuthToken()");

    // If the caller requested an authToken type we don't support, then
    // return an error
    if (!authTokenType.equals(Constants.AUTHTOKEN_TYPE)) {
        final Bundle result = new Bundle();
        result.putString(AccountManager.KEY_ERROR_MESSAGE, "invalid authTokenType");
        return result;
    }//w  ww  .j  a  v  a2s.  c o  m
    try {
        final AccountManager am = AccountManager.get(mContext);
        final String peek = am.peekAuthToken(account, authTokenType);
        if (peek != null) {
            final Bundle result = new Bundle();
            result.putString(AccountManager.KEY_ACCOUNT_NAME, account.name);
            result.putString(AccountManager.KEY_ACCOUNT_TYPE, Constants.ACCOUNT_TYPE);
            result.putString(AccountManager.KEY_AUTHTOKEN, peek);
            return result;
        }
        // Extract the username and password from the Account Manager, and
        // ask
        // the server for an appropriate AuthToken.
        final String password = am.getPassword(account);
        if (password != null) {
            String[] reply;

            reply = SifeupAPI.authenticate(account.name, password, mContext);
            final String authToken = reply[1];
            if (!TextUtils.isEmpty(authToken)) {
                final Bundle result = new Bundle();
                result.putString(AccountManager.KEY_ACCOUNT_NAME, account.name);
                result.putString(AccountManager.KEY_ACCOUNT_TYPE, Constants.ACCOUNT_TYPE);
                result.putString(AccountManager.KEY_AUTHTOKEN, authToken);
                return result;
            }
        }

    } catch (AuthenticationException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
        throw new NetworkErrorException();
    }
    // If we get here, then we couldn't access the user's password - so we
    // need to re-prompt them for their credentials. We do that by creating
    // an intent to display our AuthenticatorActivity panel.
    final Intent intent = new Intent(mContext, AuthenticatorActivity.class);
    intent.putExtra(AuthenticatorActivity.PARAM_CONFIRM_CREDENTIALS, true);
    intent.putExtra(AuthenticatorActivity.PARAM_USERNAME, account.name);
    intent.putExtra(AuthenticatorActivity.PARAM_AUTHTOKEN_TYPE, authTokenType);
    intent.putExtra(AccountManager.KEY_ACCOUNT_AUTHENTICATOR_RESPONSE, response);
    final Bundle bundle = new Bundle();
    bundle.putParcelable(AccountManager.KEY_INTENT, intent);
    return bundle;
}

From source file:edu.mit.mobile.android.locast.accounts.AbsLocastAuthenticatorActivity.java

/**
 * {@inheritDoc}//from   w  w  w . j a va 2 s. co m
 */
@Override
public void onCreate(Bundle icicle) {
    if (BuildConfig.DEBUG) {
        Log.i(TAG, "onCreate(" + icicle + ")");
    }
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
        requestWindowFeature(Window.FEATURE_ACTION_BAR);
    }
    super.onCreate(icicle);

    mAccountManager = AccountManager.get(this);
    if (BuildConfig.DEBUG) {
        Log.i(TAG, "loading data from Intent");
    }

    final Intent intent = getIntent();
    mUsername = intent.getStringExtra(EXTRA_USERNAME);
    mAuthtokenType = intent.getStringExtra(EXTRA_AUTHTOKEN_TYPE);
    mRequestNewAccount = mUsername == null;
    mConfirmCredentials = intent.getBooleanExtra(EXTRA_CONFIRMCREDENTIALS, false);

    if (BuildConfig.DEBUG) {
        Log.i(TAG, "    request new: " + mRequestNewAccount);
    }
    requestWindowFeature(Window.FEATURE_LEFT_ICON);

    final CharSequence appName = getAppName();

    // make the title based on the app name.
    setTitle(getString(R.string.login_title, appName));

    // TODO make this changeable. Maybe use fragments?
    setContentView(R.layout.login);
    // this is done this way, so the associated icon is managed in XML.
    try {
        getWindow().setFeatureDrawable(Window.FEATURE_LEFT_ICON,
                getPackageManager().getActivityIcon(getComponentName()));
    } catch (final NameNotFoundException e) {
        e.printStackTrace();
    }

    mMessage = (TextView) findViewById(R.id.message);
    mUsernameEdit = (EditText) findViewById(R.id.username);
    mUsernameEdit.setHint(isEmailAddressLogin() ? R.string.auth_email_login_hint : R.string.auth_username_hint);
    mPasswordEdit = (EditText) findViewById(R.id.password);
    mPasswordEdit.setOnEditorActionListener(this);
    findViewById(R.id.login).setOnClickListener(this);
    findViewById(R.id.cancel).setOnClickListener(this);
    mRegisterButton = (Button) findViewById(R.id.register);
    mRegisterButton.setOnClickListener(this);
    final String regButton = getString(R.string.signup_text, appName);
    if (regButton.length() < 24) {
        mRegisterButton.setText(regButton);
    }

    ((TextView) findViewById(R.id.username_label)).setText(getString(R.string.username_label, appName));

    mUsernameEdit.setText(mUsername);

    // this will be unnecessary with fragments
    mAuthenticationTask = (AuthenticationTask) getLastNonConfigurationInstance();
    if (mAuthenticationTask != null) {
        mAuthenticationTask.attach(this);
    }
}