How can I get the google username on Android?

后端 未结 1 1407
忘了有多久
忘了有多久 2020-11-27 03:54

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 n

相关标签:
1条回答
  • 2020-11-27 04:21

    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;
    }
    
    0 讨论(0)
提交回复
热议问题