Damodaran
Damodaran

Reputation: 49

How to get Current Active Google play account in Android

I can able to get all the configured gmails using below code snippet

 Account[] accounts = AccountManager.get(this).getAccounts();

for (Account account : accounts) {

 Log.e("Gmail","gmail "+account.name);

}

With the above snippet, I am getting more than one Gmail. But I need only current active gmail. Guide me to solve this.

Upvotes: 2

Views: 5880

Answers (2)

Monte Creasor
Monte Creasor

Reputation: 513

Here's a less verbose approach (Kotlin)

val playAccounts = AccountManager.get(context).getAccountsByType("com.google")

Upvotes: 0

ELITE
ELITE

Reputation: 5940

There is no concept of primary email id or current active google account in android.

You can get the google accounts of user which has been logged in on that phone.

Account[] accounts = AccountManager.get(this).getAccounts();
if(accounts != null && accounts.length > 0) {
    ArrayList playAccounts = new ArrayList();
    for (Account account : accounts) {
        String name = account.name;
        String type = account.type;
        if(account.type.equals("com.google")) {
            playAccounts.add(ac.name);
        }
        Log.d(TAG, "Account Info: " + name + ":" + type);
    }
    Log.d("tag", "Google Play Accounts present on phone are :: " + playAccounts);
}

As per the answer suggested in above link is to select the last account which you got in list, to get the first account added in android.

String emailId = playAccounts.get(playAccounts.size()-1);

Update - 1

You'll need GET_ACCOUNTS permission to access accounts.

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

Hope it'll help.

Upvotes: 5

Related Questions