android获取手机通讯录联系人

android获取手机通讯录联系人

0x01前言

首先需要在AndroidManifest配置文件中添加获取通讯录读写权限

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

0x02请求读取联系人

在需要请求的事件下添加读取联系人请求

1
2
3
// 请求手机通讯录
Intent intent = new Intent(Intent.ACTION_PICK, ContactsContract.Contacts.CONTENT_URI);
startActivityForResult(intent, ACTION_SELECT_CONTACTS);

全局参数

1
2
public static final int ACTION_SELECT_CONTACTS = 111;
private List<String> contactsPhone = new ArrayList<String>();

0x03处理回调结果

点击系统通讯录后系统会回调回选择的联系人信息,需要根据其在获取点击的联系人名下的手机号码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
String username = "";
contactsPhone.clear();
if (resultCode == Activity.RESULT_OK) {
switch (requestCode){
case ACTION_SELECT_CONTACTS:
Cursor cursor = getContentResolver().query(data.getData(),
null, null, null, null);
if (cursor.moveToFirst()) { // True if the cursor is not empty
int columnIndex = cursor.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME);
username = cursor.getString(columnIndex);//获取联系人的姓名
//获取联系人对应的ID
String contactId = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts._ID));
//根据ID获取对应的联系人的所有手机号码
Cursor phone = getContentResolver().query(
ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null,
ContactsContract.CommonDataKinds.Phone.CONTACT_ID+ " = "
+ contactId, null, null);
while (phone.moveToNext()) {
String userPhone = phone.getString(phone
.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
if(!userPhone.isEmpty()){
contactsPhone.add(userPhone);
}
}
if(phone != null){
phone.close();
}
}
if(cursor != null){
cursor.close();
}
if(contactsPhone.size() >= 1){
showSelectDil(username);
}else{
Toast.makeText(MainActivity.this, "当前联系人没有可显示的手机号码", Toast.LENGTH_SHORT).show();
}
break;
default:
break;
}
}
}

通过弹框显示所有的手机号码信息,供用户自行选择

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
private void showSelectDil(String username) {
AlertDialog.Builder params = new AlertDialog.Builder(MainActivity.this);
params.setTitle(username);
final String[] items = new String[contactsPhone.size()];
for (int i = 0; i < contactsPhone.size(); i++){
items[i] = contactsPhone.get(i);
}
params.setItems(items, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
Toast.makeText(MainActivity.this, items[i], Toast.LENGTH_SHORT).show();
}
});
params.create().show();
}

实际的效果图为:
enter image description here