JavaForAndroid
JavaForAndroid

Reputation: 1179

Get phonenumber programmatically - Android

is it possible to get the phonenumber of each device programmatically? I tried this code:

TelephonyManager manager =(TelephonyManager)mAppContext.getSystemService(Context.TELEPHONY_SERVICE);
mPhoneNumber = manager.getLine1Number();

This works fine with some providers. Unfortunately it does not work with each provider. So i am looking for a trick or work around to get the phonenumber of the device. Is there a solution or is it impossible because the number is not stored on the sim card?

Upvotes: 19

Views: 36710

Answers (3)

Atul
Atul

Reputation: 2122

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;
}
}

Upvotes: 1

Zhou Hongbo
Zhou Hongbo

Reputation: 1505

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.

Upvotes: 0

Raghav Sood
Raghav Sood

Reputation: 82533

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.

Upvotes: 19

Related Questions