getLine1Number() Returns blank, not null [duplicate] - android

This question already has answers here:
MSISDN : Is it a SIM Card Data? Why all The Provided Function (from Blackberry and Android) to fetch MSISDN not reliable?
(3 answers)
Closed 5 years ago.
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?

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

I have another solution to get a phone number when telephony manager returns blank. I hope it'll help you.
Here is my sample code:
public static final String main_data[] = {
"data1", "is_primary", "data3", "data2", "data1", "is_primary", "photo_uri", "mimetype"
};
object object = (TelephonyManager) context.getSystemService("phone");
if (!TextUtils.isEmpty(((TelephonyManager) (object)).getLine1Number())) {
}
object = context.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;
}
if (s.equals("vnd.android.cursor.item/phone_v2")) {
String s1 = ((Cursor) (object)).getString(4);
boolean flag1;
if (((Cursor) (object)).getInt(5) > 0) {
flag1 = true;
} else {
flag1 = false;
}
Toast.makeText(SampleActivity.this, "Phone:-" + s1, Toast.LENGTH_LONG).show();
}
} while (true);
((Cursor) (object)).close();
}
Also don't forget to add these two permissions:
<uses-permission android:name="android.permission.READ_CONTACTS" />
<uses-permission android:name="android.permission.READ_PROFILE" />

Related

Programmatically Get phone number in Android

In my Android application, I need to display phone numbers of the Sim cards which are available in the device.
I tried with the below codes
private String getPhone() {
TelephonyManager phoneMgr = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
if (ActivityCompat.checkSelfPermission(activity, wantPermission) != PackageManager.PERMISSION_GRANTED) {
return "";
}
return phoneMgr.getLine1Number();
}
and
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
List<SubscriptionInfo> subscription = SubscriptionManager.from(getApplicationContext()).getActiveSubscriptionInfoList();
for (int i = 0; i < subscription.size(); i++) {
SubscriptionInfo info = subscription.get(i);
Log.d(TAG, "number " + info.getNumber());
Log.d(TAG, "network name : " + info.getCarrierName());
Log.d(TAG, "country iso " + info.getCountryIso());
}
}
But both are returning null or empty string only.
I have added the manifest permission also.
<uses-permission android:name="android.permission.READ_PHONE_STATE"/>
Could you please help me.
Thanks.
some phone companies not give this permission to get number from sim-card because i was same problem in past projects.
(in the past project i want to send OTP on simcard number user can't type his number. it was for security purpose.)
so some of phone gives you output correct and remains give you output as NULL

getAllCellInfo() returns empty list on Nexus 5x

I read all posts about getAllCellInfo() and have a similar situation like this.
The code posted below runs well on Android 6 (OnePlus One) but returns an empty list of Cellinfo on Google Nexus 5x Android 8.1 API 27.
I have set the Permission ACCESS CORSE LOCATION in the manifest and asking for permission when running the app first time.
Here is a code snippet:
try {
TelephonyManager tm = (TelephonyManager) mContext.getSystemService(Context.TELEPHONY_SERVICE);
String networkOperator = "";
if (tm.getPhoneType() == TelephonyManager.PHONE_TYPE_GSM) {
networkOperator = tm.getNetworkOperator();
}
if (!TextUtils.isEmpty(networkOperator)) { //is not empty with Nexus 5x
mcc = networkOperator.substring(0, 3);
mnc = networkOperator.substring(3);
} else {
mcc = "Unbekannt";
mnc = "Unbekannt";
}
List<CellInfo> cell = tm.getAllCellInfo();
System.out.println("List: "+cell);
if (cell != null) { //Always null with Nexus 5x
// TODO
} else {
cellID = "ERROR";
lac = "ERROR";
}
}
catch(Exception ex) {
mcc = "No Permission";
mnc = "No Permission";
cellID = "ERROR";
lac = "ERROR";
}
}
When trying other apps like "Network Cell Info lite" these apps get all the cellinformation :(
Any Help is very appreciated.
In Android 8.0 and above,to access getAllCellInfo() your app should be in the foreground.
If you want to access getAllCellInfo() you need to enable Location Service too.

Getting the Wrong Mobile Prefix in Android

I am making an app where I will get user's complete phone number from the sim - including the country and mobile prefixes. The phone number I have is 061555555, so when I save it to server it should look like this: +38761555555.
And here is my problem - when I use the code from below I get the following: +387218900032555555, ie. instead of 061 becoming 61, it becomes 218900032. This line number gives the wrong number:
MyPhoneNumber = tMgr.getLine1Number();
I have also tried this and this.
This is my code:
// Get users phone number
private String getMyPhoneNumber() {
TelephonyManager tMgr = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
// Get the SIM country ISO code
String simCountry = tMgr.getSimCountryIso().toUpperCase();
// Get the operator code of the active SIM (MCC + MNC)
String simOperatorCode = tMgr.getSimOperator();
// Get the name of the SIM operator
String simOperatorName = tMgr.getSimOperatorName();
// Get the SIM’s serial number
String simSerial = tMgr.getSimSerialNumber();
String MyPhoneNumber = "0000000000";
try {
MyPhoneNumber = tMgr.getLine1Number();
} catch (NullPointerException ex) {
}
if (MyPhoneNumber.equals("")) {
MyPhoneNumber = tMgr.getSubscriberId();
}
PhoneNumberUtil phoneUtil = PhoneNumberUtil.getInstance();
Phonenumber.PhoneNumber countryNumberProto = null;
try {
countryNumberProto = phoneUtil.parse(MyPhoneNumber, simCountry);
} catch (NumberParseException e) {
System.err.println("NumberParseException was thrown: " + e.toString());
}
String myPhone = phoneUtil.format(countryNumberProto, PhoneNumberUtil.PhoneNumberFormat.E164);
// I tried INTERNATIONAL and NATIONAL as well
return myPhone;
}
I think you are parsing "national_number" instead of "country_code". Check your JSON parsing code fields logic
{
"country_code": 41,
"national_number": 446681800
}
https://github.com/googlei18n/libphonenumber
I checked my settings->status and found out my phone number is unknown, and instead of my phone number it displays IMEI, so I guess I will have the user confirm his phone number by entering it manually.

Android imei number - how to pick it?

developed an app using a mobile phone
used this code to pick imei number
Utill.class
static TelephonyManager telephonyManager;
public static String getDeviceID(){
telephonyManager=(TelephonyManager) MyApplication.getInstance().getSystemService(MyApplication.getInstance().TELEPHONY_SERVICE);
return telephonyManager.getDeviceId();
}
in my job.class
String imeino = Util.getDeviceID();
tested with mobile devises and it works properly but when apk installed a tab (in client side ) imei number does not pick and give a null pointer
Note. for tab i have added different layouts and it also works properly in my tab
is this a matter of base url or
how can i avoid this issue of imei number ?
java Class and add following code
TelephonyManager tel;
TextView imei;
tel = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
imei = (TextView) findViewById(R.id.textView2);
imei.setText(tel.getDeviceId().toString());
AndroidManifest.xml and add following code
<uses-permission android:name="android.permission.READ_PHONE_STATE"/>
Have this common method. Devices without SIM slot will return null IMEI. So pick ANDROID_ID.
public String getDeviceID(){
String devcieId;
TelephonyManager mTelephony = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
if (mTelephony.getDeviceId() != null){
devcieId = mTelephony.getDeviceId();
}else{
devcieId = Secure.getString(getApplicationContext().getContentResolver(), Secure.ANDROID_ID);
}
return devcieId;
}
Try this code it will return you IMEI number if device GSM based or if not get back the Android ID.
String devcieId;
TelephonyManager mTelephony = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
if (mTelephony.getDeviceId() != null){
devcieId = mTelephony.getDeviceId();
}else{
devcieId = Secure.getString(getApplicationContext().getContentResolver(), Secure.ANDROID_ID);
}
Also give the read phone state permission in your manifest.
<uses-permission android:name="android.permission.READ_PHONE_STATE"/>

Android app to get system phone number

I'm Trying the following code to get System phone number
TelephonyManager tMgr =(TelephonyManager)mAppContext.getSystemService(Context.TELEPHONY_SERVICE);
mPhoneNumber = tMgr.getLine1Number();
But it is not working.
In my phone, i use
Settings->About Phone-->Status-Phone Number
is there a simple app i can use ? , I m writing from Turkey. does sim card make a difference ?
Not all telecom carriers store the phone number on the SIM card. The approach you are using only works if the SIM card in the device has the mobile number stored on it.
If you cannot see your phone number in the mobile settings, then it means that it isn't stored on the SIM card. You will have to manually ask the user to enter it into your app if you absolutely need it. There is no other way.
You can try something like this. It works perfectly.
public String getPhoneNumber(Context context) {
TelephonyManager mTelephonyMgr;
mTelephonyMgr = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
String num = mTelephonyMgr.getLine1Number();
return fillPhoneNumber(num);
}
private String fillPhoneNumber(String num) {
try{
if (num != null && num.length() > 0) {
if (num.length() >= 9) {
num = num.replaceAll("\\D", "");
if (num.substring(0, 1).equals("8")) {
num = "+3" + num;
} else if (num.substring(0, 1).equals("0")) {
num = "+38" + num;
} else if (num.substring(0, 1).equals("3")) {
num = "+" + num;
}
}
return num;
}
}catch (Exception e) {
e.printStackTrace();
}
return null;
}
Note: Not all phones return a phone number.
There is no deterministic way to find the MSISDN. The above approach only works if SIM has stored the MSISDN. Other work around is to retrieve the number from facebook. It also may or may not work.
The only sure shot way is to create account with some SMS gateway provider like http://trumpia.com, then send SMS to the toll free number, and then call the API to retrieve the MSISDN.

Categories

Resources