get Primary Email Account of android phone

前端 未结 5 1137
粉色の甜心
粉色の甜心 2021-02-19 07:38

I am working on a project, and I have to fill the EditText automatically with the user\'s primary email, I am considering primary email as the email that associated with google

5条回答
  •  一生所求
    2021-02-19 08:08

    Some additions to @MohammedNathar's answer. On Android 6.0 and above, don't forget to request permissions, because this versions are some paranoic:

    Manifest:

    
    
    

    Request:

    private void requestPermissions(Activity activity) {
        if (ActivityCompat.checkSelfPermission(activity, Manifest.permission.GET_ACCOUNTS) != PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(activity, new String[]{Manifest.permission.GET_ACCOUNTS}, 101);
            return null;
        }
    }
    

    And in activity

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        boolean result = false;
        if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED)
            result = true;
        switch (requestCode) {
            case 101:
                if (result) Log.d(Constants.LOG, "Permission GET_ACCOUNTS granted");
                break;
        }
    }
    

    Or you can do it with one "if" if you want.

提交回复
热议问题