1:申请权限
<uses-permission android:name="android.permission.READ_CONTACTS"/>
<uses-permission android:name="android.permission.WRITE_CONTACTS"/>
2:读取联系人
Cursor cursor = context.getContentResolver()
.query(ContactsContract.Contacts.CONTENT_URI,
null, null, null, null);
if (cursor == null) {
Log.e(TAG, "联系人cursor is null");
return;
}
while (cursor.moveToNext()) {
@SuppressLint("Range") int id = cursor.getInt(cursor.getColumnIndex(ContactsContract.Contacts._ID));
@SuppressLint("Range") String lastUpdatedTimeStamp = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts.CONTACT_LAST_UPDATED_TIMESTAMP));
@SuppressLint("Range") String name = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
Log.e(TAG, "id:" + id + " name:" + name);
}
3:删除联系人
private void delContact2(Context c, String mContactId) {
ArrayList ops = new ArrayList();
// 先删除子表Contacts中的数据
ops.add(ContentProviderOperation
.newDelete(ContactsContract.Contacts.CONTENT_URI)
.withSelection(
ContactsContract.Contacts._ID + "=?",
new String[]{String.valueOf(mContactId)})
.build());
// 然后删除子表Data中的数据
ops.add(ContentProviderOperation
.newDelete(ContactsContract.Data.CONTENT_URI)
.withSelection(
ContactsContract.Data.RAW_CONTACT_ID + "=?",
new String[]{String.valueOf(mContactId)})
.build());
// 最后删除父表RawContacts中的数据
ops.add(ContentProviderOperation
.newDelete(ContactsContract.RawContacts.CONTENT_URI)
.withSelection(
ContactsContract.RawContacts.CONTACT_ID
+ "=?",
new String[]{String.valueOf(mContactId)})
.build());
try {
getContentResolver().applyBatch(
ContactsContract.AUTHORITY, ops);
} catch (Exception e) {
e.printStackTrace();
}
}
标签:String,Contacts,ContactsContract,ops,改查,cursor,增删,Android,null
From: https://www.cnblogs.com/zhjing/p/17087042.html