Programmatically obtain the phone number of the Android phone Programmatically obtain the phone number of the Android phone android android

Programmatically obtain the phone number of the Android phone


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.


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:

<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.