close
Contacts Provider是官方寫好的提供聯絡人的資訊
這篇就介紹基本的用法
1. 官網https://developer.android.com/guide/topics/providers/contacts-provider.html
2. 首先要有存取權限
<uses-permission android:name="android.permission.READ_PROFILE"/>
<uses-permission android:name="android.permission.READ_CONTACTS"/>
<uses-permission android:name="android.permission.WRITE_CONTACTS"/>
3. 接著用ContentResolver來取得cursor
4. 用where來讀取聯絡人的資料
while (cursor.moveToNext()){
int id = cursor.getInt(cursor.getColumnIndex(ContactsContract.Contacts._ID));
Log.d("TAG", "id = " + id);
Log.d("TAG", "Name = " + cursor.getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME)));
Log.d("TAG", "LOOKUP_KEY = " + cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts.LOOKUP_KEY)));
Cursor mailCursor = contentResolver.query(
ContactsContract.CommonDataKinds.Email.CONTENT_URI,
null,
null,
null,
null);
while(mailCursor.moveToNext()){
Log.d("TAG", "Email = " + mailCursor.getString(mailCursor.getColumnIndex(ContactsContract.CommonDataKinds.Email.DATA)));
}
mailCursor.close();
Cursor phoneCursor = contentResolver.query(
ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
null,
ContactsContract.CommonDataKinds.Phone.CONTACT_ID +" = ?",
new String[]{""+id},
null);
while(phoneCursor.moveToNext()){
Log.d("TAG", "Phone = " + phoneCursor.getString(phoneCursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER)));
}
phoneCursor.close();
}
cursor.close();
5. 用applyBatch來新增聯絡人
ArrayList<ContentProviderOperation> ops = new ArrayList<>();
int rawContactInsertIndex = ops.size();
ops.add(ContentProviderOperation.newInsert(ContactsContract.RawContacts.CONTENT_URI)
.withValue(ContactsContract.RawContacts.ACCOUNT_TYPE, null)
.withValue(ContactsContract.RawContacts.ACCOUNT_NAME, null)
.build());
ops.add(ContentProviderOperation.newInsert(ContactsContract.Data.CONTENT_URI)
.withValueBackReference(ContactsContract.Contacts.Data.RAW_CONTACT_ID, rawContactInsertIndex)
.withValue(ContactsContract.Contacts.Data.MIMETYPE,
ContactsContract.CommonDataKinds.StructuredName.CONTENT_ITEM_TYPE)
.withValue(ContactsContract.CommonDataKinds.StructuredName.DISPLAY_NAME, "測試人")
.build());
ops.add(ContentProviderOperation.newInsert(ContactsContract.Data.CONTENT_URI)
.withValueBackReference(ContactsContract.Data.RAW_CONTACT_ID, rawContactInsertIndex)
.withValue(ContactsContract.Data.MIMETYPE, ContactsContract.CommonDataKinds.Phone.CONTENT_ITEM_TYPE)
.withValue(ContactsContract.CommonDataKinds.Phone.NUMBER, "0912345678")
.build());
try {
getContentResolver().applyBatch(ContactsContract.AUTHORITY, ops);
} catch (RemoteException | OperationApplicationException e) {
e.printStackTrace();
}
6. 用delete來刪除聯絡人
ContentResolver contentResolver = getContentResolver();
Uri uri = Uri.withAppendedPath(ContactsContract.
Contacts.CONTENT_LOOKUP_URI, "0r252-543A5F612C2A");
contentResolver.delete(uri, null, null);
文章標籤
全站熱搜
留言列表