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:ru.orangesoftware.financisto2.activity.FlowzrSyncActivity.java

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    FlowzrSyncActivity.me = this;
    mNotifyBuilder = new NotificationCompat.Builder(getApplicationContext());
    nm = (NotificationManager) getApplicationContext().getSystemService(Context.NOTIFICATION_SERVICE);
    setContentView(R.layout.flowzr_sync);
    restoreUIFromPref();/*  w  w  w .  j  av  a2s  .  c  o m*/
    if (useCredential != null) {

    }

    AccountManager accountManager = AccountManager.get(getApplicationContext());
    final Account[] accounts = accountManager.getAccountsByType("com.google");
    if (accounts.length < 1) {
        new AlertDialog.Builder(this).setTitle(getString(R.string.flowzr_sync_error))
                .setMessage(R.string.account_required)
                .setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                        finish();
                    }
                }).show();
    }
    //radio crendentials
    RadioGroup radioGroupCredentials = (RadioGroup) findViewById(R.id.radioCredentials);
    OnClickListener radio_listener = new OnClickListener() {
        public void onClick(View v) {
            RadioButton radioButtonSelected = (RadioButton) findViewById(v.getId());
            for (Account account : accounts) {
                if (account.name == radioButtonSelected.getText()) {
                    useCredential = account;
                }
            }
        }
    };
    //initialize value
    for (int i = 0; i < accounts.length; i++) {
        RadioButton rb = new RadioButton(this);
        radioGroupCredentials.addView(rb); //, 0, lp); 
        rb.setOnClickListener(radio_listener);
        rb.setText(((Account) accounts[i]).name);
        if (useCredential != null) {
            if (accounts[i].name.equals(useCredential.name)) {
                rb.toggle(); //.setChecked(true);
            }
        }
    }

    bOk = (Button) findViewById(R.id.bOK);
    bOk.setOnClickListener(new View.OnClickListener() {
        public void onClick(View view) {

            setRunning();
            initProgressDialog();
            //                if (useCredential!=null) {
            //                   flowzrBilling=new FlowzrBilling(FlowzrSyncActivity.this, getApplicationContext(), http_client, useCredential.toString());  
            //                }               
            if (useCredential == null) {
                showErrorPopup(FlowzrSyncActivity.this, R.string.flowzr_choose_account);
                notifyUser(getString(R.string.flowzr_choose_account), 100);
                setReady();
            } else if (!isOnline(FlowzrSyncActivity.this)) {
                showErrorPopup(FlowzrSyncActivity.this, R.string.flowzr_sync_error_no_network);
                notifyUser(getString(R.string.flowzr_sync_error_no_network), 100);
                setReady();
            } else {
                saveOptionsFromUI();
                //Play Service Billing
                //FlowzrBilling flowzrBilling = new FlowzrBilling(FlowzrSyncActivity.this, getApplicationContext(), http_client, useCredential.toString());  
                //if (flowzrSyncTask.checkSubscription()) {
                flowzrSyncEngine = new FlowzrSyncEngine(FlowzrSyncActivity.this);
                //}

            }
        }
    });

    Button bCancel = (Button) findViewById(R.id.bCancel);
    bCancel.setOnClickListener(new View.OnClickListener() {
        public void onClick(View view) {
            if (flowzrSyncEngine != null) {
                flowzrSyncEngine.isCanceled = true;
            }
            isRunning = false;
            setResult(RESULT_CANCELED);
            setReady();
            startActivity(new Intent(getApplicationContext(), MainActivity.class));
            //finish();
        }
    });

    Button textViewAbout = (Button) findViewById(R.id.buySubscription);
    textViewAbout.setOnClickListener(new View.OnClickListener() {
        public void onClick(View v) {
            if (isOnline(FlowzrSyncActivity.this)) {
                visitFlowzr(useCredential);
            } else {
                showErrorPopup(FlowzrSyncActivity.this, R.string.flowzr_sync_error_no_network);
            }
        }
    });

    Button textViewAboutAnon = (Button) findViewById(R.id.visitFlowzr);
    textViewAboutAnon.setOnClickListener(new View.OnClickListener() {
        public void onClick(View v) {
            if (isOnline(FlowzrSyncActivity.this)) {
                visitFlowzr(null);
            } else {
                showErrorPopup(FlowzrSyncActivity.this, R.string.flowzr_sync_error_no_network);
            }
        }
    });

    TextView textViewNotes = (TextView) findViewById(R.id.flowzrPleaseNote);
    textViewNotes.setMovementMethod(LinkMovementMethod.getInstance());
    textViewNotes.setText(Html.fromHtml(getString(R.string.flowzr_terms_of_use)));
    if (MyPreferences.isAutoSync(this)) {
        if (checkPlayServices()) {
            gcm = GoogleCloudMessaging.getInstance(this);
            regid = getRegistrationId(getApplicationContext());

            if (regid.equals("")) {
                registerInBackground();
            }
            Log.i(TAG, "Google Cloud Messaging registered as :" + regid);
        } else {
            Log.i(TAG, "No valid Google Play Services APK found.");
        }
    }
}

From source file:org.brussels.gtug.attendance.AccountsActivity.java

/**
 * Registers for C2DM messaging with the given account name.
 * //  w  ww .  j  a  va2s . c o m
 * @param accountName a String containing a Google account name
 */
private void register(final String accountName) {
    // Store the account name in shared preferences
    final SharedPreferences prefs = Util.getSharedPreferences(mContext);
    SharedPreferences.Editor editor = prefs.edit();
    editor.putString(Util.ACCOUNT_NAME, accountName);
    editor.remove(Util.AUTH_COOKIE);
    editor.remove(Util.DEVICE_REGISTRATION_ID);
    editor.commit();

    // Obtain an auth token and register<
    final AccountManager mgr = AccountManager.get(mContext);
    Account[] accts = mgr.getAccountsByType("com.google");
    for (Account acct : accts) {
        final Account account = acct;
        if (account.name.equals(accountName)) {
            // Get the auth token from the AccountManager and convert
            // it into a cookie for the appengine server
            final Activity activity = this;
            mgr.getAuthToken(account, "ah", null, activity, new AccountManagerCallback<Bundle>() {
                public void run(AccountManagerFuture<Bundle> future) {
                    String authToken = getAuthToken(future);
                    // Ensure the token is not expired by invalidating it and
                    // obtaining a new one
                    mgr.invalidateAuthToken(account.type, authToken);
                    mgr.getAuthToken(account, "ah", null, activity, new AccountManagerCallback<Bundle>() {
                        public void run(AccountManagerFuture<Bundle> future) {
                            String authToken = getAuthToken(future);
                            // Convert the token into a cookie for future use
                            String authCookie = getAuthCookie(authToken);
                            Editor editor = prefs.edit();
                            editor.putString(Util.AUTH_COOKIE, authCookie);
                            editor.commit();
                            C2DMessaging.register(mContext, Constants.SENDER_ID);
                        }
                    }, null);
                }
            }, null);
            break;
        }
    }
}

From source file:es.uma.lcc.tasks.PictureDetailsTask.java

private void handleAuthenticationError() {
    Thread t = new CookieRefresherThread(AccountManager.get(mMainActivity), mMainActivity);
    t.start();/*w w w  .j  ava  2 s . com*/
    try {
        t.join();
        (new PictureDetailsTask(mMainActivity, mPicId, false)).execute();
    } catch (InterruptedException e) {
        e.printStackTrace();
    }
}

From source file:es.uma.lcc.tasks.PicturesViewTask.java

private void handleAuthenticationError() {
    Thread t = new CookieRefresherThread(AccountManager.get(mMainActivity), mMainActivity);
    t.start();// w w  w  . j  a  v  a  2  s.c om
    try {
        t.join();
        (new PicturesViewTask(mMainActivity, false)).execute();
    } catch (InterruptedException e) {
        e.printStackTrace();
    }
}

From source file:com.murrayc.galaxyzoo.app.LoginUtils.java

/**
 * Add the anonymous Account./*w ww .  ja  v a2s .  co  m*/
 *
 * Don't call this from the main thread - use an AsyncTask, for instance.
 * @param context
 */
private static void addAnonymousAccount(final Context context) {
    final AccountManager accountManager = AccountManager.get(context);
    final Account account = new Account(ACCOUNT_NAME_ANONYMOUS, LoginUtils.ACCOUNT_TYPE);
    //Note that this requires the AUTHENTICATE_ACCOUNTS permission on
    //SDK <=22:
    accountManager.addAccountExplicitly(account, null, null);

    //In case it has not been called yet.
    //This has no effect the second time.
    Utils.initDefaultPrefs(context);

    //Give the new account the existing (probably default) preferences,
    //so the SyncAdapter can use them.
    //See SettingsFragment.onSharedPreferenceChanged().
    copyPrefsToAccount(context, accountManager, account);

    //Tell the SyncAdapter to sync whenever the network is reconnected:
    setAutomaticAccountSync(context, account);
}

From source file:com.android.browser.GoogleAccountLogin.java

private static Account[] getAccounts(Context ctx) {
    return AccountManager.get(ctx).getAccountsByType(GOOGLE);
}

From source file:com.google.android.gm.ay.java

public static boolean a(final Context context, final Account account) {
    boolean b = false;
    if (account != null) {
        final android.accounts.Account[] accountsByType = AccountManager.get(context)
                .getAccountsByType("com.google");
        final String lw = account.lw();
        int n = 0;
        while (true) {
            final int length = accountsByType.length;
            b = false;/*from  w ww.  j a v  a2  s.c o  m*/
            if (n >= length) {
                break;
            }
            if (lw.equals(accountsByType[n].name)) {
                b = true;
                break;
            }
            ++n;
        }
    }
    return b;
}

From source file:com.android.tv.settings.MainFragment.java

private void updateAccounts() {
    if (mAccountsGroup == null) {
        return;/* w w  w .  ja v  a 2  s.c o m*/
    }

    final Set<String> touchedAccounts = new ArraySet<>(mAccountsGroup.getPreferenceCount());

    final AccountManager am = AccountManager.get(getContext());
    final AuthenticatorDescription[] authTypes = am.getAuthenticatorTypes();
    final ArrayList<String> allowableAccountTypes = new ArrayList<>(authTypes.length);
    final Context themedContext = getPreferenceManager().getContext();

    for (AuthenticatorDescription authDesc : authTypes) {
        final Context targetContext;
        try {
            targetContext = getContext().createPackageContext(authDesc.packageName, 0);
        } catch (PackageManager.NameNotFoundException e) {
            Log.e(TAG, "Authenticator description with bad package name", e);
            continue;
        } catch (SecurityException e) {
            Log.e(TAG, "Security exception loading package resources", e);
            continue;
        }

        // Main title text comes from the authenticator description (e.g. "Google").
        String authTitle = null;
        try {
            authTitle = targetContext.getString(authDesc.labelId);
            if (TextUtils.isEmpty(authTitle)) {
                authTitle = null; // Handled later when we add the row.
            }
        } catch (Resources.NotFoundException e) {
            Log.e(TAG, "Authenticator description with bad label id", e);
        }

        // There exist some authenticators which aren't intended to be user-facing.
        // If the authenticator doesn't have a title or an icon, don't present it to
        // the user as an option.
        if (authTitle != null || authDesc.iconId != 0) {
            allowableAccountTypes.add(authDesc.type);
        }

        Account[] accounts = am.getAccountsByType(authDesc.type);
        if (accounts == null || accounts.length == 0) {
            continue; // No point in continuing; there aren't any accounts to show.
        }

        // Icon URI to be displayed for each account is based on the type of authenticator.
        Drawable authImage = null;
        try {
            authImage = targetContext.getDrawable(authDesc.iconId);
        } catch (Resources.NotFoundException e) {
            Log.e(TAG, "Authenticator has bad resources", e);
        }

        // Display an entry for each installed account we have.
        for (final Account account : accounts) {
            final String key = "account_pref:" + account.type + ":" + account.name;
            Preference preference = findPreference(key);
            if (preference == null) {
                preference = new Preference(themedContext);
            }
            preference.setTitle(authTitle != null ? authTitle : account.name);
            preference.setIcon(authImage);
            preference.setSummary(authTitle != null ? account.name : null);
            preference.setFragment(AccountSyncFragment.class.getName());
            AccountSyncFragment.prepareArgs(preference.getExtras(), account);

            touchedAccounts.add(key);
            preference.setKey(key);

            mAccountsGroup.addPreference(preference);
        }
    }

    for (int i = 0; i < mAccountsGroup.getPreferenceCount();) {
        final Preference preference = mAccountsGroup.getPreference(i);
        final String key = preference.getKey();
        if (touchedAccounts.contains(key) || TextUtils.equals(KEY_ADD_ACCOUNT, key)) {
            i++;
        } else {
            mAccountsGroup.removePreference(preference);
        }
    }

    // Never allow restricted profile to add accounts.
    final Preference addAccountPref = findPreference(KEY_ADD_ACCOUNT);
    if (addAccountPref != null) {
        addAccountPref.setOrder(Integer.MAX_VALUE);
        if (isRestricted()) {
            addAccountPref.setVisible(false);
        } else {
            Intent i = new Intent().setComponent(new ComponentName("com.android.tv.settings",
                    "com.android.tv.settings.accounts.AddAccountWithTypeActivity"));
            i.putExtra(AddAccountWithTypeActivity.EXTRA_ALLOWABLE_ACCOUNT_TYPES_STRING_ARRAY,
                    allowableAccountTypes.toArray(new String[allowableAccountTypes.size()]));

            // If there are available account types, show the "add account" button.
            addAccountPref.setVisible(!allowableAccountTypes.isEmpty());
            addAccountPref.setIntent(i);
        }
    }
}

From source file:com.androidexperiments.sprayscape.unitydriveplugin.GoogleDriveUnityPlayerActivity.java

private Account getAccountByName(String name) {
    for (Account a : AccountManager.get(this).getAccountsByType("com.google")) {
        if (a.name.equals(name)) {
            return a;
        }//from ww  w . ja v a2 s .  c om
    }
    return null;
}

From source file:com.cloudtask1.AccountsActivity.java

/**
 * Registers for C2DM messaging with the given account name.
 * //from  w w  w  . j ava  2s .c o  m
 * @param accountName a String containing a Google account name
 */
private void register(final String accountName) {
    // Store the account name in shared preferences
    final SharedPreferences prefs = Util.getSharedPreferences(mContext);
    SharedPreferences.Editor editor = prefs.edit();
    editor.putString(Util.ACCOUNT_NAME, accountName);
    editor.remove(Util.AUTH_COOKIE);
    editor.remove(Util.DEVICE_REGISTRATION_ID);
    editor.commit();

    // Obtain an auth token and register
    final AccountManager mgr = AccountManager.get(mContext);
    Account[] accts = mgr.getAccountsByType("com.google");
    for (Account acct : accts) {
        final Account account = acct;
        if (account.name.equals(accountName)) {
            if (Util.isDebug(mContext)) {
                // Use a fake cookie for the dev mode app engine server
                // The cookie has the form email:isAdmin:userId
                // We set the userId to be the same as the email
                String authCookie = "dev_appserver_login=" + accountName + ":false:" + accountName;
                prefs.edit().putString(Util.AUTH_COOKIE, authCookie).commit();
                C2DMessaging.register(mContext, Setup.SENDER_ID);
            } else {
                // Get the auth token from the AccountManager and convert
                // it into a cookie for the appengine server
                final Activity activity = this;
                mgr.getAuthToken(account, "ah", null, activity, new AccountManagerCallback<Bundle>() {
                    public void run(AccountManagerFuture<Bundle> future) {
                        String authToken = getAuthToken(future);
                        // Ensure the token is not expired by invalidating it and
                        // obtaining a new one
                        mgr.invalidateAuthToken(account.type, authToken);
                        mgr.getAuthToken(account, "ah", null, activity, new AccountManagerCallback<Bundle>() {
                            public void run(AccountManagerFuture<Bundle> future) {
                                String authToken = getAuthToken(future);
                                // Convert the token into a cookie for future use
                                String authCookie = getAuthCookie(authToken);
                                Editor editor = prefs.edit();
                                editor.putString(Util.AUTH_COOKIE, authCookie);
                                editor.commit();
                                C2DMessaging.register(mContext, Setup.SENDER_ID);
                            }
                        }, null);
                    }
                }, null);
            }
            break;
        }
    }
}