Android How to - Get all device accounts having specified domain name








Question

We would like to know how to get all device accounts having specified domain name.

Answer

import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
//from   w w w. j  ava  2 s.c  o m
import android.accounts.Account;
import android.accounts.AccountManager;
import android.content.Context;

public class Main {
    /**
     * Get all device accounts having specified domain name.
     * @param context application context
     * @param domain domain name used for filtering
     * @return List of account names that contain the specified domain name
     */
    public static List<String> getDeviceAccountsWithDomain(
            final Context context, final String domain) {
        final ArrayList<String> retval = new ArrayList<String>();
        final String atDomain = "@" + domain.toLowerCase(Locale.ROOT);
        for (final Account account : getAccounts(context)) {
            if (account.name.toLowerCase(Locale.ROOT).endsWith(atDomain)) {
                retval.add(account.name);
            }
        }
        return retval;
    }

    private static Account[] getAccounts(final Context context) {
        return AccountManager.get(context).getAccounts();
    }
}