Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

getLine1Number() Returns blank, not null [duplicate]

I want to get Mobile Number of Device. I have used following code reference by Alex Volovoy's This Link

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

Log.d("msg", "Phone : "+mPhoneNumber);

OUTPUT in Logcat:

Without Simcard Phones Returns:

02-01 17:22:45.472: D/msg(29102): Phone : null

With Simcard:

02-01 17:22:45.472: D/msg(29102): Phone : 

I have also taken permission in <uses-permission android:name="android.permission.READ_PHONE_STATE"/> in AndroidManifest.xml

So what should i do? Is there any Mistake?

like image 280
Pratik Butani Avatar asked Feb 01 '14 12:02

Pratik Butani


1 Answers

To get the phone number from the device , first you have to set your own phone number on the device, just through :

Settings -> About Phone -> Status -> My phone Number

Phone numbers are not available on SIM for each operators, like in india Sim dont have phone numbers in any memory, So WE cant get phone number from these connection. However, some countries, and operators have stored phone numbers on SIM, and we can get those. TO make this to work for all devices we can employ two strategies:

To avoid this problem , we can catch the error and work accordingly. Like:

TelephonyManager tMgr = (TelephonyManager) 
                 ShowMyLocation.this.getSystemService(Context.TELEPHONY_SERVICE);

String MyPhoneNumber = "0000000000";

try 
{
    MyPhoneNumber =tMgr.getLine1Number();
}
catch(NullPointerException ex)
{
}

if(MyPhoneNumber.equals("")){
    MyPhoneNumber = tMgr.getSubscriberId();
}
like image 159
Ankit Avatar answered Oct 25 '22 02:10

Ankit