Android获取手机联系人的方法
程序员文章站
2023-12-16 21:10:28
android 获取系统联系人信息的实例
一、获取手机联系人姓名及手机号
//跳转到系统联系人应用
intent intent = new intent...
android 获取系统联系人信息的实例
一、获取手机联系人姓名及手机号
//跳转到系统联系人应用 intent intent = new intent(intent.action_pick, contactscontract.contacts.content_uri); try { startactivityforresult(intent, contacts1requestcode); } catch (exception e) { logmanager.e("打开联系人信息失败"); }
添加权限申请
<uses-permission android:name="android.permission.read_contacts" />
选择联系人并返回
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联系人手机号 map<string, string> phonemap = this.getcontactphone(cursor); if (!cursor.isclosed()) { cursor.close(); } if (null != phonemap && !phonemap.isempty()) { set<string> 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 map<string, string> getcontactphone(cursor cursor) { map<string, string> resultmap = new hashmap<string, string>(); 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<string> allphonenumlist = new arraylist<string>(); 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; }
如有疑问请留言或者到本站社区交流讨论,感谢阅读,希望能帮助到大家,谢谢大家对本站的支持!