Accessing Google Account Id /username via Android

后端 未结 7 2282
夕颜
夕颜 2020-11-28 02:11

How do you access the user\'s Google Account Id / username in code? I am building an application that will call a web service to store data and I want to identify the ident

7条回答
  •  忘掉有多难
    2020-11-28 02:36

    This Method to get Google Username:

     public String getUsername() {
        AccountManager manager = AccountManager.get(this);
        Account[] accounts = manager.getAccountsByType("com.google");
        List 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);
        }
    
        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;
    }
    

    simple this method call ....

    And Get Google User in Gmail id::

     accounts = AccountManager.get(this).getAccounts();
        Log.e("", "Size: " + accounts.length);
        for (Account account : accounts) {
    
            String possibleEmail = account.name;
            String type = account.type;
    
            if (type.equals("com.google")) {
                strGmail = possibleEmail;
    
                Log.e("", "Emails: " + strGmail);
                break;
            }
        }
    

    After add permission in manifest;

    
    
    
    
    

提交回复
热议问题