How can I get the google username on Android?

僤鯓⒐⒋嵵緔 提交于 2019-11-26 06:34:12

问题


I\'ve seen references to using the AccountManager like 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.

I\'m using android 2.1 sdk.


回答1:


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


来源:https://stackoverflow.com/questions/2727029/how-can-i-get-the-google-username-on-android

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!