在android中更快地从通讯簿中检索联系人

在android中更快地从通讯簿中检索联系人,android,contacts,addressbook,Android,Contacts,Addressbook,我想检索所有联系人的详细信息,如“电话号码”、“显示姓名”、“显示图像”和“电子邮件Id”。我使用下面的方法来做它,它的作品很好 public void readContacts() { Log.d("readcontacts", "::" + "true"); String phoneNumber = null; ContentResolver cr = getContentResolver(); Cursor cur = cr.query(ContactsCo

我想检索所有联系人的详细信息,如“电话号码”、“显示姓名”、“显示图像”和“电子邮件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);
        }
    }

}

但问题是检索大约400个联系人的详细信息大约需要45秒到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();
            }
然后我在Imageview上显示photojumb,如下所示:

 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;
}

是否有必要在每次写入时打开和关闭
数据库helperassets
?实际上,我不想使用数据库,我想在flyI上显示它。在循环外更改数据库打开和关闭的操作,但对我来说仍然需要太长时间。如果您希望消除数据库,那么就完全取消数据库操作,我认为使用
ContentProviderOperation
的批处理操作会有所帮助。您没有发布完整的代码,我的意思是读取电话号码和电子邮件idI面临相同的问题这里是2200个联系人,但将数据加载到列表中需要很多时间。您能发布完整的代码吗?@Ajit-这里是读取通讯录中所有联系人的完整代码。如果有2200个联系人,则不会超过3到4秒。您可以在“alContactEntities”中获取所有联系人的数组,其中包括电话号码和电子邮件ID?@Jigar-我想您只读取姓名和个人资料uri,我需要电话号码和电子邮件ID
/**
 * 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();
    }
}