下面列出了android.provider.Contacts.Intents#android.provider.ContactsContract.CommonDataKinds.Phone 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
private ContactData getContactData(Context context, String displayName, long id) {
ContactData contactData = new ContactData(id, displayName);
Cursor numberCursor = null;
try {
numberCursor = context.getContentResolver().query(Phone.CONTENT_URI, null,
Phone.CONTACT_ID + " = ?",
new String[] {contactData.id + ""}, null);
while (numberCursor != null && numberCursor.moveToNext()) {
int type = numberCursor.getInt(numberCursor.getColumnIndexOrThrow(Phone.TYPE));
String label = numberCursor.getString(numberCursor.getColumnIndexOrThrow(Phone.LABEL));
String number = numberCursor.getString(numberCursor.getColumnIndexOrThrow(Phone.NUMBER));
String typeLabel = Phone.getTypeLabel(context.getResources(), type, label).toString();
contactData.numbers.add(new NumberData(typeLabel, number));
}
} finally {
if (numberCursor != null)
numberCursor.close();
}
return contactData;
}
private static void updateNormalizedNumber(Context context, ContentResolver resolver,
String dataId, String number) {
if (TextUtils.isEmpty(number) || TextUtils.isEmpty(dataId)) {
return;
}
final String countryIso = getCurrentCountryIso(context);
if (TextUtils.isEmpty(countryIso)) {
return;
}
final String normalizedNumber = PhoneNumberUtils.formatNumberToE164(number,
getCurrentCountryIso(context));
if (TextUtils.isEmpty(normalizedNumber)) {
return;
}
final ContentValues values = new ContentValues();
values.put(Phone.NORMALIZED_NUMBER, normalizedNumber);
resolver.update(Data.CONTENT_URI, values, Data._ID + "=?", new String[] {dataId});
}
/**
* Builds contact uri by given name and phone number
*
* @param phoneNumber
* @param contactName
* @return Builder.build()
*/
private static Uri buildUri(String phoneNumber, String contactName) {
Uri.Builder builder;
if (phoneNumber != null && !phoneNumber.isEmpty()) {
builder = Uri.withAppendedPath(Phone.CONTENT_FILTER_URI, Uri.encode(phoneNumber)).buildUpon();
builder.appendQueryParameter(ContactsContract.STREQUENT_PHONE_ONLY, "true");
} else if (contactName != null && !contactName.isEmpty()) {
builder = Uri.withAppendedPath(Phone.CONTENT_FILTER_URI, Uri.encode(contactName)).buildUpon();
builder.appendQueryParameter(ContactsContract.PRIMARY_ACCOUNT_NAME, "true");
} else {
builder = Phone.CONTENT_URI.buildUpon();
}
builder.appendQueryParameter(Contacts.EXTRA_ADDRESS_BOOK_INDEX, "true");
builder.appendQueryParameter(ContactsContract.REMOVE_DUPLICATE_ENTRIES, "true");
return builder.build();
}
/**
* Open contact edit page in default contacts app by contact's id
*
* @param activity
* @param number
*/
public static void openContactToEditByNumber(Activity activity, String number) {
try {
long contactId = ContactUtils.getContactByPhoneNumber(activity, number).getContactId();
Uri uri = ContentUris.withAppendedId(ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
contactId);
Intent intent = new Intent(Intent.ACTION_EDIT);
intent.setDataAndType(uri, ContactsContract.Contacts.CONTENT_ITEM_TYPE);
intent.putExtra("finishActivityOnSaveCompleted", true);
//add the below line
intent.addFlags(FLAG_ACTIVITY_CLEAR_TOP);
activity.startActivityForResult(intent, 1);
} catch (Exception e) {
Toast.makeText(activity, "Oops there was a problem trying to open the contact :(", Toast.LENGTH_SHORT).show();
}
}
/**
* 得到手机通讯录联系人信息
*/
private void getPhoneContacts() {
ContentResolver resolver = mContext.getContentResolver();
//query查询,得到结果的游标
Cursor phoneCursor = resolver.query(Phone.CONTENT_URI, PHONES_PROJECTION, null, null, null);
if (phoneCursor != null) {
while (phoneCursor.moveToNext()) {
//得到手机号码
String phoneNumber = phoneCursor.getString(PHONES_NUMBER_INDEX);
//当手机号码为空的或者为空字段 跳过当前循环
if (TextUtils.isEmpty(phoneNumber)) {
continue;
}
//得到联系人名称
String contactName = phoneCursor.getString(PHONES_DISPLAY_NAME_INDEX);
ContactModel cb = new ContactModel();
cb.setContactName(contactName);
cb.setPhoneNumber(phoneNumber);
contactsList.add(cb);
}
phoneCursor.close();
}
}
/**
* 得到手机通讯录联系人信息
*/
private void getPhoneContacts() {
//query查询,得到结果的游标
Cursor phoneCursor = mResolver.query(Phone.CONTENT_URI, PHONES_PROJECTION, null, null, null);
if (phoneCursor != null) {
while (phoneCursor.moveToNext()) {
//得到手机号码
String phoneNumber = phoneCursor.getString(PHONES_NUMBER_INDEX);
//当手机号码为空的或者为空字段 跳过当前循环
if (TextUtils.isEmpty(phoneNumber)) {
continue;
}
//得到联系人名称
String contactName = phoneCursor.getString(PHONES_DISPLAY_NAME_INDEX);
ContactModel cb = new ContactModel();
cb.setContactName(contactName);
cb.setPhoneNumber(phoneNumber);
contactsList.add(cb);
}
phoneCursor.close();
}
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (RESULT_OK == resultCode) {
String selection = Phone.CONTACT_ID + "=?";
Uri result = data.getData();
String id = result.getLastPathSegment();
String[] arguments = new String[]{id};
ContentResolver resolver = getContentResolver();
Cursor cursor = resolver.query(Phone.CONTENT_URI, null, selection, arguments, null);
int index = cursor.getColumnIndex(Phone.DATA);
if (cursor.moveToFirst()) {
String phone = cursor.getString(index);
set(this, phone);
EditText edit = (EditText) findViewById(R.id.contact);
edit.setText(phone);
}
cursor.close();
}
}
private ContactData getContactData(Context context, String displayName, long id) {
ContactData contactData = new ContactData(id, displayName);
Cursor numberCursor = null;
try {
numberCursor = context.getContentResolver().query(Phone.CONTENT_URI, null,
Phone.CONTACT_ID + " = ?",
new String[] {contactData.id + ""}, null);
while (numberCursor != null && numberCursor.moveToNext()) {
int type = numberCursor.getInt(numberCursor.getColumnIndexOrThrow(Phone.TYPE));
String label = numberCursor.getString(numberCursor.getColumnIndexOrThrow(Phone.LABEL));
String number = numberCursor.getString(numberCursor.getColumnIndexOrThrow(Phone.NUMBER));
String typeLabel = Phone.getTypeLabel(context.getResources(), type, label).toString();
contactData.numbers.add(new NumberData(typeLabel, number));
}
} finally {
if (numberCursor != null)
numberCursor.close();
}
return contactData;
}
public List<String> getNumbersForThreadSearchFilter(Context context, String constraint) {
LinkedList<String> numberList = new LinkedList<>();
Cursor cursor = null;
try {
cursor = context.getContentResolver().query(Uri.withAppendedPath(Phone.CONTENT_FILTER_URI,
Uri.encode(constraint)),
null, null, null, null);
while (cursor != null && cursor.moveToNext()) {
numberList.add(cursor.getString(cursor.getColumnIndexOrThrow(Phone.NUMBER)));
}
} finally {
if (cursor != null)
cursor.close();
}
return numberList;
}
/**
* 得到手机通讯录联系人信息
*/
private void getPhoneContacts() {
ContentResolver resolver = mContext.getContentResolver();
//query查询,得到结果的游标
Cursor phoneCursor = resolver.query(Phone.CONTENT_URI, PHONES_PROJECTION, null, null, null);
if (phoneCursor != null) {
while (phoneCursor.moveToNext()) {
//得到手机号码
String phoneNumber = phoneCursor.getString(PHONES_NUMBER_INDEX);
//当手机号码为空的或者为空字段 跳过当前循环
if (TextUtils.isEmpty(phoneNumber)) {
continue;
}
//得到联系人名称
String contactName = phoneCursor.getString(PHONES_DISPLAY_NAME_INDEX);
ContactModel cb = new ContactModel();
cb.setContactName(contactName);
cb.setPhoneNumber(phoneNumber);
contactsList.add(cb);
}
phoneCursor.close();
}
}
private static HashMap<String, Long> loadPhoneContacts(Context c){
mContentResolver = c.getContentResolver();
HashMap<String, Long> contacts = new HashMap<String, Long>();
Cursor cursor = mContentResolver.query(
Phone.CONTENT_URI,
new String[]{Phone.DISPLAY_NAME, Phone.RAW_CONTACT_ID},
null,
null,
null);
while (cursor.moveToNext()) {
contacts.put(cursor.getString(cursor.getColumnIndex(Phone.DISPLAY_NAME)), cursor.getLong(cursor.getColumnIndex(Phone.RAW_CONTACT_ID)));
//names.add(cursor.getString(cursor.getColumnIndex(Phone.DISPLAY_NAME)));
}
cursor.close();
return contacts;
}
@Override
protected Cursor getChildrenCursor(Cursor groupCursor) {
// Given the group, we return a cursor for all the children within that group
// Return a cursor that points to this contact's phone numbers
Uri.Builder builder = Contacts.CONTENT_URI.buildUpon();
ContentUris.appendId(builder, groupCursor.getLong(GROUP_ID_COLUMN_INDEX));
builder.appendEncodedPath(Contacts.Data.CONTENT_DIRECTORY);
Uri phoneNumbersUri = builder.build();
mQueryHandler.startQuery(TOKEN_CHILD, groupCursor.getPosition(), phoneNumbersUri,
PHONE_NUMBER_PROJECTION, Phone.MIMETYPE + "=?",
new String[] { Phone.CONTENT_ITEM_TYPE }, null);
return null;
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Set up our adapter
mAdapter = new MyExpandableListAdapter(
this,
android.R.layout.simple_expandable_list_item_1,
android.R.layout.simple_expandable_list_item_1,
new String[] { Contacts.DISPLAY_NAME }, // Name for group layouts
new int[] { android.R.id.text1 },
new String[] { Phone.NUMBER }, // Number for child layouts
new int[] { android.R.id.text1 });
setListAdapter(mAdapter);
mQueryHandler = new QueryHandler(this, mAdapter);
// Query for people
mQueryHandler.startQuery(TOKEN_GROUP, null, Contacts.CONTENT_URI, CONTACTS_PROJECTION,
Contacts.HAS_PHONE_NUMBER + "=1", null, null);
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.list_7);
mPhone = (TextView) findViewById(R.id.phone);
getListView().setOnItemSelectedListener(this);
// Get a cursor with all numbers.
// This query will only return contacts with phone numbers
Cursor c = getContentResolver().query(Phone.CONTENT_URI,
PHONE_PROJECTION, Phone.NUMBER + " NOT NULL", null, null);
startManagingCursor(c);
ListAdapter adapter = new SimpleCursorAdapter(this,
// Use a template that displays a text view
android.R.layout.simple_list_item_1,
// Give the cursor to the list adapter
c,
// Map the DISPLAY_NAME column to...
new String[] {Phone.DISPLAY_NAME},
// The "text1" view defined in the XML template
new int[] {android.R.id.text1});
setListAdapter(adapter);
}
public void onItemSelected(AdapterView<?> parent, View v, int position, long id) {
if (position >= 0) {
//Get current cursor
Cursor c = (Cursor) parent.getItemAtPosition(position);
int type = c.getInt(COLUMN_PHONE_TYPE);
String phone = c.getString(COLUMN_PHONE_NUMBER);
String label = null;
//Custom type? Then get the custom label
if (type == Phone.TYPE_CUSTOM) {
label = c.getString(COLUMN_PHONE_LABEL);
}
//Get the readable string
String numberType = (String) Phone.getTypeLabel(getResources(), type, label);
String text = numberType + ": " + phone;
mPhone.setText(text);
}
}
public Set<String> getAllContactsWithNumbers(Context context) {
Set<String> results = new HashSet<>();
try (Cursor cursor = context.getContentResolver().query(Phone.CONTENT_URI, new String[] {Phone.NUMBER}, null ,null, null)) {
while (cursor != null && cursor.moveToNext()) {
if (!TextUtils.isEmpty(cursor.getString(0))) {
results.add(PhoneNumberFormatter.get(context).format(cursor.getString(0)));
}
}
}
return results;
}
@Ignore
public Contact(Cursor cursor) {
this.contactId = cursor.getLong(cursor.getColumnIndex(Phone.CONTACT_ID));
Timber.i("CONTACT_ID: " + this.contactId);
this.name = cursor.getString(cursor.getColumnIndex(Phone.DISPLAY_NAME_PRIMARY));
this.photoUri = cursor.getString(cursor.getColumnIndex(Phone.PHOTO_THUMBNAIL_URI));
this.phoneNumbers = new ArrayList<>();
this.phoneNumbers.add(cursor.getString(cursor.getColumnIndex(Phone.NUMBER)));
this.isFavorite = "1".equals(cursor.getString(cursor.getColumnIndex(Phone.STARRED)));
}
/**
* Get a filter string
*
* @param context
* @return String
*/
private static String getWhere(Context context) {
return "(" + Phone.DISPLAY_NAME_PRIMARY + " IS NOT NULL" +
" OR " + Phone.DISPLAY_NAME_ALTERNATIVE + " IS NOT NULL" + ")" +
" AND " + Phone.HAS_PHONE_NUMBER + "=1" +
" AND (" + ContactsContract.RawContacts.ACCOUNT_NAME + " IS NULL" +
" OR ( " + ContactsContract.RawContacts.ACCOUNT_TYPE + " NOT LIKE '%whatsapp%'" +
" AND " + ContactsContract.RawContacts.ACCOUNT_TYPE + " NOT LIKE '%tachyon%'" + "))";
}
private Cursor loadFavoritesContacts() {
if (ContextCompat.checkSelfPermission(getContext(), android.Manifest.permission.READ_CONTACTS) == PackageManager.PERMISSION_GRANTED) {
String selection = Phone.STARRED + " = 1";
return getContext().getContentResolver().query(
buildFavoritesUri(), getProjection(), selection, null,
getSortOrder());
} else {
Toast.makeText(getContext(), "To get favorite contacts please allow contacts permission", Toast.LENGTH_LONG).show();
return null;
}
}
/**
* Builds contact uri by given name and phone number
*
* @return Builder.build()
*/
private static Uri buildFavoritesUri() {
Uri.Builder builder = Phone.CONTENT_URI.buildUpon();
builder.appendQueryParameter(ContactsContract.Contacts.EXTRA_ADDRESS_BOOK_INDEX, "true");
builder.appendQueryParameter(ContactsContract.REMOVE_DUPLICATE_ENTRIES, "true");
return builder.build();
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
View view;
if (convertView == null) {
view = LayoutInflater.from(contextRef.get()).inflate(R.layout.speed_dial_entry, null);
} else {
view = convertView;
}
String order = (new Integer(position+1)).toString();
((TextView)view.findViewById(R.id.entry_order)).setText(order);
String number = SpeedDial.getNumber(contextRef.get(), order);
String result;
if (position == 0) {
result = contextRef.get().getResources().getString(R.string.voice_mail);
((TextView)view.findViewById(R.id.entry_title)).setText(result);
return view;
}
String contactName = null;
Cursor cursor = contextRef.get().getContentResolver().query(Phone.CONTENT_URI, new String[]{Phone.DISPLAY_NAME}, Phone.NUMBER + "=?", new String[]{number}, null);
if (cursor != null) {
if (cursor.getCount() > 0) {
cursor.moveToFirst();
contactName = cursor.getString(0);
cursor.close();
}
}
if (null == contactName) {
result = !number.equals("") ? number : contextRef.get().getResources().getString(R.string.tap_for_addition);
} else {
result = contactName+" ("+number+")";
}
((TextView)view.findViewById(R.id.entry_title)).setText(result);
return view;
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
DialerApp.setTheme(this);
Intent intent = getIntent();
speedDialSlot = intent.getStringExtra(SpeedDialActivity.SPEED_DIAL_SLOT);
Cursor contactsCursor = getContentResolver().query(Phone.CONTENT_URI, PROJECTION, Phone.HAS_PHONE_NUMBER+"=1", null, Phone.DISPLAY_NAME);
pickContactNumberAdapter = new PickContactNumberAdapter(this, contactsCursor, 0);
setListAdapter(pickContactNumberAdapter);
}
@Override
public Loader<Cursor> onCreateLoader(int id, Bundle args) {
if (id == 0) {
return new CursorLoader(this, Calls.CONTENT_URI, LogEntryAdapter.PROJECTION, null, null, Calls.DEFAULT_SORT_ORDER);
} else {
return new CursorLoader(this, Phone.CONTENT_URI, ContactsEntryAdapter.PROJECTION, Phone.HAS_PHONE_NUMBER+"=1", null, Phone.DISPLAY_NAME);
}
}
@Override
public void onClick(View view) {
if (view.getId() == R.id.contact_entry_image) {
Intent intent = new Intent(Intent.ACTION_VIEW);
Uri uri = Uri.withAppendedPath(Phone.CONTENT_URI, ((ContactImageTag)view.getTag()).contactId);
intent.setDataAndType(uri, "vnd.android.cursor.dir/contact");
try {
activityRef.get().startActivity(intent);
} catch (ActivityNotFoundException e) {
activityRef.get().showMissingContactsAppDialog();
}
}
}
/**
* 全量获取手机联系人信息
* @return
*/
private static List<PhoneInfo> getMobileContactInner() {
List list = new ArrayList<PhoneInfo>();
Cursor cursor = null;
ContentResolver contentResolver = MyApplication.getApplication().getContentResolver();
if(sMobileContactObserver == null){
Log.d("hyh", "ContactUtil: getMobileContactInner: 注册MobileContactObserver");
sMobileContactObserver = new MobileContactObserver(null);
contentResolver.registerContentObserver(Phone.CONTENT_URI,false,sMobileContactObserver);
}
try {
cursor = contentResolver.query(Phone.CONTENT_URI,
null, null, null, null);
while (cursor.moveToNext()) {
//读取通讯录的姓名
String name = cursor.getString(cursor
.getColumnIndex(Phone.DISPLAY_NAME));
//读取通讯录的号码
String number = cursor.getString(cursor
.getColumnIndex(Phone.NUMBER));
//联系人id,不过同一个联系人有可能存多个号码,所以会存在不同号码对应相同id的情况
String contactId = cursor.getString(cursor
.getColumnIndex(Phone.CONTACT_ID));
String version = cursor.getString(cursor.getColumnIndex(ContactsContract.RawContacts.VERSION));
PhoneInfo phoneInfo = new PhoneInfo(contactId,version,name,number);
list.add(phoneInfo);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
if (cursor != null) {
cursor.close();
}
}
return list;
}
private void addPhoneEntry(WritableArray phones, Cursor cursor, Activity activity) {
String phoneNumber = cursor.getString(cursor.getColumnIndex(Phone.NUMBER));
int phoneType = cursor.getInt(cursor.getColumnIndex(Phone.TYPE));
String phoneLabel = cursor.getString(cursor.getColumnIndex(Phone.LABEL));
CharSequence typeLabel = Phone.getTypeLabel(activity.getResources(), phoneType, phoneLabel);
WritableMap phoneEntry = Arguments.createMap();
phoneEntry.putString("number", phoneNumber);
phoneEntry.putString("type", String.valueOf(typeLabel));
phones.pushMap(phoneEntry);
}
@Nullable
private ContactNumberCursorWrapper getContactNumbers(long contactId) {
Cursor cursor = contentResolver.query(
Phone.CONTENT_URI,
new String[]{Phone.NUMBER},
Phone.NUMBER + " IS NOT NULL AND " +
Phone.CONTACT_ID + " = " + contactId,
null,
null);
return (validate(cursor) ? new ContactNumberCursorWrapper(cursor) : null);
}
/**
* 往手机通讯录插入联系人
*
* @param ct
* @param name
* @param tel
* @param email
*/
public static void insertContact(Context ct, String name, String tel, String email) {
ContentValues values = new ContentValues();
// 首先向RawContacts.CONTENT_URI执行一个空值插入,目的是获取系统返回的rawContactId
Uri rawContactUri = ct.getContentResolver().insert(RawContacts.CONTENT_URI, values);
long rawContactId = ContentUris.parseId(rawContactUri);
// 往data表入姓名数据
if (!TextUtils.isEmpty(tel)) {
values.clear();
values.put(Data.RAW_CONTACT_ID, rawContactId);
values.put(Data.MIMETYPE, StructuredName.CONTENT_ITEM_TYPE);// 内容类型
values.put(StructuredName.GIVEN_NAME, name);
ct.getContentResolver().insert(android.provider.ContactsContract.Data.CONTENT_URI, values);
}
// 往data表入电话数据
if (!TextUtils.isEmpty(tel)) {
values.clear();
values.put(Data.RAW_CONTACT_ID, rawContactId);
values.put(Data.MIMETYPE, Phone.CONTENT_ITEM_TYPE);// 内容类型
values.put(Phone.NUMBER, tel);
values.put(Phone.TYPE, Phone.TYPE_MOBILE);
ct.getContentResolver().insert(android.provider.ContactsContract.Data.CONTENT_URI, values);
}
// 往data表入Email数据
if (!TextUtils.isEmpty(email)) {
values.clear();
values.put(Data.RAW_CONTACT_ID, rawContactId);
values.put(Data.MIMETYPE, Email.CONTENT_ITEM_TYPE);// 内容类型
values.put(Email.DATA, email);
values.put(Email.TYPE, Email.TYPE_WORK);
ct.getContentResolver().insert(android.provider.ContactsContract.Data.CONTENT_URI, values);
}
}
/**
* Get the NAME_PROJECTION for PhoneNumberPicker.
*/
public static String[] getNameProjection() {
String[] nameProjection = {
Data.CONTACT_ID,
ContactsContract.Contacts.DISPLAY_NAME,
ContactsContract.Contacts.PHOTO_THUMBNAIL_URI,
Phone.NUMBER,
};
return nameProjection;
}
/**
* Get the DATA_PROJECTION for ContactPicker and PhoneNumberPicker.
*/
public static String[] getDataProjection() {
String[] dataProjection = {
Data.MIMETYPE,
Email.ADDRESS,
Email.TYPE,
Phone.NUMBER,
Phone.TYPE,
};
return dataProjection;
}