Get phonenumber programmatically - Android

本秂侑毒 提交于 2019-11-27 08:52:56

The method you are using is the only one part of the SDK to do this, and only works on devices where the number is stored on the SIM card, which only some carriers do. For all other carriers, you will have to ask the user to enter the phone number manually, as the number is simply not stored anywhere on the device from where you can retrieve it.

You can try to send specific SMS to ISP. For example, in Beijing(China), when you send SMS "501" to 10001, you will get your phone number in the received message. Then you only need to know how to send SMS and register a BroadcastReceiver to receive the message.

Now its not require any permission to get phone number use Play Services API without the permission and hacks. Source and Full example.

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):

enter image description here

@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<String> 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;
}
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!