Programmatically obtain the phone number of the Android phone

后端 未结 18 1692
南笙
南笙 2020-11-21 06:17

How can I programmatically get the phone number of the device that is running my android app?

18条回答
  •  隐瞒了意图╮
    2020-11-21 06:55

    So that's how you request a phone number through the Play Services API without the permission and hacks. Source and Full example.

    In your build.gradle (version 10.2.x and higher required):

    compile "com.google.android.gms:play-services-auth:$gms_version"
    

    In your activity (the code is simplified):

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        // ...
        googleApiClient = new GoogleApiClient.Builder(this)
                .addApi(Auth.CREDENTIALS_API)
                .build();
        requestPhoneNumber(result -> {
            phoneET.setText(result);
        });
    }
    
    public void requestPhoneNumber(SimpleCallback callback) {
        phoneNumberCallback = callback;
        HintRequest hintRequest = new HintRequest.Builder()
                .setPhoneNumberIdentifierSupported(true)
                .build();
    
        PendingIntent intent = Auth.CredentialsApi.getHintPickerIntent(googleApiClient, hintRequest);
        try {
            startIntentSenderForResult(intent.getIntentSender(), PHONE_NUMBER_RC, null, 0, 0, 0);
        } catch (IntentSender.SendIntentException e) {
            Logs.e(TAG, "Could not start hint picker Intent", e);
        }
    }
    
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == PHONE_NUMBER_RC) {
            if (resultCode == RESULT_OK) {
                Credential cred = data.getParcelableExtra(Credential.EXTRA_KEY);
                if (phoneNumberCallback != null){
                    phoneNumberCallback.onSuccess(cred.getId());
                }
            }
            phoneNumberCallback = null;
        }
    }
    

    This will generate a dialog like this:

提交回复
热议问题