Android 获取系统联系人信息的实例
一、获取手机联系人姓名及手机号
//跳转到系统联系人应用 Intent intent = new Intent(Intent.ACTION_PICK, ContactsContract.Contacts.CONTENT_URI); try { startActivityForResult(intent, Contacts1RequestCode); } catch (Exception e) { LogManager.e("打开联系人信息失败"); }
添加权限申请
选择联系人并返回
protected void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); if (Contacts1RequestCode == requestCode) {// 取联系信息返回 if (resultCode == RESULT_OK) { Uri cOntactData= data.getData(); Cursor cursor = getContentResolver().query(contactData, null, null, null, null); //Key联系人姓名,Value联系人手机号 MapphOneMap= this.getContactPhone(cursor); if (!cursor.isClosed()) { cursor.close(); } if (null != phoneMap && !phoneMap.isEmpty()) { Set keySet = phoneMap.keySet(); if (null != keySet && !keySet.isEmpty()) { Object[] keys = keySet.toArray(); String phOneName= (String) keys[0]; String phOneNo= phoneMap.get(phoneName); } } } } }
/** * 获取联系人姓名及手机号 * * @param cursor * @return Key为联系人姓名,Value为联系人手机号 */ private MapgetContactPhone(Cursor cursor) { Map resultMap = new HashMap (); String phOneName= null;// 姓名 String mobilePhOneNo= null;// 手机号 if (null != cursor) { cursor.moveToFirst(); // 获得联系人的ID号 int idFieldIndex = cursor .getColumnIndex(ContactsContract.Contacts._ID); String cOntactId= cursor.getString(idFieldIndex); // 联系人姓名 int idphOneNameIndex= cursor .getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME); phOneName= cursor.getString(idphoneNameIndex); // 获得联系人的电话号码的cursor; Cursor allPhOnes= getContentResolver().query( ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null, ContactsContract.CommonDataKinds.Phone.CONTACT_ID + "=?", new String[] { contactId }, null); // 所以联系电话(包话电话和手机号) List allPhOneNumList= new ArrayList (); if (allPhones.moveToFirst()) { // 遍历所有的电话号码 for (; !allPhones.isAfterLast(); allPhones.moveToNext()) { int telNoTypeIndex = allPhones .getColumnIndex(ContactsContract.CommonDataKinds.Phone.TYPE); int telNoType = allPhones.getInt(telNoTypeIndex); int telNoIndex = allPhones .getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER); String telNo = allPhones.getString(telNoIndex); allPhoneNumList.add(telNo); if (2 == telNoType) {// 手机号(原生态的SDK定义:mobile是2,home是1,work是3,other是7) mobilePhOneNo= telNo; break; } } if (!allPhones.isClosed()) { allPhones.close(); } if (null == mobilePhoneNo) {// 没有存贮手机号 if (!allPhoneNumList.isEmpty()) {// 存在其它号码 for (String tel : allPhoneNumList) { if (VerifyKit.isLegal(FormatType.MobilePhone, tel)) {// 取属于手机号格式 mobilePhOneNo= tel; break; } } } } } if (!cursor.isClosed()) { cursor.close(); } resultMap.put(phoneName, mobilePhoneNo); } return resultMap; }
如有疑问请留言或者到本站社区交流讨论,感谢阅读,希望能帮助到大家,谢谢大家对本站的支持!