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": "[email protected]"
                }
            ],
            "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": "[email protected]"
                },
                {
                    "type": "住宅",
                    "email": "[email protected]"
                }
            ],
            "name": "小强",
            "org": [
                {
                    "orgName": "三月",
                    "title": "攻城狮"
                }
            ],
            "note": "comment  for test"
        }
    ]
}


 

 

你可能感兴趣的:(Android 读取联系人(详细))