How to get Current Active Google play account in A

2020-07-24 05:31发布

问题:

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.

回答1:

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.