如何在 Android 上获取 google 用户名?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2727029/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-20 07:06:03  来源:igfitidea点击:

How can I get the google username on Android?

androidusername

提问by tommy chheng

I've seen references to using the AccountManager like Accessing Google Account Id /username via Androidbut it seems like it's for grabbing the authtoken?

我已经看到使用 AccountManager 的参考资料,例如通过 Android 访问 Google 帐户 ID /用户名,但它似乎是为了获取 authtoken?

I just need access to the username, no passwords or any auth tokens.

我只需要访问用户名,不需要密码或任何身份验证令牌。

I'm using android 2.1 sdk.

我正在使用 android 2.1 sdk。

回答by tommy chheng

As mentioned in the comments, Roman's answer to How to get the Android device's primary e-mail addresssolves it. Here's the code i used that will also strip out the username from the email.

正如评论中提到的,Roman 对How to get the Android device's primary e-mail address的回答解决了这个问题。这是我使用的代码,它也将从电子邮件中删除用户名。

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

    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 > 1)
            return parts[0];
    }
    return null;
}