Reputation: 2369
I need a way to capture an Android device's phone number in order to send it back to my web api for processing.
I've read about the issues and inconsistencies with the getLine1Number function so my question is this, are there any programmatic alternatives to getLine1Number
or is it the only available method to retrieve the device phone number?
To be clear, I am not looking for a UUID, this is a mobile phone application and I require the users phone number for data association.
Upvotes: -1
Views: 1502
Reputation: 467
You can use getLine1Number () for this. It will returns the phone number string for line 1, for example, the MSISDN for a GSM phone. Return null if it is unavailable.
here is an example:
TelephonyManager tm = (TelephonyManager)getSystemService(TELEPHONY_SERVICE);
String number = tm.getLine1Number();
It requires the READ_PHONE_STATE permission to be added on the Androidmanifest.xml file.
Upvotes: 1
Reputation: 77904
This is a snippets of code to get phone numbers:
....
private final static String PHONE = "phone";
...
Map<String, String> contactDataMap = new HashMap<String, String>();
ContentResolver cr = context.getContentResolver();
Uri contactData = data.getData();
//Cursor cursor = managedQuery(contactData, null, null, null, null);
Cursor cursor = cr.query(contactData, null, null, null, null);
cursor.moveToFirst();
String name = cursor.getString(cursor.getColumnIndexOrThrow(ContactsContract.Contacts.DISPLAY_NAME));
String id = cursor.getString(cursor.getColumnIndexOrThrow(ContactsContract.Contacts._ID));
contactDataMap.put(NAME, (name != null)?name:"");
if (Integer.parseInt(cursor.getString(
cursor.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER))) > 0) {
Cursor pCur = cr.query(
ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
null,
ContactsContract.CommonDataKinds.Phone.CONTACT_ID +" = ?",
new String[]{id},
null);
while (pCur.moveToNext()) {
String number = pCur.getString(pCur.getColumnIndexOrThrow(ContactsContract.CommonDataKinds.Phone.NUMBER));
contactDataMap.put(PHONE, (number != null)?number:"");
break; // ? we want only 1 value
}
pCur.close();
}
By this way you can fetch phone numbers. be sure that you have permissions:
<uses-permission android:name="android.permission.READ_CONTACTS" />
Upvotes: 1