Imaginemos un mundo libre

La paz interior comienza en el momento en el que decides no permitir, que ninguna persona o evento, tome el control de tus emociones.

Android Code Snippets: Get User Accounts by domain

leave a comment »

Sometimes, when working on your Android apps, you will need to get the user accounts registered on the phone. A usual scenario, is the Login stuff, where you want to get domain specific accounts.

One way to achieve this, is to use the Account and AccountManager classes. If you want to get only accounts of an specific type, use the getAccountsByType() method.

Imagine I only want to get Google Accounts of mydomain.com

I call the method account_manager.getAccountsByType(“com.google”) to get Google accounts and for matching my domain, I use the Patterns util class that works with regular expressions. What I really need is the Patterns.EMAIL_ADDRESS pattern. Once I got these accounts, I can store them in an array and do whatever I want with them.

Here we go:

import android.accounts.Account;
import android.accounts.AccountManager;
import android.util.Log;
import android.util.Patterns;
...

import java.util.ArrayList;
import java.util.regex.Pattern;

public class LoginActivity extends Activity {
    private static final String TAG = "LOGIN";
    private static final String GOOGLE_ACCOUNT = "com.google";
    private static final String DOMAIN = "@yourdomain.com";
    private ArrayList<String> mDomainAccounts = new ArrayList<String>();

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.login);
        getAccounts();
    }

    private void getAccounts() {
        AccountManager account_manager = AccountManager.get(this);
        Pattern emailPattern = Patterns.EMAIL_ADDRESS;

        if(account_manager != null) {
            Account[] accounts = account_manager.getAccountsByType(GOOGLE_ACCOUNT);
            for (Account account : accounts) {
                if (emailPattern.matcher(account.name).matches()) {
                    mDomainAccounts.add(account.name);
                    Log.i(TAG, account.name);
                }
            }
        }
    }

    ...
}

Don’t forget to add the GET_ACCOUNTS permission to your AndroidManifest:

<uses-permission android:name=”android.permission.GET_ACCOUNTS” />

Written by Ronny Yabar

July 4, 2013 at 12:47 pm

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: