Android获取手机联系人(以及单个人对应多个手机号情况)
2019-03-11 本文已影响0人
Steven_SHH
获取手机联系人方法
private String[] getContacts() {
// 联系人的Uri,也就是content://com.android.contacts/contacts
Uri uri = ContactsContract.Contacts.CONTENT_URI;
// 指定获取_id和display_name两列数据,display_name即为姓名
String[] projection = new String[]{
ContactsContract.Contacts._ID,
ContactsContract.Contacts.DISPLAY_NAME
};
//根据Uri查询相应的ContentProvider,cursor为获取到的数据集
Cursor cursor = this.getContentResolver().query(uri, projection, null, null, null);
String[] arr = new String[cursor.getCount()];
int i = 0;
if (cursor.moveToFirst()) {
do {
Long id = cursor.getLong(0);
//获取姓名
String name = cursor.getString(1);
//指定获取NUMBER这一列数据
String[] phoneProjection = new String[]{
ContactsContract.CommonDataKinds.Phone.NUMBER
};
arr[i] = id + " , 姓名:" + name;
//根据联系人的ID获取此人的电话号码
Cursor phonesCursor = this.getContentResolver().query(
ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
phoneProjection,
ContactsContract.CommonDataKinds.Phone.CONTACT_ID + "=" + id,
null,
null);
//因为每个联系人可能有多个电话号码,所以需要遍历
if (phonesCursor != null && phonesCursor.moveToFirst()) {
do {
String num = phonesCursor.getString(0);
arr[i] += " , 电话号码:" + num;
} while (phonesCursor.moveToNext());
}
i++;
} while (cursor.moveToNext());
for (int j = 0; j < arr.length; j++) {
Log.e("Steven", arr[j]);
}
// 关闭游标
cursor.close();
}
return arr;
}
6.0以后需要手动获取权限
if (ContextCompat.checkSelfPermission(MainActivity.this,
android.Manifest.permission.READ_CONTACTS) != PackageManager.PERMISSION_GRANTED) {
// 申请权限 第二个参数是一个 数组 可以同时申请多个权限
ActivityCompat.requestPermissions(MainActivity.this,
new String[]{android.Manifest.permission.READ_CONTACTS}, 1);
} else {// 已授权
getContacts();
}