从设备中检索Google用户名

时间:2015-04-24 11:06:55

标签: android

我必须在不使用Google API的情况下从设备中检索Google用户名。我在堆栈溢出时尝试了一些代码,但它无法正常工作.. 请帮忙

2 个答案:

答案 0 :(得分:1)

试试这个

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

一切顺利

答案 1 :(得分:0)

使用以下代码:

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

}

添加一项权限:

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

参考答案:this