How can I get my phone number in Android? When I use:
TelephonyManager tMgr =(TelephonyManager)this.getSystemService(Context.TELEPHONY_SERVICE);
String mPhoneNumber = tMgr.getLine1Number();
and use:
<uses-permission android:name="android.permission.READ_PHONE_STATE" />
it returns null, why?
From the documentation:
Returns the phone number string for line 1, for example, the MSISDN for a GSM phone. Return null if it is unavailable.
So you have done everything right, but there is no phone number stored.
If you get null
, you could display something to get the user to input the phone number on his/her own.
If the function you called returns null, it means your phone number is not registered in your contact list.
If instead of the phone number you just need an unique number, you may use the sim card's serial number:
TelephonyManager telemamanger = (TelephonyManager)getSystemService(Context.TELEPHONY_SERVICE); String getSimSerialNumber = telemamanger.getSimSerialNumber();
As Answered here
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:
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.
private String getMyPhoneNumber(){
TelephonyManager mTelephonyMgr;
mTelephonyMgr = (TelephonyManager)
getSystemService(Context.TELEPHONY_SERVICE);
return mTelephonyMgr.getLine1Number();
}
private String getMy10DigitPhoneNumber(){
String s = getMyPhoneNumber();
return s.substring(2);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With