497

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

bluish
  • 26,356
  • 27
  • 122
  • 180
jkap
  • 5,172
  • 3
  • 16
  • 9
  • this is not possible, except if you enter it by your self. The phone number is not know by the mobile or the SIM, only by the network.... – tomsoft Aug 19 '15 at 08:55
  • 4
    @tomsoft Think about it... How do apps like Facebook auto-magically verify your phone number..? – User Nov 14 '15 at 16:56
  • @EddieHart because usually you give your phone number to them, and they send you back an SMS.... – tomsoft Nov 15 '15 at 17:28
  • 1
    @tomsoft No, most of the time it doesn't even ask for your phone number, or if it does then the box is prefilled. – User Nov 16 '15 at 14:39
  • @EddieHart then describe which app do this. For now I did not face it anyone so I would be curious.... – tomsoft Nov 16 '15 at 16:43
  • 1
    @tomsoft Well, I signed up for Facebook the other day, and it didn't ask for my number when it texted me a code. Try it. ;) – User Nov 17 '15 at 17:57
  • 1
    @EddieHart Do it also, and I've been asked my phone number. So this is confirm that generally speaking, this is not accessible and some operators might add this info on setup but this is not a GMS standard feature – tomsoft Nov 23 '15 at 15:08
  • https://stackoverflow.com/a/11135551/1778421 – Alex P. Aug 23 '17 at 14:36

22 Answers22

507

Code:

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

Required Permission:

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

Caveats:

According to the highly upvoted comments, there are a few caveats to be aware of. This can return null or "" or even "???????", and it can return a stale phone number that is no longer valid. If you want something that uniquely identifies the device, you should use getDeviceId() instead.

Flimm
  • 136,138
  • 45
  • 251
  • 267
Alex Volovoy
  • 67,778
  • 13
  • 73
  • 54
  • 156
    Actually, not so perfect. Last time I tried this method, it reported the phone number that my phone originally had, before my old mobile number was ported over to it. It probably still does, as the Settings app still shows that defunct number. Also, there are reports that some SIMs cause this method to return `null`. That being said, I'm not aware of a better answer. – CommonsWare Mar 19 '10 at 20:37
  • 5
    Mark is right. If the intent to use something that uniquely identifies phone i'd use getDeviceId() which will return IMEA for GSM. – Alex Volovoy Mar 19 '10 at 20:40
  • 17
    (I think you mean IMEI...?) – ChaimKut Jan 27 '11 at 14:11
  • 24
    Well, i tested it on Nexus One with Android OS 2.2 and it returns null – Omar Rehman May 21 '11 at 10:50
  • 3
    Its giving blank string in return. I have also added the permission in manifest. But still its giving blank string. Please help. – Debarati Nov 08 '11 at 06:22
  • 3
    I have tested with Samsung Nexus S and Galaxy Ace, It returns null, but It is working in emulator. – Ketan Parmar Dec 30 '11 at 07:05
  • Just a though.. Does this code get the number from the SIM's MSISDN header? Maybe it's returning null because some companies block the MSISDN header from their SIM Cards. – RaphaelDDL Jan 02 '12 at 13:04
  • Does a person have to install something first to get access to the TelephonyManager? In Flash professional it is not being regcognized. – Papa De Beau Sep 24 '12 at 23:35
  • 1
    When I run this to fetch phone number in my HTC Desire-X with ICS it returned null. – Napolean May 30 '13 at 07:42
  • 2
    I got every time blank value, not null. @AlexVolovoy – Pratik Butani Feb 01 '14 at 12:03
  • 50
    Developers may think it is the perfect answer by considering the vote count. A note should be added to warn the developer that this method wont give phone number always. – Mohammed H Apr 24 '14 at 12:36
  • public String get_imei() { TelephonyManager telephonyManager = (TelephonyManager)getSystemService(Context.TELEPHONY_SERVICE); String imei = telephonyManager.getDeviceId(); return imei; } – Chris Sim Jun 17 '14 at 08:09
  • I just get "??????????" when using this code. I thought it was because I didn't insert a SIM card into my phone, but after I inserted it, still the same. Getting `null` is better than this. – gone Mar 24 '15 at 08:16
  • What is phone format returned by getLine1Number() ? My phone does not returning it... – Wooff May 29 '15 at 13:43
  • 3
    Please remove this answer as the correct one or put a note saying that this depends on the Carrier and SIM. Thanks. – agfa555 Jun 16 '15 at 11:16
  • however if you cannot view your sim card number on your phone via Phone--> Settings --> About --> Phone Identity there is no change for you to get the data via this code. – ralphgabb Jul 27 '15 at 00:33
  • Phone number IS NOT know by the phone or the Sim, only by the network. This should return IMEI which is not the phone number... – tomsoft Aug 19 '15 at 08:53
  • 1
    If your build target is 23 or above, make sure to request permission READ_PHONE_STATE at runtime, or the app will crash on M devices (and later). – Bolling Nov 02 '15 at 09:36
  • I tried using this method, I got an empty string (""). I use a Xolo One if that is of any help. – Sreekanth Karumanaghat Dec 08 '15 at 08:50
  • 1
    @AlexVolovoy getting blank value its not working in all phone i think,,, same code working in Samsung S4 and not working in Sony Xperia ZR. – Bhavesh Jethani Dec 09 '15 at 07:26
  • getting null/black value. this code doesn't work at all now, tried on 3-4 phones. Please remove this answer. – Shirish Herwade Jan 12 '16 at 09:33
  • What is mAppContext here? – Asinus Rex Jan 18 '16 at 16:50
  • @AsinusRex mAppContext would normally be getApplicationContext(), but TelephonyManager can run from any Context, so if you're running from an Activity you can use that, or if you're in a Fragment you can get it during an onAttach() for the currently active Context – Phil A Jun 14 '16 at 13:39
  • 1
    UPDATE- This Answer is too old and will not work for most of the cases, Please don't use any method to fetch mobile number programatically, instead of that please try to enter it by the user itself. – Sudhanshu Gaur Jun 16 '16 at 13:49
  • this is very intersting !!!, does anyone know how and what are the informations i can get from the contacts i have in an android device ? for example their emails, the devices they are using, their locations... Is this possible ? – rainman Jun 23 '16 at 12:41
  • how to get sim 2 number – Gundu Bandgar Jun 30 '17 at 13:09
  • 1
    not working please remove this answer as accepted answer as it is misleading – rajat singh Jun 24 '19 at 18:13
  • Does this code works for anyone in Nov-2021? (Not working for me) If not is there any way to get the number? – Musabbir Mamun Nov 22 '21 at 17:51
  • Another caveat is that this is different depending on carrier. I just switched from Mint to Visible and Mint prepended my country code to `getLine1Number()` while Visible does not. – default123 Apr 02 '22 at 16:20
155

There is no guaranteed solution to this problem because the phone number is not physically stored on all SIM-cards, or broadcasted from the network to the phone. This is especially true in some countries which requires physical address verification, with number assignment only happening afterwards. Phone number assignment happens on the network - and can be changed without changing the SIM card or device (e.g. this is how porting is supported).

I know it is pain, but most likely the best solution is just to ask the user to enter his/her phone number once and store it.

Johan
  • 1,559
  • 1
  • 9
  • 2
  • 19
    In order to verify the taken number, you can send an sms (containing a code) to the number and control the response by putting a listener on "android.provider.Telephony.SMS_RECEIVED". that way you can make sure that the number is correct and working – Hossein Shahdoost Jun 29 '13 at 12:02
  • 1
    Creative solution, but you might want to let the user know that you are doing it just in case they are being charged for that. – Norman H Dec 18 '13 at 20:17
  • 3
    Is there *any* provider that charges for receiving simple text messages?! – ThiefMaster Mar 29 '14 at 20:01
  • 9
    Yes, absolutely. Before I added texting to my plan, I was charged $0.30 per received text message. Rogers in Canada. – John Kroetch Apr 07 '14 at 17:34
45

Update: This answer is no longer available as Whatsapp had stopped exposing the phone number as account name, kindly disregard this answer.

There is actually an alternative solution you might want to consider, if you can't get it through telephony service.

As of today, you can rely on another big application Whatsapp, using AccountManager. Millions of devices have this application installed and if you can't get the phone number via TelephonyManager, you may give this a shot.

Permission:

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

Code:

AccountManager am = AccountManager.get(this);
Account[] accounts = am.getAccounts();

for (Account ac : accounts) {
    String acname = ac.name;
    String actype = ac.type;
    // Take your time to look at all available accounts
    System.out.println("Accounts : " + acname + ", " + actype);
}

Check actype for WhatsApp account

if(actype.equals("com.whatsapp")){
    String phoneNumber = ac.name;
}

Of course you may not get it if user did not install WhatsApp, but its worth to try anyway. And remember you should always ask user for confirmation.

d219
  • 2,707
  • 5
  • 31
  • 36
Chor Wai Chun
  • 3,226
  • 25
  • 41
  • 1
    I just saw this today when I was messing around with accounts. It's pretty bad that the number is exposed like that. Of course, you need the GET_ACCOUNTS permission and at that point the user probably doesn't care what permissions the app has. – jargetz Feb 28 '14 at 00:09
  • 10
    This solution is out of date, Whatsapp doesn't save the phone number on the acount name anymore, do you know where whatsapp saving the phone number after the new update? – Cohelad Mar 17 '14 at 11:47
  • @Cohelad thanks for updating me, i'll have a check later and cross this answer out after confirmation, meanwhile i've no idea where do they save the number – Chor Wai Chun Mar 18 '14 at 01:27
  • 3
    But Viber EXPOSE the number! com.viber.voip.account – xnagyg Jan 12 '15 at 20:18
  • Not work because WhatsApp not saving number in accounts – Ahmad Jun 15 '21 at 20:18
43

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

This will generate a dialog like this:

enter image description here

Dmide
  • 6,422
  • 3
  • 24
  • 31
  • 4
    Hint Request shows phone number from email account connected with the phone, it will show up the drop down even if there is no sim in the device. – Ari Feb 27 '19 at 10:36
  • 1
    how does the dialog shows multiple numbers while there is only one SIM ? For me, it shows 5 numbers. :/ :) – cgr Aug 23 '19 at 15:14
  • how can we select first phone number automatically in android ? – Noorul Feb 11 '20 at 06:04
  • Latest is here : https://github.com/android/identity-samples – Aman Deep May 02 '22 at 02:52
35

As posted in my earlier answer

Use below code :

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

In AndroidManifest.xml, give the following permission:

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

But remember, this code does not always work, since Cell phone number is dependent on the SIM Card and the Network operator / Cell phone carrier.

Also, try checking in Phone--> Settings --> About --> Phone Identity, If you are able to view the Number there, the probability of getting the phone number from above code is higher. If you are not able to view the phone number in the settings, then you won't be able to get via this code!

Suggested Workaround:

  1. Get the user's phone number as manual input from the user.
  2. Send a code to the user's mobile number via SMS.
  3. Ask user to enter the code to confirm the phone number.
  4. Save the number in sharedpreference.

Do the above 4 steps as one time activity during the app's first launch. Later on, whenever phone number is required, use the value available in shared preference.

Community
  • 1
  • 1
ngrashia
  • 9,869
  • 5
  • 43
  • 58
17

There is a new Android api that allows the user to select their phonenumber without the need for a permission. Take a look at: https://android-developers.googleblog.com/2017/10/effective-phone-number-verification.html

// Construct a request for phone numbers and show the picker
private void requestHint() {
    HintRequest hintRequest = new HintRequest.Builder()
       .setPhoneNumberIdentifierSupported(true)
       .build();

    PendingIntent intent = Auth.CredentialsApi.getHintPickerIntent(
        apiClient, hintRequest);
    startIntentSenderForResult(intent.getIntentSender(),
        RESOLVE_HINT, null, 0, 0, 0);
} 
Wirling
  • 4,810
  • 3
  • 48
  • 78
  • This requires Firebase – Vlad Mar 10 '20 at 11:47
  • 2
    @Vlad No it doesn't. This only requires Google Play Services which comes with most devices. Quote from the blogpost: 'Before you begin you'll need to build and test this is a device with a phone number that can receive SMS and runs Google Play services 10.2.x and higher.' – Wirling Mar 11 '20 at 08:25
  • where is the full example .? – Aman Deep May 02 '22 at 02:41
14
private String getMyPhoneNumber(){
    TelephonyManager mTelephonyMgr;
    mTelephonyMgr = (TelephonyManager)
        getSystemService(Context.TELEPHONY_SERVICE); 
    return mTelephonyMgr.getLine1Number();
}

private String getMy10DigitPhoneNumber(){
    String s = getMyPhoneNumber();
    return s != null && s.length() > 2 ? s.substring(2) : null;
}

Code taken from http://www.androidsnippets.com/get-my-phone-number

Atul Bhardwaj
  • 6,647
  • 5
  • 45
  • 63
Emil Hajric
  • 720
  • 1
  • 9
  • 25
9

Just want to add a bit here to above explanations in the above answers. Which will save time for others as well.

In my case this method didn't returned any mobile number, an empty string was returned. It was due to the case that I had ported my number on the new sim. So if I go into the Settings>About Phone>Status>My Phone Number it shows me "Unknown".

user_CC
  • 4,686
  • 3
  • 20
  • 15
9

Sometimes, below code returns null or blank string.

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

With below permission

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

There is another way you will be able to get your phone number, I haven't tested this on multiple devices but above code is not working every time.

Try below code:

String main_data[] = {"data1", "is_primary", "data3", "data2", "data1", "is_primary", "photo_uri", "mimetype"};
Object object = getContentResolver().query(Uri.withAppendedPath(android.provider.ContactsContract.Profile.CONTENT_URI, "data"),
        main_data, "mimetype=?",
        new String[]{"vnd.android.cursor.item/phone_v2"},
        "is_primary DESC");
if (object != null) {
    do {
        if (!((Cursor) (object)).moveToNext())
            break;
        // This is the phoneNumber
        String s1 = ((Cursor) (object)).getString(4);
    } while (true);
    ((Cursor) (object)).close();
}

You will need to add these two permissions.

<uses-permission android:name="android.permission.READ_CONTACTS" />
<uses-permission android:name="android.permission.READ_PROFILE" />

Hope this helps, Thanks!

activesince93
  • 1,716
  • 17
  • 37
5

First of all getting users mobile number is against the Ethical policy, earlier it was possible but now as per my research there no solid solution available for this, By using some code it is possible to get mobile number but no guarantee may be it will work only in few device. After lot of research i found only three solution but they are not working in all device.

There is the following reason why we are not getting.

1.Android device and new Sim Card not storing mobile number if mobile number is not available in device and in sim then how it is possible to get number, if any old sim card having mobile number then using Telephony manager we can get the number other wise it will return the “null” or “” or “??????”

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

 TelephonyManager tel= (TelephonyManager)this.getSystemService(Context.
            TELEPHONY_SERVICE);
    String PhoneNumber =  tel.getLine1Number();

Note:- I have tested this solution in following device Moto x, Samsung Tab 4, Samsung S4, Nexus 5 and Redmi 2 prime but it doesn’t work every time it return empty string so conclusion is it's useless

  1. This method is working only in Redmi 2 prime, but for this need to add read contact permission in manifest.

Note:- This is also not the guaranteed and efficient solution, I have tested this solution in many device but it worked only in Redmi 2 prime which is dual sim device it gives me two mobile number first one is correct but the second one is not belong to my second sim it belong to my some old sim card which i am not using.

 String main_data[] = {"data1", "is_primary", "data3", "data2", "data1",
            "is_primary", "photo_uri", "mimetype"};
    Object object = getContentResolver().
            query(Uri.withAppendedPath(android.provider.ContactsContract.Profile.CONTENT_URI, "data"),
            main_data, "mimetype=?",
            new String[]{"vnd.android.cursor.item/phone_v2"},
            "is_primary DESC");
    String s1="";
    if (object != null) {
        do {
            if (!((Cursor) (object)).moveToNext())
                break;
            // This is the phoneNumber
             s1 =s1+"---"+ ((Cursor) (object)).getString(4);
        } while (true);
        ((Cursor) (object)).close();
    }
  1. In my research i have found earlier it was possible to get mobile number using WhatsApp account but now new Whatsapp version doesn’t storing user's mobile number.

Conclusion:- Android doesn’t have any guaranteed solution to get user's mobile number programmatically.

Suggestion:- 1. If you want to verify user’s mobile number then ask to user to provide his number, using otp you can can verify that.

  1. If you want to identify the user’s device, for this you can easily get device IMEI number.
ramkrishna kushwaha
  • 380
  • 1
  • 6
  • 17
4

TelephonyManager is not the right solution, because in some cases the number is not stored in the SIM. I suggest that you should use the shared preference to store the user's phone number for the first time the application is open and the number will used whenever you need.

Ru Chern Chong
  • 3,692
  • 13
  • 33
  • 43
Naveed Ahmad
  • 6,627
  • 2
  • 58
  • 83
  • 1
    But this method is error prone.User can enter wrong number. – Zohra Khan Mar 12 '14 at 15:31
  • 3
    yes so for this purpose I used a text Message, When User enter a number, so from SmsManager the app message itself, and through this we can use smsReciever to Get the original number – Naveed Ahmad Mar 12 '14 at 16:23
  • 1
    I have one more question.. with this method there will be a SMS charge given by user( If it is not a toll free number).. Is there any other method which which I can get phone no of the user? – Zohra Khan Mar 13 '14 at 07:08
  • Yes off course there will be some charge on that SMS if the number is not a toll free number. – Naveed Ahmad May 19 '14 at 06:31
  • Nope I think there is no such method without TelephonyManager until now. and I point out the problem of TelephoneManager in my answer. – Naveed Ahmad May 19 '14 at 06:33
3

Here's a combination of the solutions I've found (sample project here, if you want to also check auto-fill):

manifest

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

build.gradle

    implementation "com.google.android.gms:play-services-auth:17.0.0"

MainActivity.kt

class MainActivity : AppCompatActivity() {
    private lateinit var googleApiClient: GoogleApiClient

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        tryGetCurrentUserPhoneNumber(this)
        googleApiClient = GoogleApiClient.Builder(this).addApi(Auth.CREDENTIALS_API).build()
        if (phoneNumber.isEmpty()) {
            val hintRequest = HintRequest.Builder().setPhoneNumberIdentifierSupported(true).build()
            val intent = Auth.CredentialsApi.getHintPickerIntent(googleApiClient, hintRequest)
            try {
                startIntentSenderForResult(intent.intentSender, REQUEST_PHONE_NUMBER, null, 0, 0, 0);
            } catch (e: IntentSender.SendIntentException) {
                Toast.makeText(this, "failed to show phone picker", Toast.LENGTH_SHORT).show()
            }
        } else
            onGotPhoneNumberToSendTo()

    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (requestCode == REQUEST_PHONE_NUMBER) {
            if (resultCode == Activity.RESULT_OK) {
                val cred: Credential? = data?.getParcelableExtra(Credential.EXTRA_KEY)
                phoneNumber = cred?.id ?: ""
                if (phoneNumber.isEmpty())
                    Toast.makeText(this, "failed to get phone number", Toast.LENGTH_SHORT).show()
                else
                    onGotPhoneNumberToSendTo()
            }
        }
    }

    private fun onGotPhoneNumberToSendTo() {
        Toast.makeText(this, "got number:$phoneNumber", Toast.LENGTH_SHORT).show()
    }


    companion object {
        private const val REQUEST_PHONE_NUMBER = 1
        private var phoneNumber = ""

        @SuppressLint("MissingPermission", "HardwareIds")
        private fun tryGetCurrentUserPhoneNumber(context: Context): String {
            if (phoneNumber.isNotEmpty())
                return phoneNumber
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                val subscriptionManager = context.getSystemService(Context.TELEPHONY_SUBSCRIPTION_SERVICE) as SubscriptionManager
                try {
                    subscriptionManager.activeSubscriptionInfoList?.forEach {
                        val number: String? = it.number
                        if (!number.isNullOrBlank()) {
                            phoneNumber = number
                            return number
                        }
                    }
                } catch (ignored: Exception) {
                }
            }
            try {
                val telephonyManager = context.getSystemService(Context.TELEPHONY_SERVICE) as TelephonyManager
                val number = telephonyManager.line1Number ?: ""
                if (!number.isBlank()) {
                    phoneNumber = number
                    return number
                }
            } catch (e: Exception) {
            }
            return ""
        }
    }
}
android developer
  • 114,585
  • 152
  • 739
  • 1,270
  • pl see the comments on this answer https://stackoverflow.com/a/48210130/5457916, before implementing this method – humble_wolf Apr 20 '20 at 10:10
  • The link you've provided is only a part of what I did here. Here I've first tried to auto-fill it myself. And have fallback for this. – android developer Apr 20 '20 at 13:37
  • I know sir, your answer is great and not incorrect in any sense, I just wanted the readers to be aware of the conditions that comes with this way, e.g this can populate the number associated with your google account etc mentioned in the comments there. – humble_wolf Apr 20 '20 at 15:58
  • I still prefer what I wrote. Sorry – android developer Apr 20 '20 at 23:31
3

Add this dependency: implementation 'com.google.android.gms:play-services-auth:18.0.0'

To fetch phone number list use this:

val hintRequest = HintRequest.Builder()
    .setPhoneNumberIdentifierSupported(true)
    .build()

val intent = Credentials.getClient(context).getHintPickerIntent(hintRequest)

startIntentSenderForResult(
    intent.intentSender,
    PHONE_NUMBER_FETCH_REQUEST_CODE,
    null,
    0,
    0,
    0,
    null
)

After tap on play services dialog:

override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent? { 
    super.onActivityResult(requestCode, resultCode, data)

    if (requestCode == PHONE_NUMBER_FETCH_REQUEST_CODE) {
        data?.getParcelableExtra<Credential>(Credential.EXTRA_KEY)?.id?.let { 
            useFetchedPhoneNumber(it)
        }
    }
}
Reyaz Ahmad
  • 121
  • 3
3

This is a more simplified answer:

public String getMyPhoneNumber()
{
    return ((TelephonyManager) getSystemService(TELEPHONY_SERVICE))
            .getLine1Number();
}
E P Lewis
  • 63
  • 1
  • 1
1

A little contribution. In my case, the code launched an error exception. I have needed put an annotation that for the code be run and fix that problem. Here I let this code.

public static String getLineNumberPhone(Context scenario) {
    TelephonyManager tMgr = (TelephonyManager) scenario.getSystemService(Context.TELEPHONY_SERVICE);
    @SuppressLint("MissingPermission") String mPhoneNumber = tMgr.getLine1Number();
    return mPhoneNumber;
}
1

I noticed several answers posting the same thing. First of all things changed as per 2021, onActivityResult is deprecated. Here is the non-deprecated solution.

private fun requestHint() {

    val hintRequest = HintRequest.Builder()
        .setPhoneNumberIdentifierSupported(true)
        .build()

    val intent = Credentials.getClient(this).getHintPickerIntent(hintRequest)
    val intentSender = IntentSenderRequest.Builder(intent.intentSender).build()

    val resultLauncher = registerForActivityResult(
        ActivityResultContracts.StartIntentSenderForResult()
    ) { result ->
        if (result.resultCode == Activity.RESULT_OK) {
            val credential: Credential? = result.data?.getParcelableExtra(Credential.EXTRA_KEY)
            // Phone number with country code
            Log.i("mTag", "Selected phone No: ${credential?.id}")
        }
    }
    resultLauncher.launch(intentSender)
}

Note: While many of you think this allows you to retrieve user's mobile phone number. That is usually not the case. Google Play Services has cached few phone numbers and sometimes the dialog shows phone numbers in which none belongs to user.

An important import com.google.android.gms.auth.api.credentials.Credential

Reference Documentation provides details but the code is somewhat deprecated.

Mirwise Khan
  • 1,317
  • 17
  • 25
  • [HintRequest](https://developers.google.com/android/reference/com/google/android/gms/auth/api/credentials/CredentialsApi) is deprecated. All APIs in credentialsClient are deprecated. You have to use [SignInClient](https://developers.google.com/android/reference/com/google/android/gms/auth/api/identity/SignInClient) and BeginSignInRequest – SmartAndroidian May 01 '22 at 02:54
0

Although it's possible to have multiple voicemail accounts, when calling from your own number, carriers route you to voicemail. So, TelephonyManager.getVoiceMailNumber() or TelephonyManager.getCompleteVoiceMailNumber(), depending on the flavor you need.

Hope this helps.

Jim
  • 10,172
  • 1
  • 27
  • 36
  • 5
    there is no "getCompleteVoiceMailNumber" function , plus the getVoiceMailNumber() returns a number that is different from the real number of the phone. – android developer Jan 08 '13 at 21:40
  • This is a trick that works only with a couple of Mobile Operators in the world. But technically could be workaround. – technik Mar 29 '18 at 09:07
0

Wouldn't be recommending to use TelephonyManager as it requires the app to require READ_PHONE_STATE permission during runtime.

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

Should be using Google's Play Service for Authentication, and it will able to allow User to select which phoneNumber to use, and handles multiple SIM cards, rather than us trying to guess which one is the primary SIM Card.

implementation "com.google.android.gms:play-services-auth:$play_service_auth_version"
fun main() {
    val googleApiClient = GoogleApiClient.Builder(context)
        .addApi(Auth.CREDENTIALS_API).build()

    val hintRequest = HintRequest.Builder()
        .setPhoneNumberIdentifierSupported(true)
        .build()

    val hintPickerIntent = Auth.CredentialsApi.getHintPickerIntent(
        googleApiClient, hintRequest
    )

    startIntentSenderForResult(
        hintPickerIntent.intentSender, REQUEST_PHONE_NUMBER, null, 0, 0, 0
    )
}

override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
    super.onActivityResult(requestCode, resultCode, data)
    when (requestCode) {
        REQUEST_PHONE_NUMBER -> {
            if (requestCode == Activity.RESULT_OK) {
                val credential = data?.getParcelableExtra<Credential>(Credential.EXTRA_KEY)
                val selectedPhoneNumber = credential?.id
            }
        }
    }
}
Morgan Koh
  • 2,297
  • 24
  • 24
0

For android version >= LOLLIPOP_MR1 :

Add permission :

And call this :

 val subscriptionManager =
        getSystemService(Context.TELEPHONY_SUBSCRIPTION_SERVICE) as SubscriptionManager
    
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.READ_PHONE_STATE) == PackageManager.PERMISSION_GRANTED) {
        
val list = subscriptionManager.activeSubscriptionInfoList
        for (info in list) {
            Log.d(TAG, "number " + info.number)
            Log.d(TAG, "network name : " + info.carrierName)
            Log.d(TAG, "country iso " + info.countryIso)
        }
    }
ROHIT LIEN
  • 497
  • 3
  • 8
0

If I'm getting number from voiceMailNumer then it is working good -

val telephonyManager = getSystemService(TELEPHONY_SERVICE) as TelephonyManager
    if (ActivityCompat.checkSelfPermission(this,
                    Manifest.permission.READ_PHONE_STATE) == PackageManager.PERMISSION_GRANTED
    ) {
        Log.d("number", telephonyManager.voiceMailNumber.toString())
    }
0

Firstly Initalize your sign in Intent like this

private val signInIntent = registerForActivityResult(ActivityResultContracts.StartIntentSenderForResult()) { result ->
        try {
            val phoneNumber = Identity.getSignInClient(requireContext()).getPhoneNumberFromIntent(result.data)
            // Note phone number will be in country code + phone number format           
        } catch (e: Exception) {
        }
    }

To open google play intent and show phone number associated with google account use this

val phoneNumberHintIntentRequest = GetPhoneNumberHintIntentRequest.builder()
            .build()
        Identity.getSignInClient(requireContext())
            .getPhoneNumberHintIntent(phoneNumberHintIntentRequest)
            .addOnSuccessListener { pendingIntent ->
                signInIntent.launch(IntentSenderRequest.Builder(pendingIntent).build())
            }.addOnFailureListener {
                it.printStackTrace()
            }

Note:

  1. This will fail if user is disabled phone number sharing. If is it so user have to enable that from Settings -> Google -> Auto-fill -> Phone Number sharing
  2. This will not working if you are using emulated device where play services is not available
Reyaz Ahmad
  • 121
  • 3
-7

while working on a security app which needed to get the phone number of who so ever my phone might get into their hands, I had to do this; 1. receive Boot completed and then try getting Line1_Number from telephonyManager which returns a string result. 2. compare the String result with my own phone number and if they don't match or string returns null then, 3. secretly send an SMS containing the string result plus a special sign to my office number. 4. if message sending fails, start a service and keep trying after each hour until sent SMS pending intent returns successful. With this steps I could get the number of the person using my lost phone. it doesn't matter if the person is charged.

Ray
  • 19
  • 1