Getting the Gmail Id of the User In Android
Asked Answered
B

2

7

I don't know it is the correct question or not.How can we get the lo-gin id of the user from which it has been lo-gin to the Google Play Store in Android.Is this possible or not.

Biggers answered 4/9, 2013 at 12:28 Comment(0)
C
8

As per my knowledge the user has to configure his gmail account in his android phone and then he gets access to Google Play.

You can fetch the account information as given below (from Jim Blackler):

import android.accounts.Account;
import android.accounts.AccountManager;
import android.content.Context;

/**
* This class uses the AccountManager to get the primary email address of the
* current user.
*/
public class UserEmailFetcher {

    static String getEmail(Context context) {
        AccountManager accountManager = AccountManager.get(context); 
        Account account = getAccount(accountManager);

        if (account == null) {
            return null;
        } else {
            return account.name;
        }
    }

    private static Account getAccount(AccountManager accountManager) {
        Account[] accounts = accountManager.getAccountsByType("com.google");
        Account account;
        if (accounts.length > 0) {
            account = accounts[0];      
        } else {
            account = null;
        }
        return account;
    }
}

In Manifest

<uses-permission android:name="android.permission.GET_ACCOUNTS" />
Candlenut answered 4/9, 2013 at 12:37 Comment(1)
FYI this won't work reliably for Android 6.0 and later unless the user has explicitly granted your app the permission (which is a part of the user facing "contacts" permission group). See my answer below for an alternate method of retrieving an email address.Gabbert
G
7

If you're after a method that doesn't require requesting a permission via AndroidManifest.xml you can use Google Play Services' AccountPicker.

Spawn a dialog that allows the user to pick their desired Google Account:

Intent intent = AccountPicker.newChooseAccountIntent(null, null, new String[]{"com.google"}, false, null, null, null, null);
startActivityForResult(intent, SOME_REQUEST_CODE);

then handle the result in your Activity:

protected void onActivityResult(final int requestCode, final int resultCode, final Intent data) {
    if (requestCode == SOME_REQUEST_CODE && resultCode == RESULT_OK) {
        String emailAddress = data.getStringExtra(AccountManager.KEY_ACCOUNT_NAME);
        // do something...
    }
}

Remember to add compile 'com.google.android.gms:play-services-identity:8.+' to the dependencies in your build.gradle file (check here for the most recent version number to use).

Gabbert answered 12/10, 2015 at 4:10 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.