Android 读取联系人(详细)

import java.io.InputStream;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.content.ContentUris;
import android.content.Context;
import android.database.Cursor;
import android.net.Uri;
import android.provider.ContactsContract;
import android.util.Log;

public class CopyOfContactCollector {

    private static final String TAG = CopyOfContactCollector.class.getSimpleName();
    
    private static final String KEY_BIRTH = "birthday";
    private static final String KEY_ADDR = "address";
    private static final String KEY_NICKNAME = "nickname";
    private static final String KEY_ORG = "org";
    private static final String KEY_IM = "IM";
    private static final String KEY_NOTE = "note";
    private static final String KEY_EMAIL = "email";
    private static final String KEY_PHONE = "phone";
    private static final String KEY_WEBSITE = "website";
    private static final String KEY_PHOTO = "photo";
    
    private Context context;

    public CopyOfContactCollector(Context context) {
        this.context = context;
    }
    
    public void getContacts() {

        Cursor cursor = null;
        try {
            cursor = context.getContentResolver().query(
                    ContactsContract.Contacts.CONTENT_URI, 
                    null,
                    null, 
                    null, 
                    null);
            
            JSONArray contactList = new JSONArray();
            while (cursor.moveToNext()) {
                String contactId = cursor.getString(cursor
                        .getColumnIndex(ContactsContract.Contacts._ID));
                int hasPhone = cursor.getInt(cursor
                        .getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER));
                String contactName = cursor.getString(cursor
                        .getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
                long photoId = cursor.getLong(cursor.getColumnIndex(ContactsContract.Contacts.PHOTO_ID));
                
                JSONObject item = new JSONObject();
                item.put("id", contactId);
                item.put("name", contactName);
                
                // phone
                if (hasPhone == 1) {
                    this.getPhone(contactId, item);
                }
                
                // photo
                this.getPhoto(contactId, photoId, item);
                
                // email
                this.getEmail(contactId, item);
               
                // address
                this.getAddress(contactId, item);
                
                // birthdat
                this.getBirthday(contactId, item);
                
                // instant message
                this.getIM(contactId, item);
                
                // nickname
                this.getNickname(contactId, item);
                
                // note
                this.getNote(contactId, item);
                
                // org
                this.getOrg(contactId, item);
                
                // website
                this.getWebsite(contactId, item);
                
                contactList.put(item);
            }
            
            JSONObject data = new JSONObject();
            data.put("CONTACTS", contactList);
            data.put("TIMESTAMP", System.currentTimeMillis());
            
            System.out.println(data.toString());
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (cursor != null) {
                cursor.close();
            }
        }
    }
    
    private void getPhone (String contactId, JSONObject data) throws JSONException {
        Cursor pCur = null;
        try {
            pCur = context.getContentResolver().query(
                    ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
                    null,
                    ContactsContract.CommonDataKinds.Phone.CONTACT_ID +" = ?",
                    new String[]{contactId + ""}, 
                    null);
            
            JSONArray phoneList = new JSONArray();
            while (pCur.moveToNext()) {
                 int type = pCur.getInt(pCur.getColumnIndex(
                         ContactsContract.CommonDataKinds.Phone.TYPE));
                 String phoneType = ContactsContract.CommonDataKinds.Phone.getTypeLabel(
                         context.getResources(), type, "").toString();
                 String phoneNumber = pCur.getString(pCur.getColumnIndex(
                         ContactsContract.CommonDataKinds.Phone.NUMBER));
             
                 JSONObject item = new JSONObject();
                 item.put("phone", phoneNumber);
                 item.put("type", phoneType);
                 
                 phoneList.put(item);
            }
            
            data.put(KEY_PHONE, phoneList);
        } finally {
            if (pCur != null) {
                pCur.close();
            }
        }
    }
    
    private void getEmail (String contactId, JSONObject data) throws JSONException {
        Cursor emailCur = null;
        try {
            emailCur = context.getContentResolver().query(
                    ContactsContract.CommonDataKinds.Email.CONTENT_URI,
                    null,
                    ContactsContract.CommonDataKinds.Email.CONTACT_ID + " = ?",
                    new String[]{contactId}, 
                    null);
            
            JSONArray emailList = new JSONArray();
            while (emailCur.moveToNext()) {
                String email = emailCur.getString(emailCur.getColumnIndex(
                            ContactsContract.CommonDataKinds.Email.DATA));
                int type = emailCur.getInt(emailCur.getColumnIndex(
                            ContactsContract.CommonDataKinds.Email.TYPE));
                String emailType = ContactsContract.CommonDataKinds.Email.getTypeLabel(
                            context.getResources(), type, "").toString();
                
                JSONObject item = new JSONObject();
                item.put("email", email);
                item.put("type", emailType);
              
                emailList.put(item);
            }
            
            data.put(KEY_EMAIL, emailList);
        } finally {
            if (emailCur != null) {
                emailCur.close();
            }
        }
    }
    
    private void getNote (String contactId, JSONObject data) throws JSONException {
        Cursor noteCur = null;
        try {
            String noteWhere = 
                ContactsContract.Data.CONTACT_ID + " = ? AND " + 
                ContactsContract.Data.MIMETYPE + " = ?";
            
            String[] noteWhereParams = new String[]{
                        contactId,
                        ContactsContract.CommonDataKinds.Note.CONTENT_ITEM_TYPE};
            
            noteCur = context.getContentResolver().query(
                        ContactsContract.Data.CONTENT_URI, 
                        null, 
                        noteWhere, 
                        noteWhereParams, 
                        null);
            if (noteCur.moveToFirst()) {
                String note = noteCur.getString(noteCur.getColumnIndex(
                            ContactsContract.CommonDataKinds.Note.NOTE));
                data.put(KEY_NOTE, note);
            }
        } finally {
            if (noteCur != null) {
                noteCur.close();
            }
        }
    }
    
    private void getWebsite (String contactId, JSONObject data) throws JSONException {
        Cursor websiteCur = null;
        try {
            String where = 
                ContactsContract.Data.CONTACT_ID + " = ? AND " + 
                ContactsContract.Data.MIMETYPE + " = ?";
            
            String[] whereParams = new String[]{
                        contactId,
                        ContactsContract.CommonDataKinds.Website.CONTENT_ITEM_TYPE};
            
            websiteCur = context.getContentResolver().query(
                        ContactsContract.Data.CONTENT_URI, 
                        null, 
                        where, 
                        whereParams, 
                        null);
            if (websiteCur.moveToFirst()) {
                String website = websiteCur.getString(websiteCur.getColumnIndex(
                            ContactsContract.CommonDataKinds.Website.URL));
                data.put(KEY_WEBSITE, website);
            }
        } finally {
            if (websiteCur != null) {
                websiteCur.close();
            }
        }
    }
    
    private void getIM (String contactId, JSONObject data) throws JSONException {
        Cursor imCur = null;
        try {
            String imWhere = 
                ContactsContract.Data.CONTACT_ID + " = ? AND " + 
                ContactsContract.Data.MIMETYPE + " = ?";
            
            String[] imWhereParams = new String[]{contactId,
                    ContactsContract.CommonDataKinds.Im.CONTENT_ITEM_TYPE};
            
            imCur = context.getContentResolver().query(
                    ContactsContract.Data.CONTENT_URI,
                    null, 
                    imWhere, 
                    imWhereParams, 
                    null);
            
            JSONArray imList = new JSONArray();
            while (imCur.moveToNext()) {
                String imName = imCur.getString(
                         imCur.getColumnIndex(ContactsContract.CommonDataKinds.Im.DATA));
                int type = imCur.getInt(
                         imCur.getColumnIndex(ContactsContract.CommonDataKinds.Im.TYPE));
                String imType = ContactsContract.CommonDataKinds.Im.getTypeLabel(
                            context.getResources(), type, "").toString();
                
                JSONObject item = new JSONObject();
                item.put("imName", imName);
                item.put("imType", imType);
                
                imList.put(item);
            }
            
            data.put(KEY_IM, imList);
        } finally {
            if (imCur != null) {
                imCur.close();
            }
        }
    }
    
    private void getOrg (String contactId, JSONObject data) throws JSONException {
        Cursor orgCur = null;
        try {
            String orgWhere = 
                ContactsContract.Data.CONTACT_ID + " = ? AND " + 
                ContactsContract.Data.MIMETYPE + " = ?";
            
            String[] orgWhereParams = new String[]{contactId,
                    ContactsContract.CommonDataKinds.Organization.CONTENT_ITEM_TYPE};
            
            orgCur = context.getContentResolver().query(
                    ContactsContract.Data.CONTENT_URI,
                    null, 
                    orgWhere, 
                    orgWhereParams, 
                    null);
            JSONArray orgList = new JSONArray();
            while (orgCur.moveToNext()) {
                String orgName = orgCur.getString(orgCur.getColumnIndex(
                            ContactsContract.CommonDataKinds.Organization.DATA));
                String title = orgCur.getString(orgCur.getColumnIndex(
                        ContactsContract.CommonDataKinds.Organization.TITLE));
                
                JSONObject item = new JSONObject();
                item.put("orgName", orgName);
                item.put("title", title);
                
                orgList.put(item);
            }
            data.put(KEY_ORG, orgList);
        } finally {
          if (orgCur != null) {
              orgCur.close();
          }
        }
    }
    
    private void getNickname (String contactId, JSONObject data) throws JSONException {
        Cursor nicknameCur = null;
        try {
            String nicknameWhere = 
                ContactsContract.Data.CONTACT_ID + " = ? AND " + 
                ContactsContract.Data.MIMETYPE + " = ?";
            
            String[] nicknameWhereParams = new String[]{contactId,
                    ContactsContract.CommonDataKinds.Nickname.CONTENT_ITEM_TYPE};
                                    
            nicknameCur = context.getContentResolver().query(
                    ContactsContract.Data.CONTENT_URI,
                    null, 
                    nicknameWhere, 
                    nicknameWhereParams, 
                    null);
            
            while (nicknameCur.moveToNext()) {
                String nickname = nicknameCur.getString(nicknameCur.getColumnIndex(
                                    ContactsContract.CommonDataKinds.Nickname.NAME));
                data.put(KEY_NICKNAME, nickname);
                break;
            }
        } finally {
            if (nicknameCur != null) {
                nicknameCur.close();
            }
        }
    }

    private void getBirthday (String contactId, JSONObject data) throws JSONException {
        Cursor bCur = null;
        try {
            bCur = context.getContentResolver().query(
                    ContactsContract.Data.CONTENT_URI, 
                    new String[] {ContactsContract.CommonDataKinds.Event.DATA }, 
                    ContactsContract.Data.CONTACT_ID+" = "+contactId+" AND "
                    +ContactsContract.Data.MIMETYPE+" = '"
                    +ContactsContract.CommonDataKinds.Event.CONTENT_ITEM_TYPE+"' AND "
                    +ContactsContract.CommonDataKinds.Event.TYPE+" = "
                    +ContactsContract.CommonDataKinds.Event.TYPE_BIRTHDAY, 
                    null, 
                    null);
            while (bCur.moveToNext()) {
                String birthday = bCur.getString(0);
                data.put(KEY_BIRTH, birthday);
                break;
            }
        } finally {
            if (bCur != null) {
                bCur.close();
            }
        }
    }
    
    /**
     * Get address infomation of given contact.
     * 
     * @param contactId
     * @param data
     * @throws JSONException
     */
    private void getAddress (String contactId, JSONObject data) throws JSONException {
        
        Cursor postals = null;
        try {
            // address
            postals = context.getContentResolver().query(
                    ContactsContract.CommonDataKinds.StructuredPostal.CONTENT_URI,
                    null,
                    ContactsContract.CommonDataKinds.StructuredPostal.CONTACT_ID + " = " + contactId, 
                    null, 
                    null);
            
            int postFormattedNdx = postals.getColumnIndex(
                        ContactsContract.CommonDataKinds.StructuredPostal.FORMATTED_ADDRESS);
            int postTypeNdx = postals.getColumnIndex(
                        ContactsContract.CommonDataKinds.StructuredPostal.TYPE);
            int postStreetNdx = postals.getColumnIndex(
                        ContactsContract.CommonDataKinds.StructuredPostal.STREET);
            
            JSONArray addrList = new JSONArray();
            while (postals.moveToNext()) {
                String addressType = ContactsContract.CommonDataKinds.StructuredPostal
                            .getTypeLabel(context.getResources(), postTypeNdx, "").toString();
                String str1 = postals.getString(postFormattedNdx);
                String str2 = postals.getString(postStreetNdx);
                
                JSONObject item = new JSONObject();
                item.put("addressType", addressType);
                item.put("address", str1 + str2);
                
                addrList.put(item);
            } 
            
            data.put(KEY_ADDR, addrList);
        } finally {
            if (postals != null) {
                postals.close();
            }
        }
    }
    
    /**
     * Get the photo of given contact.
     * 
     * @param cr
     * @param id
     * @param photo_id
     * @return
     */
    private void getPhoto (String contactId, long photoId, JSONObject data) throws JSONException {
        
        Uri uri = ContentUris.withAppendedId(
                ContactsContract.Contacts.CONTENT_URI, Long.parseLong(contactId));
        
        InputStream input = ContactsContract.Contacts.openContactPhotoInputStream(
                    context.getContentResolver(), uri);
        if (input != null) {
            /*Bitmap photo =  BitmapFactory.decodeStream(input);
            data.put(KEY_PHOTO, photo);*/
        } else {
            Log.d(TAG, "First try failed to load photo!");
        }

        byte[] photoBytes = null;
        Uri photoUri = ContentUris.withAppendedId(ContactsContract.Data.CONTENT_URI, photoId);
        Cursor c = context.getContentResolver().query(
                photoUri, 
                new String[] {ContactsContract.CommonDataKinds.Photo.PHOTO},
                null, 
                null, 
                null);
        try {
            if (c.moveToFirst()) {
                photoBytes = c.getBlob(0);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            c.close();
        }

        if (photoBytes != null) {
            /*Bitmap photo = BitmapFactory.decodeByteArray(photoBytes, 0, photoBytes.length);
            data.put(KEY_PHOTO, photo);*/
        } else {
            Log.d(TAG, "Second try also failed!");
        }
    }


}


 

结果如下:

{
    "TIMESTAMP": 946692989880,
    "CONTACTS": [
        {
            "id": "801",
            "phone": [
                {
                    "type": "手机",
                    "phone": "11122"
                },
                {
                    "type": "家",
                    "phone": "222111"
                }
            ],
            "org": [],
            "IM": [],
            "address": [],
            "email": [
                {
                    "type": "工作",
                    "email": "zhangsan@qq.com"
                }
            ],
            "name": "john"
        },
        {
            "id": "802",
            "org": [],
            "IM": [],
            "address": [],
            "email": [],
            "name": "jack"
        },
        {
            "id": "803",
            "phone": [
                {
                    "type": "手机",
                    "phone": "1300070302533"
                }
            ],
            "org": [],
            "IM": [],
            "address": [],
            "email": [],
            "name": "alex"
        },
        {
            "id": "1064",
            "birthday": "2000-01-06",
            "phone": [
                {
                    "type": "手机",
                    "phone": "18811112222"
                },
                {
                    "type": "家",
                    "phone": "18811113333"
                },
                {
                    "type": "工作",
                    "phone": "18811114444"
                }
            ],
            "IM": [
                {
                    "imName": "12345678",
                    "imType": "其他"
                },
                {
                    "imName": "13245678",
                    "imType": "其他"
                }
            ],
            "website": "www.baidu.com",
            "nickname": "nickname",
            "address": [
                {
                    "address": "百度市谷歌西路10086号",
                    "addressType": "自定义"
                }
            ],
            "email": [
                {
                    "type": "工作",
                    "email": "office@xxx.com"
                },
                {
                    "type": "住宅",
                    "email": "home@xxx.com"
                }
            ],
            "name": "小强",
            "org": [
                {
                    "orgName": "三月",
                    "title": "攻城狮"
                }
            ],
            "note": "comment  for test"
        }
    ]
}


 

 

  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
Android 中,读取联系人的权限是 `android.permission.READ_CONTACTS`。这个权限允许应用程序读取设备上的联系人信息,例如姓名、电话号码、电子邮件地址等。 如果你的应用程序需要读取联系人信息,需要在 AndroidManifest.xml 文件中声明该权限。例如: ```xml <uses-permission android:name="android.permission.READ_CONTACTS" /> ``` 需要注意的是,从 Android 6.0(API 级别 23)开始,Android 引入了运行时权限机制,应用程序需要在运行时请求权限,用户可以选择允许或拒绝应用程序的权限请求。因此,在使用联系人权限时,需要检查权限是否已经被授予,如果没有被授予,需要向用户请求该权限。可以使用以下代码检查和请求联系人权限: ```java if (ContextCompat.checkSelfPermission(this, Manifest.permission.READ_CONTACTS) != PackageManager.PERMISSION_GRANTED) { // 如果没有读取联系人的权限,则向用户请求该权限 ActivityCompat.requestPermissions(this, new String[] { Manifest.permission.READ_CONTACTS }, REQUEST_CODE); } else { // 如果已经有读取联系人的权限,则执行读取联系人的操作 readContacts(); } ``` 在上面的代码中,我们首先检查应用程序是否已经被授予读取联系人的权限,如果没有被授予,则向用户请求该权限。如果已经被授予,则执行读取联系人的操作。需要注意的是,`REQUEST_CODE` 是请求权限时的请求码,用于在权限请求回调中处理权限请求的结果。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值