How can I programmatically get the phone number of the device that is running my android app?
15 Answers
Code:
Required Permission:
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.
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.
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:
Code:
Check actype
for WhatsApp account
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.
As posted in my earlier answer
Use below code :
In AndroidManifest.xml, give the following permission:
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.
Heathkit radios to build. 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:
- Get the user's phone number as manual input from the user.
- Send a code to the user's mobile number via SMS.
- Ask user to enter the code to confirm the phone number.
- 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.
Code taken from http://www.androidsnippets.com/get-my-phone-number
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'.
Sometimes, below code returns null
or blank string.
With below permission
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:
You will need to add these two permissions.
Hope this helps,Thanks!
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
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):
In your activity (the code is simplified):
This will generate a dialog like this:
TelephonyManager is not the right Solution,Because in some cases the number is not stored in the SIM, Due to my suggestion,You should use Shared Preference to store user's Phone number first time the application is open, and after that the number will used whenever you need in application.
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 “??????”
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
- This method is working only in Redmi 2 prime, but for this need to addread contact permission in manifest.
Download game naruto ultimate ninja 5 untuk pc tanpa emulator. 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.
- 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.
- If you want to identify the user’s device, for this you can easily get device IMEI number.
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.
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.
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.
protected by Community♦Jan 3 '13 at 10:14
Thank you for your interest in this question. Because it has attracted low-quality or spam answers that had to be removed, posting an answer now requires 10 reputation on this site (the association bonus does not count).
Would you like to answer one of these unanswered questions instead?
Not the answer you're looking for? Browse other questions tagged androidphone-numbertelephonymanager or ask your own question.
v1.7: Aggiunto il supporto ai dispositivi dual sim con android 5.1 e superiori
il codice iccid solitamente è composto da 19 cifre, in casi contrari verrà mostrato un avviso a schermo, si consiglia di contattare l'operatore che ha rilasciato la Sim nel caso in cui l'identificativo rilevato non dovesse essere formato da 19 cifre per chiarimenti
v2.0: La nuova versione 2.0 porta una ventata fresca al design dell'applicazione con nuova icona ed interfaccia, l'utilizzo dei bundle android e delle nuove librerie AndroidX
---------------------------
Ringraziamenti speciali:
Giulio Fagioli (Remeic) per l'icona ed il mockup grafico
Rubens Rainelli per l'idea
---------------------------
1.7.5 (Beta) Inserita gestione di iccid Anomali da 16, 20 e 22 caratteri
1.7.6 (Beta) Ridotta dimensione caratteri, aggiunta possibilità di vedere iccid originale per iccid errati
2.0 Ultimi ritocchi grafici, vedi changelog sopra 1.7.4->1.7.6
2.0.1 Fix per android Pie
All GSM devices use a SIM, a secure smart card, which holds information about the network and the user setting. Android currently provides a read-only interface via the telephony APIs, to access the physical device and SIM information. So, what does the information constitute, and how is it useful? Let’s first get familiar with the context and the basics, before delving into the telephony API.
Telephony metrics relevant to programming
Telephony-related metrics can be broadly classified into SIM-related information, physical device-related information, and network provider-related information. Table 1 summarises some important metrics.
SIM | Physical Device | Network Provider |
Serial Number | Device ID | Call state |
Subscriber ID | Software version | Country |
Country | Phone type | Operator |
State | USB vendor ID | Operator name |
Operator name | S/N or serial number | Operator location |
The information above includes the following:
- The SIM Serial Number (SSN) on the SIM card uniquely identifies the SIM card. It’s also referred to as the Integrated Circuit Card ID (ICCID). This holds information related to the SIM’s country, state and operator.
- The International Mobile Subscriber Identity (IMSI) identifies the subscriber (Subscriber ID), and network details such as the provider network’s operator country, operator code/name and network state. In addition, Location Area Identity (LAI) provides the region within a provider network, which appears as the operator’s location.
- The International Mobile Equipment Identity (IMEI) number uniquely identifies a GSM device internationally. This number is often printed on the instrument panel, and can usually be retrieved by typing
*#06#
on the phone’s keypad. A stolen or lost phone is tracked (or blocked) by its IMEI. - In addition to the above metrics, during the setup of a development environment with a real device, programmers need to determine a few physical device metrics, such as: (a) USB vendor ID of the device, for the creation of permissions for the device in app debug mode, and (b) device serial number (that appears as a S/N) printed on the device — this is seen as the device, when testing and developing in an IDE such as Eclipse (see Figure 1). Though many popular USB vendor IDs are publicly listed, yours may not be. Both these bits of information can be retrieved using a procedure listed in the box item below.
Retrieving crucial hardware device metrics |
To retrieve the USB ID, use lsusb , as shown below:Advertisement The above two lines indicate two mobile phones connected to my system via USB, in device debug mode. The four-digit vendor ID of the HTC phone is 0bb4 and that of the unlisted Micromax (appears as ONDA) is 19d2. Along with the vendor ID are the bus number details (001) of the phone, and the device number (005/006). You may note that the device number is not constant, and will change each time you plug/unplug the phone, or enable/disable debugging on your device. Type the following to determine the serial number and the OS details of the mobile (in this case, the HTC), using udev, which is used by the OS to dynamically map, present, and control USB devices: |
The Android Telephony package
Programmers will need ways to not just retrieve telephony data, but also to dial a phone number, intercept outgoing phone calls, or send/receive SMS messages. This is achieved with a combination of classes provided in the android.telephony package, along with inbuilt Intents and phone services.
The most important of these is the TelephonyManager class, which can be used to retrieve metadata about the SIM card, the physical device and the network provider. Programmers will need to use the Android Context, through the getSystemService()
method, with a constant as shown below, to obtain an instance of the TelephonyManager
class.
With this handle, telephony data can be retrieved. Sample code to retrieve the phone’s call state, using the getCallState() method, is shown below.
Additionally, it is often important to know the change in the call or service state of the phone, in an app. For example, you may want to mute your application when a call arrives. This is done by attaching a listener, called PhoneStateListener to the TelephonyManager
.
Finally, it is important to note that information retrieval via TelephonyManager
is permission-protected. For the application to access this information, the android.permission.READ_PHONE_STATE
permission has to be set in the app’s manifest.xml
. Figure 2 shows some metrics retrieved using TelephonyManager
.
The Android emulator includes a mock GSM modem that you can manipulate using the gsm
command from the console. An alternative would be to simply use the Swiss knife, which is the Dalvik debug monitoring service (DDMS), which lets you simulate special device status and activities.
With respect to Telephony actions, you can simulate phone calls and send/receive SMS messages to/from the emulator. Other than this, the state of the phone, the network speed and latency (GPRS, EDGE, UMTS, etc.,) can also be set. DDMS can be launched from the tools/
directory in your Android SDK distribution. As we discussed earlier, it could be useful for situations where the existing functionality of App needs to be enhanced with SMS sending feature. Or for building specialized SMS App, such as being able to set a time when the message would leave your phone.
With this background, let’s look at the steps to incorporate SMS feature. As we discussed earlier, it could be useful for situations where the existing functionality of App needs to be enhanced with SMS sending feature. Or for building specialized SMS App, such as being able to set a time when the message would leave your phone.
The steps to sending a simple text message:
- The app incorporates the
android.telephony
package. - Permissions must be set in the manifest file to send and receive SMS messages, as shown below:
- Send SMS —
android.permission.SEND_SMS
- Receive SMS —
android.permission.RECEIVE_SMS
- Send SMS —
- The app uses an instance of
SmsManager
, retrieved using the static methodgetDefault()
: - A
PendingIntent
is created in order for the application to track message delivery status. (APendingIntent
provides a means for an application to work beyond its life, for a particular Intent. Even after the owning application dies, aPendingIntent
created by it can be run later.) This pending intent is invoked when the sending handset receives an acknowledgement from the network that the destination handset has received the message. - To send a simple text message, the sample code would be like what’s shown below:
The complete working code for sending SMS can be found here.
One simple way to test complete SMS functionality, especially the acknowledgement, with a pending intent, is to create two Emulator instances. Let’s say that the instances are 5554 and 5556 (see Figure 3). This number is also the port number, and the emulator can be called at this number. This is a nice way to test without incurring network provider call charges during development and testing periods.
You can read more on SMS emulation here.
Summary
Sim Card Reader
With this background, interested developers may take a deep plunge into programming with the help of Android Telephony API website. Another related area to understand would be the standards that are part of 3GPP Evolution model.
Where can I find the application TelExplore?
Exists a possibility to print the results to a log file so I can use ADB to read it via USB connection?