1、添加权限
<uses-permission android:name="android.permission.READ_CONTACTS"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
2、安卓6.0以上版本获取权限
ActivityCompat.requestPermissions(TongxunluActivity.this, new String[]{Manifest.permission.READ_CONTACTS,Manifest.permission.READ_EXTERNAL_STORAGE}, 1);
3、创建工具方法
// 获得所有的联系人 Cursor cur = context.getContentResolver().query(ContactsContract.Contacts.CONTENT_URI,null,null,null,ContactsContract.Contacts.DISPLAY_NAME+ " COLLATE LOCALIZED ASC"); // 循环遍历 if (cur.moveToFirst()) {int idColumn = cur.getColumnIndex(ContactsContract.Contacts._ID);int displayNameColumn = cur.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME);do {jsonObject = new JSONObject();contactData.put("information" + num, jsonObject);num++;// 获得联系人的ID号String contactId = cur.getString(idColumn);// 获得联系人姓名String disPlayName = cur.getString(displayNameColumn);// 查看该联系人有多少个电话号码。如果没有这返回值为0int phoneCount = cur.getInt(cur.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER));jsonObject.put("name", disPlayName);
4、调用方法即可
@Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {switch (requestCode) {case 1:if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {//在这里执行读取通讯录方法try {ContactType mobiletype= new ContactType(this);String contactinfo=mobiletype.getInformation();LgqLogutil.e("通讯录==== "+contactinfo);textView.setText(contactinfo);} catch (JSONException e) {e.printStackTrace();}} else {Toast.makeText(this, "获取联系人权限失败", Toast.LENGTH_SHORT).show();}break;default:}
}
运行结果是:
demo链接:https://download.csdn.net/download/meixi_android/11959232
在线bug交流:QQ1085220040