Google tag

Pages

Android get user account email

Link
public String getUsername() {
    AccountManager manager = AccountManager.get(this);
    Account[] accounts = manager.getAccountsByType("com.google");
    List possibleEmails = new LinkedList();

    for (Account account : accounts) {
        // TODO: Check possibleEmail against an email regex or treat
        // account.name as an email address only for certain account.type
        // values.
        possibleEmails.add(account.name);
    }

    if (!possibleEmails.isEmpty() && possibleEmails.get(0) != null) {
        String email = possibleEmails.get(0);
        /*
        String[] parts = email.split("@");
        if (parts.length > 0 && parts[0] != null)
            return parts[0];
        else
            return null;
        */
        return email;
    } else
        return null;
}

Second Option :
Link
getEmail(this)
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;
}

 android:name="android.permission.INTERNET" />
 android:name="android.permission.ACCESS_NETWORK_STATE" />

 android:name="android.permission.GET_ACCOUNTS" />

No comments: