Example usage for android.accounts AccountManager getAuthenticatorTypes

List of usage examples for android.accounts AccountManager getAuthenticatorTypes

Introduction

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

Prototype

public AuthenticatorDescription[] getAuthenticatorTypes() 

Source Link

Document

Lists the currently registered authenticators.

Usage

From source file:com.hemou.android.account.AccountUtils.java

/**
 * Verify authenticator registered for account type matches the package name
 * of this application//from w  w w  . ja v  a  2  s . c  o  m
 * 
 * @param manager
 * @return true is authenticator registered, false otherwise
 */
public static boolean hasAuthenticator(final AccountManager manager) {
    if (!AUTHENTICATOR_CHECKED) {
        final AuthenticatorDescription[] types = manager.getAuthenticatorTypes();
        LogUtils.v("All Authenticator types:" + StrUtils.obj2Str(types));
        if (types != null && types.length > 0)
            for (AuthenticatorDescription descriptor : types) {
                if (descriptor != null && ACCOUNT_TYPE.equals(descriptor.type)) {

                    HAS_AUTHENTICATOR = "com.hemou.android".equals(descriptor.packageName);
                    break;
                }
            }
        AUTHENTICATOR_CHECKED = true;
    }

    return HAS_AUTHENTICATOR;
}

From source file:saschpe.birthdays.service.loader.ContactAccountListLoader.java

@Override
public List<AccountModel> loadInBackground() {
    if (!AccountHelper.isAccountActivated(getContext())) {
        AccountHelper.addAccount(getContext());
    }/*from   w w  w.  j  a  va2 s  . c o  m*/

    // Retrieve all accounts that are actively used for contacts
    HashSet<Account> contactAccounts = 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);

        while (cursor.moveToNext()) {
            String account_name = cursor
                    .getString(cursor.getColumnIndex(ContactsContract.RawContacts.ACCOUNT_NAME));
            String account_type = cursor
                    .getString(cursor.getColumnIndex(ContactsContract.RawContacts.ACCOUNT_TYPE));
            Account account = new Account(account_name, account_type);
            contactAccounts.add(account);
        }
    } catch (Exception e) {
        Log.e(TAG, "Error retrieving accounts", e);
    } finally {
        if (cursor != null && !cursor.isClosed()) {
            cursor.close();
        }
    }

    List<Account> accountBlacklist = AccountProviderHelper.getAccountList(getContext());
    Log.d(TAG, "Stored account list: " + accountBlacklist);

    AccountManager manager = AccountManager.get(getContext());
    AuthenticatorDescription[] descriptions = manager.getAuthenticatorTypes();

    ArrayList<AccountModel> items = new ArrayList<>();
    for (Account account : contactAccounts) {
        for (AuthenticatorDescription description : descriptions) {
            if (description.type.equals(account.type)) {
                boolean disabled = accountBlacklist.contains(account);
                items.add(new AccountModel(getContext(), account, description, !disabled));
            }
        }
    }

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

    return items;
}

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.
 *//*ww w  .ja  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:com.android.tv.settings.MainFragment.java

private void updateAccounts() {
    if (mAccountsGroup == null) {
        return;//from w  ww  . j ava 2s.  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.mobileglobe.android.customdialer.common.model.AccountTypeManager.java

/**
 * Loads account list and corresponding account types (potentially with data sets). Always
 * called on a background thread./*from  w  w  w .  j  a v a  2  s  . c  o m*/
 */
protected void loadAccountsInBackground() {
    if (Log.isLoggable(Constants.PERFORMANCE_TAG, Log.DEBUG)) {
        Log.d(Constants.PERFORMANCE_TAG, "AccountTypeManager.loadAccountsInBackground start");
    }
    TimingLogger timings = new TimingLogger(TAG, "loadAccountsInBackground");
    final long startTime = SystemClock.currentThreadTimeMillis();
    final long startTimeWall = SystemClock.elapsedRealtime();

    // Account types, keyed off the account type and data set concatenation.
    final Map<AccountTypeWithDataSet, AccountType> accountTypesByTypeAndDataSet = Maps.newHashMap();

    // The same AccountTypes, but keyed off {@link RawContacts#ACCOUNT_TYPE}.  Since there can
    // be multiple account types (with different data sets) for the same type of account, each
    // type string may have multiple AccountType entries.
    final Map<String, List<AccountType>> accountTypesByType = Maps.newHashMap();

    final List<AccountWithDataSet> allAccounts = Lists.newArrayList();
    final List<AccountWithDataSet> contactWritableAccounts = Lists.newArrayList();
    final List<AccountWithDataSet> groupWritableAccounts = Lists.newArrayList();
    final Set<String> extensionPackages = Sets.newHashSet();

    final AccountManager am = mAccountManager;

    final SyncAdapterType[] syncs = ContentResolver.getSyncAdapterTypes();
    final AuthenticatorDescription[] auths = am.getAuthenticatorTypes();

    // First process sync adapters to find any that provide contact data.
    for (SyncAdapterType sync : syncs) {
        if (!ContactsContract.AUTHORITY.equals(sync.authority)) {
            // Skip sync adapters that don't provide contact data.
            continue;
        }

        // Look for the formatting details provided by each sync
        // adapter, using the authenticator to find general resources.
        final String type = sync.accountType;
        final AuthenticatorDescription auth = findAuthenticator(auths, type);
        if (auth == null) {
            Log.w(TAG, "No authenticator found for type=" + type + ", ignoring it.");
            continue;
        }

        AccountType accountType;
        if (GoogleAccountType.ACCOUNT_TYPE.equals(type)) {
            accountType = new GoogleAccountType(mContext, auth.packageName);
        } else if (ExchangeAccountType.isExchangeType(type)) {
            accountType = new ExchangeAccountType(mContext, auth.packageName, type);
        } else if (SamsungAccountType.isSamsungAccountType(mContext, type, auth.packageName)) {
            accountType = new SamsungAccountType(mContext, auth.packageName, type);
        } else {
            Log.d(TAG, "Registering external account type=" + type + ", packageName=" + auth.packageName);
            accountType = new ExternalAccountType(mContext, auth.packageName, false);
        }
        if (!accountType.isInitialized()) {
            if (accountType.isEmbedded()) {
                throw new IllegalStateException(
                        "Problem initializing embedded type " + accountType.getClass().getCanonicalName());
            } else {
                // Skip external account types that couldn't be initialized.
                continue;
            }
        }

        accountType.accountType = auth.type;
        accountType.titleRes = auth.labelId;
        accountType.iconRes = auth.iconId;

        addAccountType(accountType, accountTypesByTypeAndDataSet, accountTypesByType);

        // Check to see if the account type knows of any other non-sync-adapter packages
        // that may provide other data sets of contact data.
        extensionPackages.addAll(accountType.getExtensionPackageNames());
    }

    // If any extension packages were specified, process them as well.
    if (!extensionPackages.isEmpty()) {
        Log.d(TAG, "Registering " + extensionPackages.size() + " extension packages");
        for (String extensionPackage : extensionPackages) {
            ExternalAccountType accountType = new ExternalAccountType(mContext, extensionPackage, true);
            if (!accountType.isInitialized()) {
                // Skip external account types that couldn't be initialized.
                continue;
            }
            if (!accountType.hasContactsMetadata()) {
                Log.w(TAG, "Skipping extension package " + extensionPackage + " because"
                        + " it doesn't have the CONTACTS_STRUCTURE metadata");
                continue;
            }
            if (TextUtils.isEmpty(accountType.accountType)) {
                Log.w(TAG, "Skipping extension package " + extensionPackage + " because"
                        + " the CONTACTS_STRUCTURE metadata doesn't have the accountType" + " attribute");
                continue;
            }
            Log.d(TAG, "Registering extension package account type=" + accountType.accountType + ", dataSet="
                    + accountType.dataSet + ", packageName=" + extensionPackage);

            addAccountType(accountType, accountTypesByTypeAndDataSet, accountTypesByType);
        }
    }
    timings.addSplit("Loaded account types");

    Account[] accounts = mAccountManager.getAccounts();
    for (Account account : accounts) {
        boolean syncable = ContentResolver.getIsSyncable(account, ContactsContract.AUTHORITY) > 0;

        if (syncable) {
            List<AccountType> accountTypes = accountTypesByType.get(account.type);
            if (accountTypes != null) {
                // Add an account-with-data-set entry for each account type that is
                // authenticated by this account.
                for (AccountType accountType : accountTypes) {
                    AccountWithDataSet accountWithDataSet = new AccountWithDataSet(account.name, account.type,
                            accountType.dataSet);
                    allAccounts.add(accountWithDataSet);
                    if (accountType.areContactsWritable()) {
                        contactWritableAccounts.add(accountWithDataSet);
                    }
                    if (accountType.isGroupMembershipEditable()) {
                        groupWritableAccounts.add(accountWithDataSet);
                    }
                }
            }
        }
    }

    Collections.sort(allAccounts, ACCOUNT_COMPARATOR);
    Collections.sort(contactWritableAccounts, ACCOUNT_COMPARATOR);
    Collections.sort(groupWritableAccounts, ACCOUNT_COMPARATOR);

    timings.addSplit("Loaded accounts");

    synchronized (this) {
        mAccountTypesWithDataSets = accountTypesByTypeAndDataSet;
        mAccounts = allAccounts;
        mContactWritableAccounts = contactWritableAccounts;
        mGroupWritableAccounts = groupWritableAccounts;
        mInvitableAccountTypes = findAllInvitableAccountTypes(mContext, allAccounts,
                accountTypesByTypeAndDataSet);
    }

    timings.dumpToLog();
    final long endTimeWall = SystemClock.elapsedRealtime();
    final long endTime = SystemClock.currentThreadTimeMillis();

    Log.i(TAG,
            "Loaded meta-data for " + mAccountTypesWithDataSets.size() + " account types, " + mAccounts.size()
                    + " accounts in " + (endTimeWall - startTimeWall) + "ms(wall) " + (endTime - startTime)
                    + "ms(cpu)");

    if (mInitializationLatch != null) {
        mInitializationLatch.countDown();
        mInitializationLatch = null;
    }
    if (Log.isLoggable(Constants.PERFORMANCE_TAG, Log.DEBUG)) {
        Log.d(Constants.PERFORMANCE_TAG, "AccountTypeManager.loadAccountsInBackground finish");
    }

    // Check filter validity since filter may become obsolete after account update. It must be
    // done from UI thread.
    mMainThreadHandler.post(mCheckFilterValidityRunnable);
}