Android - 读取和查询手机联系人

本文会用到安卓的内容提供器 ContentProvider

1. 读取联系人列表

1.1. 权限

1
<uses-permission android:name="android.permission.READ_CONTACTS"/>

安卓 7.0 以上还需要申请动态权限

1
2
3
if (ContextCompat.checkSelfPermission(getApplicationContext(), Manifest.permission.READ_CONTACTS) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.READ_CONTACTS}, REQUEST_CODE);
}

1.2. 示例代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
private void fetchAllContacts() {
if (ContextCompat.checkSelfPermission(getApplicationContext(), Manifest.permission.READ_CONTACTS) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.READ_CONTACTS}, REQUEST_CODE);
}
ContentResolver resolver = getContentResolver();
Uri uri = ContactsContract.CommonDataKinds.Phone.CONTENT_URI;
Cursor cursor = resolver.query(uri, null, null, null, null);
assert cursor != null;
while (cursor.moveToNext()) {
String cName = cursor.getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME));
String cNum = cursor.getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
Log.i("Contact", "姓名:" + cName);
Log.i("Contact", "号码:" + cNum);
Log.i("Contact", "======================");
}
cursor.close();
}

2. 查询指定联系人

2.1 权限

同上

2.2 示例代码

1
2
3
4
5
6
7
8
9
10
11
private void queryContact(String number){
Uri uri = Uri.parse("content://com.android.contacts/data/phones/filter/" + number);
ContentResolver resolver = getContentResolver();
Cursor cursor = resolver.query(uri, new String[]{"display_name"}, null, null, null);
assert cursor != null;
if (cursor.moveToFirst()) {
String name = cursor.getString(0);
Log.i("Contact", number + "对应的联系人名称:" + name);
}
cursor.close();
}

3. 添加新的联系人

3.1 权限

1
2
<uses-permission android:name="android.permission.WRITE_CONTACTS"/>
<uses-permission android:name="android.permission.WRITE_PROFILE"/>

安卓 7.0 以上还需要申请动态权限

1
2
3
4
if (ContextCompat.checkSelfPermission(getApplicationContext(), Manifest.permission.READ_CONTACTS) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.WRITE_CONTACTS}, REQUEST_CODE);
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.WRITE_PROFILE}, REQUEST_CODE);
}

3.2 示例代码

TODO

评论

Your browser is out-of-date!

Update your browser to view this website correctly. Update my browser now

×