How to get the mobile number of my device programmatically?
Asked Answered
C

5

7

I have tried using 2 methods for retrieving my phone number but both of them don't work. I used:

  1. TelephonyManager
  2. SubscriptionManager

I do get Network name, Country iso, and IMEI but whenever I try to return Number it returns nothing.

I have also added all the required permissions for these! My manifest looks like:

<uses-permission android:name="android.permission.READ_PHONE_STATE" />
<uses-permission android:name="android.permission.READ_PHONE_NUMBERS" />
<uses-permission android:name="android.permission.GET_ACCOUNTS" />

Code using TelephonyManager:

TelephonyManager phoneMgr = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
phoneMgr.getLine1Number()

Code using SubscriptionManager:

if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
        List<SubscriptionInfo> subscription = SubscriptionManager.from(getApplicationContext()).getActiveSubscriptionInfoList();
        for (int i = 0; i < subscription.size(); i++) {
            SubscriptionInfo info = subscription.get(i);
            Log.e("TAG", "number " + info.getNumber());
            Log.e("TAG", "network name : " + info.getCarrierName());
            Log.e("TAG", "country iso " + info.getCountryIso());
        }
    }

In both attempts I get nothing!

Is there any other way to get phone number or I'm doing something wrong?

Carapace answered 27/9, 2019 at 5:54 Comment(1)
Does this answer your question? Programmatically obtain the phone number of the Android phoneKerley
C
11

Nowadays the TelephonyManager does not help us. Play Services API without permission is good solution for this.

This dependency is useful for this

 implementation 'com.google.android.gms:play-services-auth:16.0.1'

Now inside your Activity.java:

GoogleApiClient  mGoogleApiClient = new GoogleApiClient.Builder(this)
                .addConnectionCallbacks(this)
                .addOnConnectionFailedListener(this)
                .addApi(Auth.CREDENTIALS_API)
                .build();

        if (mGoogleApiClient != null) {
            mGoogleApiClient.connect();
        }

After this do request for Phone Number:

 HintRequest hintRequest = new HintRequest.Builder()
                .setPhoneNumberIdentifierSupported(true)
                .build();

        PendingIntent intent = Auth.CredentialsApi.getHintPickerIntent(mGoogleApiClient, hintRequest);
        try {
            startIntentSenderForResult(intent.getIntentSender(), 1008, null, 0, 0, 0, null);
        } catch (IntentSender.SendIntentException e) {
            Log.e("", "Could not start hint picker Intent", e);
        }

Now you need to handle response in your onActivityResult like this:

    @Override
    public void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        switch (requestCode) {
            case 1008:
                if (resultCode == RESULT_OK) {
                    Credential cred = data.getParcelableExtra(Credential.EXTRA_KEY);
//                    cred.getId====: ====+919*******
                    Log.e("cred.getId", cred.getId());
                    userMob = cred.getId();


                } else {
                    // Sim Card not found!
                    Log.e("cred.getId", "1008 else");

                    return;
                }


                break;
        }
    }
Concealment answered 27/9, 2019 at 6:4 Comment(9)
@HuzaifaAsif have you tried this solution?? I am sure this will help youConcealment
Is there a way to get both numbers in my phone as i'm using dual sim phone? I'm getting just the primary one for nowCarapace
Its depending on the number linked with your gmail. You will get list of numbers which are linked with your primary gmailConcealment
But what if i had linked some other number with my gmail and i have a different sim card in my phone?Carapace
mGoogleApiClient will returns you whatever number registered with it, not any else.Concealment
It means even this method is not authentic in the sense that it might return the number of my sim!Carapace
Let us continue this discussion in chat.Concealment
It's shows GoogleApiClient is deprecated .What should I use?Augmentation
There resulting mobile numbers are not actually from the sim available in the phone. The mobile numbers are the numbers Synced with the Primary google accountAurore
S
4

I found @bhoomika's answer useful but now using GoogleApiClient is deprecated. So you can use CredentialsClient instead.

Below is the method I used to trigger the phone number hint dialog (this method is in a helper class).

public void requestPhoneNumberHint(Activity currentActivity) {
    HintRequest hintRequest = new HintRequest.Builder()
            .setPhoneNumberIdentifierSupported(true)
            .build();
    CredentialsClient credentialsClient = Credentials.getClient(currentActivity);

    PendingIntent intent = credentialsClient.getHintPickerIntent(hintRequest);
    try {
        uiListener.getCurrentActivity().startIntentSenderForResult(intent.getIntentSender(),
                RESOLVE_PHONE_NUMBER_HINT, null, 0, 0, 0);
    } catch (IntentSender.SendIntentException e) {
        e.printStackTrace();
    }
}

Below is my handling for the corresponding onActivityResult (my Activity code is in Kotlin)

override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
    if(requestCode == RESOLVE_PHONE_NUMBER_HINT){
        if (resultCode == RESULT_OK) {
           var credential : Credential?  = data?.getParcelableExtra(Credential.EXTRA_KEY)
            credential?.apply {
                processPhoneNumber(id)
            }
        }
    }

As mentioned in the below documentation, the result codes can be used to identify if there were no hints that were displayed or if the user did not chose any of the options.

public static final int ACTIVITY_RESULT_NO_HINTS_AVAILABLE Activity result code indicating that there were no hints available.

Constant Value: 1002 public static final int ACTIVITY_RESULT_OTHER_ACCOUNT Activity result code indicating that the user wishes to use a different account from what was presented in the credential or hint picker.

Constant Value: 1001

https://developers.google.com/android/reference/com/google/android/gms/auth/api/credentials/CredentialsApi#ACTIVITY_RESULT_NO_HINTS_AVAILABLE

Sled answered 16/11, 2020 at 20:10 Comment(0)
A
3

By using below code you current device phone number & after selecting phone number onActivity result will be called.

Gradle :

  implementation 'com.google.android.gms:play-services-auth:17.0.0'
  implementation 'com.google.android.gms:play-services-auth-api-phone:17.0.0'

Setup Google API Client :

    //set google api client for hint request
    mGoogleApiClient = new GoogleApiClient.Builder(this)
        .addConnectionCallbacks(this)
        .enableAutoManage(this, this)
        .addApi(Auth.CREDENTIALS_API)
        .build();

Get an available number :

public void getHintPhoneNumber() {
  HintRequest hintRequest =
      new HintRequest.Builder()
          .setPhoneNumberIdentifierSupported(true)
          .build();
  PendingIntent mIntent = Auth.CredentialsApi.getHintPickerIntent(mGoogleApiClient, hintRequest);
  try {
    startIntentSenderForResult(mIntent.getIntentSender(), RESOLVE_HINT, null, 0, 0, 0);
  } catch (IntentSender.SendIntentException e) {
    e.printStackTrace();
  }
}

Get Selected Number in onActivityResult :

@Override
  protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    //Result if we want hint number
    if (requestCode == RESOLVE_HINT) {
      if (resultCode == Activity.RESULT_OK) {

        Credential credential = data.getParcelableExtra(Credential.EXTRA_KEY);
        // credential.getId();  <-- will need to process phone number string
        inputMobileNumber.setText(credential.getId());
      }
    }
  }

Reference : https://androidwave.com/automatic-sms-verification-android/

Areopagus answered 27/9, 2019 at 6:8 Comment(5)
Your code is great. It helped! But is there a way to get numbers of multiple sims? As i'm currently using a dual sim but i'm getting the number of my primary sim for now!Carapace
Please go to the reference site which I already added sure it will work for youAreopagus
Actually my other phone number is not registered with google so that's why it is not returning it!Carapace
It's shows GoogleApiClient is deprecated .What should I use?Augmentation
It gives only one mobile number while my mobile is dual sim.Please help on this.Blanketing
S
1

Have you given access to READ_PHONE_STATE permission?

 <uses-permission android:name="android.permission.READ_PHONE_STATE"/> 
Subfamily answered 27/9, 2019 at 5:58 Comment(1)
I edited the question. I have added this permission also!Carapace
C
1

getLine1Number() should do the trick, but depending on the SIM-card this will not always be able to get the phone number

I suggest that if you do not get the number from getLine1Number(), then make the user type it in manually. (This is what iOS users have to do anyway)

EDIT:

Also, you should not use IMEI as of Android 10 you will not have permission to get that information

Cook answered 27/9, 2019 at 6:7 Comment(1)
It's not working on any device. Play Service API is the best solution.Nader

© 2022 - 2024 — McMap. All rights reserved.