Getting the Gmail Id of the User In Android 6.0 marshmallow

后端 未结 3 796
遇见更好的自我
遇见更好的自我 2021-01-15 05:50

I am getting email id by using android.permission.GET_ACCOUNTS permission.

 try {
            Account[] accounts = AccountManager.get(this).getA         


        
3条回答
  •  离开以前
    2021-01-15 06:17

    Example as a separate service class to be easily used in different situations by calling getGMailAccount method.

    public class GMailAccountService {

    private static final int MIN_SDK_FOR_REQUESTING_GET_ACCOUNTS = 22;
    private static final int GET_ACCOUNTS_PERMISSION_REQUEST_CODE = 112;
    
    private Activity activity;
    
    public GMailAccountService(Activity activity) {
        this.activity = activity;
    }
    
    public String getGMailAccount() {
        if(android.os.Build.VERSION.SDK_INT > MIN_SDK_FOR_REQUESTING_GET_ACCOUNTS){
            if(!isGetAccountsPermissionAllowed()){
                requestGetAccountsPermission();
                return getGMailAccount();
            }
        }
        return extractAddressFromAccountManager();
    }
    
    private boolean isGetAccountsPermissionAllowed() {
        int result = ContextCompat.checkSelfPermission(activity, Manifest.permission.GET_ACCOUNTS);
        if (result == PackageManager.PERMISSION_GRANTED)
            return true;
        return false;
    }
    
    private void requestGetAccountsPermission(){
        ActivityCompat.shouldShowRequestPermissionRationale(activity, android.Manifest.permission.GET_ACCOUNTS);
        ActivityCompat.requestPermissions(activity,new String[]{android.Manifest.permission.GET_ACCOUNTS}, GET_ACCOUNTS_PERMISSION_REQUEST_CODE);
    }
    
    
    public String extractAddressFromAccountManager(){
    
        Pattern emailPattern = Patterns.EMAIL_ADDRESS; // API level 8
        Account[] accounts = AccountManager.get(activity).getAccountsByType("com.google");
        for (Account account : accounts) {
            if (emailPattern.matcher(account.name).matches()) {
                return account.name;
            }
        }
        return null;
    }
    

    }

提交回复
热议问题