How To get Mobile Number in android studio? I try to get my mobile number using this code but return value is blank.
TelephonyManager tpm = (TelephonyManager)getSystemService(TELEPHONY_SERVICE);
String number = tpm.getLine1Number();
How To get Mobile Number in android studio? I try to get my mobile number using this code but return value is blank.
TelephonyManager tpm = (TelephonyManager)getSystemService(TELEPHONY_SERVICE);
String number = tpm.getLine1Number();
This is the relevant documantation for https://developer.android.com/reference/android/telephony/TelephonyManager.html
getLine1Number
String getLine1Number () Returns the phone number string for line 1, for example, the MSISDN for a GSM phone. Return null if it is unavailable.
The default SMS app can also use this.
Requires the READ_PHONE_STATE, READ_SMS or READ_PHONE_NUMBERS permissions.
Also if you are using Android 6.0 or above add the following code. This code checks whether the app has permission to read the user's contacts or not also it requests the permission from the user if necessary. Try this
// Here, thisActivity is the current activity
if (ContextCompat.checkSelfPermission(thisActivity,
Manifest.permission.READ_CONTACTS)
!= PackageManager.PERMISSION_GRANTED) {
// Should we show an explanation?
if (ActivityCompat.shouldShowRequestPermissionRationale(thisActivity,
Manifest.permission.READ_CONTACTS)) {
// Show an expanation to the user *asynchronously* -- don't block
// this thread waiting for the user's response! After the user
// sees the explanation, try again to request the permission.
} else {
ActivityCompat.requestPermissions(thisActivity,
new String[]{Manifest.permission.READ_CONTACTS},
MY_PERMISSIONS_REQUEST_READ_CONTACTS);
}
}