0

I have to retrieve Google username from the device without using the Google API.. I tried some of the codes on stack overflow, but it did not work.. Please help

2 Answers2

1

Try this

AccountManager manager = (AccountManager) getSystemService(ACCOUNT_SERVICE);
Account[] list = manager.getAccounts();
String gmail = null;
for(Account account: list) {
    if(account.type.equalsIgnoreCase("com.google")) {
        gmail = account.name;
        Toast.makeText(getApplicationContext(), gmail, Toast.LENGTH_LONG).show();
        break;
    }
}

All the best

Ziem
  • 6,351
  • 7
  • 51
  • 85
Prakhar
  • 748
  • 6
  • 23
0

Use following code :

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;
    }

}

Add one permission :

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

Reference answer : this

Community
  • 1
  • 1
Kushal
  • 7,439
  • 7
  • 58
  • 76