从android中的地址簿更快地检索联系人

时间:2014-10-03 04:10:34

标签: android contacts addressbook

我想检索所有联系人的详细信息,例如“电话号码”,“显示名称”,“显示图像”和“电子邮件ID”。我使用下面的方法来做它并且它工作正常。

public void readContacts() {
    Log.d("readcontacts", "::" + "true");
    String phoneNumber = null;
    ContentResolver cr = getContentResolver();
    Cursor cur = cr.query(ContactsContract.Contacts.CONTENT_URI, null,
            null, null, null);
    if (cur.getCount() > 0) {
        while (cur.moveToNext()) {
            // contactEntity = new ContactEntity();
            final ContentValues values = new ContentValues();
            String Contact_Id = cur.getString(cur
                    .getColumnIndex(ContactsContract.Contacts._ID));
            values.put(KEY_ID, Integer.parseInt(Contact_Id));

            int hasPhoneNumber = Integer
                    .parseInt(cur.getString(cur
                            .getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER)));
            /*
             * contactEntity .setContactFirstName(cur.getString(cur
             * .getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME)));
             */

            if (Integer
                    .parseInt(cur.getString(cur
                            .getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER))) > 0) {
                // System.out.println("name : " + name + ", ID : " + id);
                // sb.append("\n Contact Name:" + name);
                Cursor pCur = cr
                        .query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
                                null,
                                ContactsContract.CommonDataKinds.Phone.CONTACT_ID
                                        + " = ?",
                                new String[] { Contact_Id }, null);
                if (pCur.moveToFirst()) {
                    phoneNumber = pCur
                            .getString(pCur
                                    .getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
                    // sb.append("\n Phone number:" + phone);
                    // System.out.println("phone" + phone);

                }
                pCur.close();

                Cursor emailCur = cr
                        .query(ContactsContract.CommonDataKinds.Email.CONTENT_URI,
                                null,
                                ContactsContract.CommonDataKinds.Email.CONTACT_ID
                                        + " = ?",
                                new String[] { Contact_Id }, null);
                if (emailCur.moveToFirst()) {
                    values.put(
                            KEY_CONTACTEMAIL,
                            (emailCur.getString(emailCur
                                    .getColumnIndex(ContactsContract.CommonDataKinds.Email.DATA))));
                    // emailType = emailCur .getString(emailCur
                    // .getColumnIndex(ContactsContract.CommonDataKinds.Email.TYPE));

                }
                emailCur.close();

                if (phoneNumber.length() >= 10) {
                    final Uri my_contact_Uri = Uri.withAppendedPath(
                            ContactsContract.Contacts.CONTENT_URI,
                            String.valueOf(Contact_Id));


                                InputStream photo_stream = ContactsContract.Contacts
                                        .openContactPhotoInputStream(
                                                getContentResolver(),
                                                my_contact_Uri);
                                if (photo_stream != null) {
                                    BufferedInputStream buf = new BufferedInputStream(
                                            photo_stream);
                                    Bitmap my_btmp = BitmapFactory
                                            .decodeStream(buf);
                                    ByteArrayOutputStream bos = new ByteArrayOutputStream();
                                    my_btmp.compress(Bitmap.CompressFormat.PNG,
                                            100, bos);
                                    byte[] bArray = bos.toByteArray();
                                    values.put(KEY_CONTACTIMAGE, bArray);
                                }
                            } catch (Exception e) {
                                // TODO Auto-generated catch block
                                e.printStackTrace();
                            }

                        }


                    // contactEntity.setBitmapContactImage(my_btmp);
                    values.put(
                            KEY_CONTACTNAME,
                            String.valueOf(cur.getString(cur
                                    .getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME))));
                    values.put(KEY_CONTACTNUMBER,
                            String.valueOf(phoneNumber));
                    databaseHelperAssets.open();
                    databaseHelperAssets.addcontact(values);
                    databaseHelperAssets.close();
                }

            }
            // values.put(KEY_TIMESWAP,
            // String.valueOf(taskEnitiy.getTimeswap()));
            // int SDK_INT = android.os.Build.VERSION.SDK_INT;

            /*
             * if (SDK_INT >= 11) { contactEntity
             * .setImgUri(cur.getString(cur
             * .getColumnIndex(ContactsContract.
             * CommonDataKinds.Phone.PHOTO_URI))); }
             */
            // alContactEntities.add(contactEntity);
        }
    }

}

但问题是需要大约45秒到1分钟来检索大约400个联系人的详细信息。每次有需要检索联系时,我都不能让我的用户等待这么久。那么任何人都可以帮我减少联系的检索时间吗?我是用来将我的联系人存储在数据库中,因为我只是在应用程序启动时才第一次阅读我的联系人。所以我会找到更好的方法来检索它,我可以排除在数据库中存储联系人。在此先感谢!!

1 个答案:

答案 0 :(得分:1)

感谢所有人的帮助和暗示,但最后我得到了答案。我使用下面的代码来获取显示图像:

  InputStream photo_stream = ContactsContract.Contacts
                                    .openContactPhotoInputStream(
                                            getContentResolver(),
                                            my_contact_Uri);
                            if (photo_stream != null) {
                                BufferedInputStream buf = new BufferedInputStream(
                                        photo_stream);
                                Bitmap my_btmp = BitmapFactory
                                        .decodeStream(buf);
                                ByteArrayOutputStream bos = new ByteArrayOutputStream();
                                my_btmp.compress(Bitmap.CompressFormat.PNG,
                                        100, bos);
                                byte[] bArray = bos.toByteArray();
                                values.put(KEY_CONTACTIMAGE, bArray);
                            }
                        } catch (Exception e) {
                            // TODO Auto-generated catch block
                            e.printStackTrace();
                        }

但是我将其改为:

try {
                String phototjumb = cur.getString(cur.getColumnIndex(ContactsContract.Contacts.PHOTO_THUMBNAIL_URI));
                if(phototjumb != null && !phototjumb.toString().equalsIgnoreCase("")){
                    contactEntity.setImageURI(phototjumb);
                    Log.d("photojumb", "::" + phototjumb);
                }
            } catch (Exception e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }

而且我用来将photojumb显示在我的Imageview上:

 imgContactImg.setImageURI(Uri.parse(contactEntity.getImageURI()));

就是这样。现在我几乎不需要2秒钟就可以直接向自定义列表视图显示联系人。

不要担心我发布完整的方法来检索联系人。这是::

@SuppressLint("InlinedApi")
public void readContacts() {
    ContentResolver cr = getContentResolver();
    Cursor cur = cr.query(ContactsContract.Contacts.CONTENT_URI, null,
            null, null, null);
    if (cur.getCount() > 0) {
        while (cur.moveToNext()) {
            contactEntity = new ContactEntity();
            String Contact_Id = cur.getString(cur
                    .getColumnIndex(ContactsContract.Contacts._ID));
            contactEntity
                    .setContactFirstName(cur.getString(cur
                            .getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME)));


            try {
                String phototjumb = cur.getString(cur.getColumnIndex(ContactsContract.Contacts.PHOTO_THUMBNAIL_URI));
                if(phototjumb != null && !phototjumb.toString().equalsIgnoreCase("")){
                    contactEntity.setImageURI(phototjumb);
                    Log.d("photojumb", "::" + phototjumb);
                }

            } catch (Exception e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }

            alContactEntities.add(contactEntity);
        }
    }

}

拥有快乐的编码。 :)

请通过以下附加的更新代码获取联系电话,显示名称,显示图像,电子邮件ID等。

public ArrayList<ContactEntity> readContacts1() {
    //Log.d("readcontacts", "::" + "true");
    alContactEntities = new ArrayList<ContactEntity>();
    String phoneNumber = null;
    String tempPhoneNumber = null;
    contactCount = 0;
    ContentResolver cr = activity.getContentResolver();

    Cursor cur = cr.query(
            ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null,
            null, null, null);

    if (cur.getCount() > 0) {
        while (cur.moveToNext()) {
            contactEntity = new ContactEntity();

            String Contact_Id = cur.getString(cur
                    .getColumnIndex(ContactsContract.Contacts._ID));

            if (Integer
                    .parseInt(cur.getString(cur
                            .getColumnIndex(ContactsContract.CommonDataKinds.Phone.HAS_PHONE_NUMBER))) > 0) {
                /*
                 * // System.out.println("name : " + name + ", ID : " + id);
                 * // sb.append("\n Contact Name:" + name);
                 */
                /*
                 * Cursor pCur = cr
                 * .query(ContactsContract.CommonDataKinds.Phone
                 * .CONTENT_URI, null,
                 * ContactsContract.CommonDataKinds.Phone.CONTACT_ID +
                 * " = ?", new String[] { Contact_Id }, null); if
                 * (pCur.moveToFirst()) {
                 */
                phoneNumber = cur
                        .getString(cur
                                .getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));



                /*
                 * String regexStr = "^[0-9\\-\\+]*$"; phoneNumber =
                 * phoneNumber.replaceAll("\\D","");
                 */
                //Log.d("PohneNumber", "" + phoneNumber);

                /*
                 * } pCur.close();
                 */

                // remove comment from below code to obtain email id
                /*Cursor emailCur = cr
                        .query(ContactsContract.CommonDataKinds
                                        .Email.CONTENT_URI, null,
                                ContactsContract.CommonDataKinds.Email.CONTACT_ID +
                                        " = ?", new String[]{Contact_Id}, null);
                if
                        (emailCur.moveToFirst()) {
                    contactEntity.setContactEmailId
                            ((emailCur.getString(emailCur
                                    .getColumnIndex(ContactsContract
                                            .CommonDataKinds.Email.DATA))));
                }
                emailCur.close();*/

                Uri uriBirthdate = ContactsContract.Data.CONTENT_URI;

                String[] projectionBirthdate = new String[]{
                        ContactsContract.Contacts.DISPLAY_NAME,
                        ContactsContract.CommonDataKinds.Event.CONTACT_ID,
                        ContactsContract.CommonDataKinds.Event.START_DATE
                };

                String whereBirthdateCaluse =
                        ContactsContract.CommonDataKinds.Event.CONTACT_ID + "= ? AND " +
                                ContactsContract.Data.MIMETYPE + "= ? AND " +
                                ContactsContract.CommonDataKinds.Event.TYPE + "=" +
                                ContactsContract.CommonDataKinds.Event.TYPE_BIRTHDAY;
                String[] selectionArgsBirthdate = new String[]{Contact_Id,
                        ContactsContract.CommonDataKinds.Event.CONTENT_ITEM_TYPE
                };
                String sortOrder = null;
                Cursor birthDayCur = cr.query(uriBirthdate, projectionBirthdate, whereBirthdateCaluse,
                        selectionArgsBirthdate, sortOrder);

                if
                        (birthDayCur.moveToFirst()) {
                    int bDayColumn = birthDayCur.getColumnIndex(ContactsContract.CommonDataKinds.Event.START_DATE);
                    String bDay = birthDayCur.getString(bDayColumn);
                    Log.d("Birthday", " : " + bDay);
                }
                birthDayCur.close();


                if (phoneNumber.length() >= 9
                        && UDF.isValidPhoneNumber(phoneNumber)) {
                    /*
                     * Uri my_contact_Uri = Uri.withAppendedPath(
                     * ContactsContract.Contacts.CONTENT_URI,
                     * String.valueOf(Contact_Id));
                     * 
                     * try { final InputStream photo_stream =
                     * ContactsContract.Contacts
                     * .openContactPhotoInputStream( activity.getContentResolver(),
                     * my_contact_Uri); if (photo_stream != null) { new
                     * Thread(new Runnable() {
                     * 
                     * @Override public void run() { BufferedInputStream buf
                     * = new BufferedInputStream( photo_stream); Bitmap
                     * my_btmp = BitmapFactory .decodeStream(buf);
                     * ByteArrayOutputStream bos = new
                     * ByteArrayOutputStream();
                     * my_btmp.compress(Bitmap.CompressFormat.PNG, 100,
                     * bos); byte[] bArray = bos.toByteArray();
                     * values.put(KEY_CONTACTIMAGE, bArray);
                     * 
                     * } }).start();
                     * 
                     * 
                     * } } catch (Exception e) { // TODO Auto-generated
                     * catch block e.printStackTrace(); } //
                     * contactEntity.setBitmapContactImage(my_btmp);
                     */
                    try {
                        String phototjumb = null;
                        int SDK_INT = android.os.Build.VERSION.SDK_INT;
                        if (SDK_INT >= 11) {
                            phototjumb = cur
                                    .getString(cur
                                            .getColumnIndex(ContactsContract.CommonDataKinds.Phone.PHOTO_THUMBNAIL_URI));
                        } else {
                            phototjumb = cur
                                    .getString(cur
                                            .getColumnIndex(ContactsContract.CommonDataKinds.Phone.PHOTO_THUMBNAIL_URI));
                        }

                        if (phototjumb != null
                                && !phototjumb.toString().equalsIgnoreCase(
                                "")) {
                            contactEntity.setImageURI(phototjumb);
                            //Log.d("photojumb", "::" + phototjumb);
                        }


                        /*if(eventEntity.getContactIndex() != -1 && contactCount == eventEntity.getContactIndex()){
                            if(eventEntity.getBlobImage() != null){
                                byte[] bb = eventEntity.getBlobImage();

                                String selectedImagePath = getRealPathFromURI(getImageUri(
                                        activity,
                                        BitmapFactory.decodeByteArray(bb, 0, bb.length)));

                                Bitmap vt = BitmapFactory.decodeFile(selectedImagePath);

                                Bitmap bitmap = Bitmap
                                        .createScaledBitmap(vt, 50, 50, false);

                                //imgContactImg.setImageBitmap(UDF.getCroppedBitmap(bitmap));

                                contactEntity.setImageURI(
                                        getImageUri(activity, vt).toString());
                            }


                        }*/

                        /*
                         * InputStream photo_stream =
                         * ContactsContract.Contacts
                         * .openContactPhotoInputStream
                         * (activity.getContentResolver(), my_contact_Uri);
                         * if(photo_stream != null){ // Use this method to
                         * set image using input stream
                         * 
                         * contactEntity.setInputStreamImage(photo_stream);
                         * 
                         * //Use this method to set image using bitmap (But
                         * it is time consuming)
                         * 
                         * BufferedInputStream buf = new
                         * BufferedInputStream(photo_stream); Bitmap my_btmp
                         * = BitmapFactory.decodeStream(buf);
                         * contactEntity.setBitmapContactImage(my_btmp); }
                         */
                    } catch (Exception e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                    if (cur.getString(cur
                            .getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME)) == null
                            || cur.getString(
                            cur.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME))
                            .trim().equalsIgnoreCase("")) {
                        contactEntity.setContactFirstName(String
                                .valueOf(phoneNumber));
                    } else {
                        contactEntity
                                .setContactFirstName(String.valueOf(cur.getString(cur
                                        .getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME))));
                    }

                    contactEntity.setContactNumber(String
                            .valueOf(phoneNumber));
                    contactEntity.setUniquePosition(contactCount);
                    contactCount++;

                    alContactEntities.add(contactEntity);

                }

            }
            // values.put(KEY_TIMESWAP,
            // String.valueOf(taskEnitiy.getTimeswap()));
            // int SDK_INT = android.os.Build.VERSION.SDK_INT;

            /*
             * if (SDK_INT >= 11) { contactEntity
             * .setImgUri(cur.getString(cur
             * .getColumnIndex(ContactsContract.
             * CommonDataKinds.Phone.PHOTO_URI))); }
             */
            // alContactEntities.add(contactEntity);

        }
    }
    cur.close();
    return alContactEntities;
}

对于UDF.isValidPhoneNumber(phoneNumber)

/**
 * Check if phone number is valid or not
 */
public static final boolean isValidPhoneNumber(CharSequence target) {
    if (target == null || TextUtils.isEmpty(target)) {
        return false;
    } else {
        return android.util.Patterns.PHONE.matcher(target).matches();
    }
}