User and device info helper code
public class DevicePhoneNumber {
public final String phoneNumber;
public DevicePhoneNumber(String phoneNumber) {
this.phoneNumber = phoneNumber;
}
@Override
public String toString() {
return "DevicePhoneNumber{" +
"phoneNumber='" + phoneNumber + '\'' +
'}';
}
}
public class DeviceUserProfile {
public final String email;
public final String firstName;
public final String lastName;
public DeviceUserProfile(String email, String firstName, String lastName) {
this.email = email;
this.firstName = firstName;
this.lastName = lastName;
}
@Override
public String toString() {
return "DeviceUserProfile{" +
"email='" + email + '\'' +
", firstName='" + firstName + '\'' +
", lastName='" + lastName + '\'' +
'}';
}
}
/**
* Try to get the current phone number of the device.
*
* Requires:
* <uses-permission android:name="android.permission.READ_PHONE_STATE"/>
*/
public DevicePhoneNumber produceCurrentPhoneNumber() {
TelephonyManager phoneManager = (TelephonyManager) application.getSystemService(Context.TELEPHONY_SERVICE);
String phoneNumber = phoneManager.getLine1Number();
if (!TextUtils.isEmpty(phoneNumber)) {
return new DevicePhoneNumber(phoneNumber);
} else {
return null;
}
}
/**
* Get some basic details about the current user.
*
* Requires:
* <uses-permission android:name="android.permission.READ_PROFILE" />
*/
public DeviceUserProfile produceDeviceUserProfile() {
Cursor cursor = application.getContentResolver().query(
Uri.withAppendedPath(
ContactsContract.Profile.CONTENT_URI,
ContactsContract.Contacts.Data.CONTENT_DIRECTORY),
new String[] {
Email.ADDRESS,
Email.IS_PRIMARY,
Profile.DISPLAY_NAME
},
ContactsContract.Contacts.Data.MIMETYPE + " = ?",
new String[]{ContactsContract.CommonDataKinds.Email.CONTENT_ITEM_TYPE},
ContactsContract.Contacts.Data.IS_PRIMARY + " DESC"
);
try {
if (cursor.getCount() > 0) {
cursor.moveToFirst();
String email = cursor.getString(0);
String displayName = cursor.getString(2);
String firstName = null;
String lastName = null;
String[] parts = displayName.split(" ");
// Display name can come back in a bunch of different formats (including e-mail), and
// so that we don't make an assumption about likely first and last name values (ex:
// Mary Ann __ Shortname vs Ben __ von Longname, we'll play it conservative and only
// return it if we have a better degree of confidence in it.
if (parts.length == 2) {
firstName = parts[0];
lastName = parts[1];
}
return new DeviceUserProfile(email, firstName, lastName);
}
return null;
} finally {
cursor.close();
}
}