获得手机通讯录联系人信息
- /**得到手机通讯录联系人信息**/
- private void getPhoneContacts() {
- ContentResolver resolver = mContext.getContentResolver();
- // 获取手机联系人
- Cursor phoneCursor = resolver.query(Phone.CONTENT_URI,PHONES_PROJECTION, null, null, null);
- if (phoneCursor != null) {
- while (phoneCursor.moveToNext()) {
- //得到手机号码
- String phoneNumber = phoneCursor.getString(PHONES_NUMBER_INDEX);
- //当手机号码为空的或者为空字段 跳过当前循环
- if (TextUtils.isEmpty(phoneNumber))
- continue;
- //得到联系人名称
- String contactName = phoneCursor.getString(PHONES_DISPLAY_NAME_INDEX);
- //得到联系人ID
- Long contactid = phoneCursor.getLong(PHONES_CONTACT_ID_INDEX);
- //得到联系人头像ID
- Long photoid = phoneCursor.getLong(PHONES_PHOTO_ID_INDEX);
- //得到联系人头像Bitamp
- Bitmap contactPhoto = null;
- //photoid 大于0 表示联系人有头像 如果没有给此人设置头像则给他一个默认的
- if(photoid > 0 ) {
- Uri uri =ContentUris.withAppendedId(ContactsContract.Contacts.CONTENT_URI,contactid);
- InputStream input = ContactsContract.Contacts.openContactPhotoInputStream(resolver, uri);
- contactPhoto = BitmapFactory.decodeStream(input);
- }else {
- contactPhoto = BitmapFactory.decodeResource(getResources(), R.drawable.contact_photo);
- }
- mContactsName.add(contactName);
- mContactsNumber.add(phoneNumber);
- mContactsPhonto.add(contactPhoto);
- }
- phoneCursor.close();
- }
- }
获得手机sim卡联系人信息
sim卡和手机本人 获取的方式类似 只是url有点不一样 ,须要注意的一点是 sim卡 是没有联系人头像的。
- /**得到手机SIM卡联系人人信息**/
- private void getSIMContacts() {
- ContentResolver resolver = mContext.getContentResolver();
- // 获取Sims卡联系人
- Uri uri = Uri.parse("content://icc/adn");
- Cursor phoneCursor = resolver.query(uri, PHONES_PROJECTION, null, null,
- null);
- if (phoneCursor != null) {
- while (phoneCursor.moveToNext()) {
- // 得到手机号码
- String phoneNumber = phoneCursor.getString(PHONES_NUMBER_INDEX);
- // 当手机号码为空的或者为空字段 跳过当前循环
- if (TextUtils.isEmpty(phoneNumber))
- continue;
- // 得到联系人名称
- String contactName = phoneCursor
- .getString(PHONES_DISPLAY_NAME_INDEX);
- //Sim卡中没有联系人头像
- mContactsName.add(contactName);
- mContactsNumber.add(phoneNumber);
- }
- phoneCursor.close();
- }
- }
这个界面就可以看到联系人的 名称 号码 以及头像了。如果想在模拟器上看须要将图片拷贝到SD卡中,然后在联系人中设置一下,这里就可以看到头像了,或者 真机上会比较清楚、
任意点击一个联系人会调用系统拨打电话的界面 ,代码如下。
- //调用系统方法拨打电话
- Intent dialIntent = new Intent(Intent.ACTION_CALL, Uri
- .parse("tel:" + mContactsNumber.get(position)));
- startActivity(dialIntent);
最重要的是须要AndroidManifest.xml中 加入权限 否则代码会报错的。 千万别忘了。
- <!-- 读取联系人权限 -->
- <uses-permission android:name="android.permission.READ_CONTACTS"/>
- <!-- 拨打电话权限 -->
- <uses-permission android:name="android.permission.CALL_PHONE"/>