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.
Get my phone number in android
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.
How to get the mobile number of my device programmatically?
Nowadays the TelephonyManager
does not help us. Play Services API without permission is good solution for this.
This dependency is useful for this
implementation 'com.google.android.gms:play-services-auth:16.0.1'
Now inside your Activity.java:
GoogleApiClient mGoogleApiClient = new GoogleApiClient.Builder(this)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(Auth.CREDENTIALS_API)
.build();
if (mGoogleApiClient != null) {
mGoogleApiClient.connect();
}
After this do request for Phone Number:
HintRequest hintRequest = new HintRequest.Builder()
.setPhoneNumberIdentifierSupported(true)
.build();
PendingIntent intent = Auth.CredentialsApi.getHintPickerIntent(mGoogleApiClient, hintRequest);
try {
startIntentSenderForResult(intent.getIntentSender(), 1008, null, 0, 0, 0, null);
} catch (IntentSender.SendIntentException e) {
Log.e("", "Could not start hint picker Intent", e);
}
Now you need to handle response in your onActivityResult
like this:
@Override
public void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
switch (requestCode) {
case 1008:
if (resultCode == RESULT_OK) {
Credential cred = data.getParcelableExtra(Credential.EXTRA_KEY);
// cred.getId====: ====+919*******
Log.e("cred.getId", cred.getId());
userMob = cred.getId();
} else {
// Sim Card not found!
Log.e("cred.getId", "1008 else");
return;
}
break;
}
}
How to get phone number or sim card information use android studio?
There is no reliable way to get the phone number from the SIM card. The TelephonyManager reads the phone number from SIM card but its upto the Telecom operators to add this information in the SIM card.
Most of the Telecom operators don't add this information in SIM card hence its not reliable enough.
There is a way to use Google-Play-Service to get the phone number, but it also doesn't gurantee 100% to return the phone number. You can do it as follows.
Add following dependencies in build.gradle
:
dependencies {
...
compile 'com.google.android.gms:play-services:11.6.0'
compile 'com.google.android.gms:play-services-auth:11.6.0'
}
Create two constants in MainActivity.java
:
private static final int PHONE_NUMBER_HINT = 100;
private final int PERMISSION_REQ_CODE = 200;
In onclick
of your Button add following:
final HintRequest hintRequest =
new HintRequest.Builder().setPhoneNumberIdentifierSupported(true).build();
try {
final GoogleApiClient googleApiClient =
new GoogleApiClient.Builder(MainActivity.this).addApi(Auth.CREDENTIALS_API).build();
final PendingIntent pendingIntent =
Auth.CredentialsApi.getHintPickerIntent(googleApiClient, hintRequest);
startIntentSenderForResult(
pendingIntent.getIntentSender(),
PHONE_NUMBER_HINT,
null,
0,
0,
0
);
} catch (Exception e) {
e.printStackTrace();
}
Add onActivityResult
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == PHONE_NUMBER_HINT && resultCode == RESULT_OK) {
Credential credential = data.getParcelableExtra(Credential.EXTRA_KEY);
final String phoneNumber = credential.getId();
}
}
How to get phone number from contact in android
Thanks for @Levon Petrosyan
But I just need to add the part from his link and copy it to my function.
This is the working code:
@Override
public void onActivityResult(int reqCode, int resultCode, Intent data){
super.onActivityResult(reqCode, resultCode, data);
if(reqCode == this.pickContact){
if (resultCode == Activity.RESULT_OK) {
Log.d("ContactsH", "ResOK");
Uri contactData = data.getData();
Cursor contact = getContentResolver().query(contactData, null, null, null, null);
if (contact.moveToFirst()) {
String name = contact.getString(contact.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
// TODO Whatever you want to do with the selected contact's name.
ContentResolver cr = getContentResolver();
Cursor cursor = cr.query(ContactsContract.Contacts.CONTENT_URI, null,
"DISPLAY_NAME = '" + name + "'", null, null);
if (cursor.moveToFirst()) {
String contactId =
cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts._ID));
//
// Get all phone numbers.
//
Cursor phones = cr.query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null,
ContactsContract.CommonDataKinds.Phone.CONTACT_ID + " = " + contactId, null, null);
while (phones.moveToNext()) {
String number = phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
int type = phones.getInt(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.TYPE));
switch (type) {
case ContactsContract.CommonDataKinds.Phone.TYPE_HOME:
// do something with the Home number here...
break;
case ContactsContract.CommonDataKinds.Phone.TYPE_MOBILE:
// do something with the Mobile number here...
Log.d("ContactsH", number);
this.callByNumber(number);
break;
case ContactsContract.CommonDataKinds.Phone.TYPE_WORK:
// do something with the Work number here...
break;
}
}
phones.close();
}
cursor.close();
}
}
}else{
Log.d("ContactsH", "Canceled");
}
}
Get phonenumber programmatically - Android
The method you are using is the only one part of the SDK to do this, and only works on devices where the number is stored on the SIM card, which only some carriers do. For all other carriers, you will have to ask the user to enter the phone number manually, as the number is simply not stored anywhere on the device from where you can retrieve it.
Get phone number of the current phone
getLine1Number() is not guaranteed to return a phone number. It only works if the SIM card in your device has the number stored on it.
You can check if it does by going to Settings -> About -> Status
and seeing if the phone number is available there. If it isn't, then your carrier doesn't keep the number on the SIM card
Related Topics
Using Android.Support.V7.Widget.Cardview in My Project (Eclipse)
What Is the Equivalent of Actionbar in Earlier Sdk Versions
Measuring a View Before Rendering It
Search Contact by Phone Number
Xiaomi Does Not Receive Notification When Application Is Not Running
Get Temperature of Battery on Android
Android Convert Date and Time to Milliseconds
Android Get Activity Returns Null
Can't Update Android Studio - Only Download
Doze Mode and Foreground Service
Clarify the Firebase Connections
Adt Blank Activity Created with Fragment Activity
Resources$Notfoundexception: File Res/Drawable/Abc_Ic_Ab_Back_Material.Xml
Display Data After Every 10 Seconds in Android
Exif Orientation Tag Value Always 0 for Image Taken with Portrait Camera App Android
Volley Out of Memory Error, Weird Allocation Attempt
Android - Gettargetfragment and Settargetfragment - What Are They Used For
Can't Apply System Screen Brightness Programmatically in Android