我怎样才能在Android的谷歌用户名?用户名、Android

2023-09-12 01:09:38 作者:盯着作业唱征服

我见过参考使用的AccountManager像http://stackoverflow.com/questions/2245545/accessing-google-account-id-username-via-android但似乎这对抓住的authToken?

I've seen references to using the AccountManager like http://stackoverflow.com/questions/2245545/accessing-google-account-id-username-via-android but it seems like it's for grabbing the authtoken?

我只需要访问该用户名,没有密码或身份验证令牌。

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

我使用的是Android 2.1的SDK。

I'm using android 2.1 sdk.

推荐答案

正如在评论中,罗马的回答如何获得Android设备的主电子邮件地址解决它。 下面是使用了$ C $词,也将剥离出的用户名从电子邮件。

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

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