How to get all registered email accounts in Android

person folder_openAndroidaccess_time April 24, 2015

In this tutorial we are going to show how to get all registered Gmail ids and other email accounts like Skype in Android. All the email ids are provided by the AccountManager class.
See flowing Steps :

  1. Declare GET_ACCOUNTS permission in Manifest file.
  2. Get the email ids using getAccounts or getAccountsByType provided by AccountManager .

Note: This will not work in EmulatorsgetAccounts will give all the email ids including Gmail id.

1. Manifest file

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.stackandroid.getdeviceemail"
    android:versionCode="1"
    android:versionName="1.0" >
    <uses-sdk
        android:minSdkVersion="19"
        android:targetSdkVersion="20" />
    <uses-permission android:name="android.permission.GET_ACCOUNTS"/>
    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name=".MainActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>
</manifest>

2. Activity layout file

<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context="com.stackandroid.getdeviceemail.MainActivity" >
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical" >
        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="@string/message" />
        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="@string/warning"
            android:textColor="@android:color/holo_orange_dark"
            android:textSize="10sp" />
        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:orientation="horizontal" >
            <Button
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_weight="1"
                android:onClick="getGmailAccounts"
                android:text="Gmail Accounts" />
            <Button
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_weight="1"
                android:onClick="getAllAccounts"
                android:text="All Accounts" />
        </LinearLayout>
        <LinearLayout
            android:id="@+id/layout"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:orientation="vertical" >
        </LinearLayout>
    </LinearLayout>
</ScrollView>

3. Main Activity code

package com.stackandroid.getdeviceemail;
import java.util.ArrayList;
import java.util.List;
import android.accounts.Account;
import android.accounts.AccountManager;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.graphics.Color;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.LinearLayout.LayoutParams;
import android.widget.TextView;
public class MainActivity extends Activity {
	private int GMAIL_ACCOUNT = 0;
	private int ALL_ACCOUNTS = 1;
	private int emailType;
	private LinearLayout rootLayout;
	private Context mContext;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		mContext = this;
		rootLayout = (LinearLayout) findViewById(R.id.layout);
		emailType = GMAIL_ACCOUNT;
		getEmails();
	}
	public void getGmailAccounts(View v)
	{
		emailType = GMAIL_ACCOUNT;
		getEmails();
	}
	public void getAllAccounts(View v)
	{
		emailType = ALL_ACCOUNTS;
		getEmails();
	}
	private void getEmails() {
		new AsyncTask<Void, Void, List<EmailAccount>>() {
			private ProgressDialog pDialog;
			@Override
			protected void onPreExecute() {
				super.onPreExecute();
				pDialog = new ProgressDialog(mContext);
				pDialog.setMessage("Reading email accounts");
				pDialog.show();
			}
			@Override
			protected List<EmailAccount> doInBackground(Void... params) {
				Account[] accounts;
				if(emailType == GMAIL_ACCOUNT)
				{
					// Fetch only gmail ids
					accounts = AccountManager.get(mContext).getAccountsByType("com.google");
				}
				else
				{
					// Fetch all emails (including gmail)
					accounts = AccountManager.get(mContext).getAccounts();
				}
				List<EmailAccount> emails = new ArrayList<EmailAccount>();
			       try{
			            for (Account account : accounts) {
			            		emails.add(new EmailAccount(account.name, account.type));
			            }
			       }
			       catch(Exception e)
			       {
			            Log.i("Exception", "Exception:"+e) ;
			       }
			       return emails;
			}
			@Override
			protected void onPostExecute(List<EmailAccount> result) {
				super.onPostExecute(result);
				populateResults(result);
				pDialog.cancel();
			}
		}.execute();
	}
	protected void populateResults(List<EmailAccount> result) {
		// Remove all clid views
		rootLayout.removeAllViews();
		TextView tv;
		// If no email is registered, display this message
		if(result.size() < 1)
		{
			tv = new TextView(this);
			tv.setLayoutParams(new LayoutParams(android.view.ViewGroup.LayoutParams.MATCH_PARENT, android.view.ViewGroup.LayoutParams.WRAP_CONTENT));
			tv.setText("No accounts registered");
			tv.setTextColor(Color.BLUE);
			rootLayout.addView(tv);
			return;
		}
		// Iterate through results and display
		int i = 0;
		for(EmailAccount account : result)
		{
			tv = new TextView(this);
			LayoutParams params = new LayoutParams(android.view.ViewGroup.LayoutParams.MATCH_PARENT, android.view.ViewGroup.LayoutParams.WRAP_CONTENT);
			params.setMargins(0, 5, 0, 0);
			tv.setLayoutParams(params);
			tv.setTextSize(15);
			if(i++%2 == 1) tv.setBackgroundColor(Color.parseColor("#81BEF7"));
			if(emailType == GMAIL_ACCOUNT) tv.setText("Email: "+account.name);
			else tv.setText("Account Type: "+account.type + "\nEmail: "+account.name);
			rootLayout.addView(tv);
		}
	}
	private class EmailAccount{
		public String name;
		public String type;
		EmailAccount(String name, String type)
		{
			this.name = name;
			this.type = type;
		}
		@Override
		public String toString() {
			return "[name :"+name+", type:"+type+"]";
		}
	}
}

4. Demonstration
Reading all registered gmail accounts

Reading all registered gmail ids
Reading all registered gmail ids

Reading all other registered accounts

Reading all registered accounts
Reading all registered accounts

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code class="" title="" data-url=""> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong> <pre class="" title="" data-url=""> <span class="" title="" data-url="">