22

我正在开发一个 Android 应用程序,我需要检索手机上使用的 Google 帐户。我想为 C2DM 执行此操作,但如果用户已经登录,我不想让用户输入他/她的 Google 电子邮件帐户。有什么办法吗?

4

2 回答 2

44

像这样的东西应该工作:

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

您需要在清单中获得以下权限:

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

如果您支持 Android 6 及更高版本,请记住“在运行时请求权限” https://developer.android.com/training/permissions/requesting.html

我是凭记忆写的,所以可能需要稍微调整一下。显然现在可以在没有电子邮件地址的情况下注册,所以也许对数据进行一些正则表达式以确保它实际上是一个电子邮件地址(确保它包含@gmail或@googlemail)

于 2010-10-28T01:26:23.730 回答
1

我尝试在以下范围内获取电子邮件地址用户名

在您的手机中获取 Google 帐户

 public String getMailId() {
        String strGmail = null;
        try {
            Account[] accounts = AccountManager.get(this).getAccounts();
            Log.e("PIKLOG", "Size: " + accounts.length);
            for (Account account : accounts) {

                String possibleEmail = account.name;
                String type = account.type;

                if (type.equals("com.google")) {

                    strGmail = possibleEmail;
                    Log.e("PIKLOG", "Emails: " + strGmail);
                    break;
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
             strGmail = null;
        }

        return strGmail;
    }

在您的手机中获取 Google 帐户用户名

 public String getUsername() {
    List<String> possibleEmails = null;
    try {
        AccountManager manager = AccountManager.get(this);
        Account[] accounts = manager.getAccountsByType("com.google");
        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);
        }
    } catch (Exception e) {
        e.printStackTrace();
        if (possibleEmails != null) {
            possibleEmails.clear();
        }
    }

    if (possibleEmails != null) {
        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;
            }
        } else {
            return null;
        }
    } else {
        return null;
    }
}

声明对您的 mainfest 文件的权限。

  <uses-permission android:name="android.permission.GET_ACCOUNTS" />
于 2016-03-18T06:00:26.057 回答