在android中获取联系人非常慢

在android中获取联系人非常慢,android,contacts,android-contacts,Android,Contacts,Android Contacts,我编写了一个代码,从联系人中获取联系人姓名、电话号码和图像,并在android的listview中显示。它工作正常,但需要更多的时间来加载。我曾尝试在代码的某些部分使用多线程。但加载时间没有缩短 以下是onCreate()方法: protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); lv

我编写了一个代码,从联系人中获取联系人姓名、电话号码和图像,并在android的listview中显示。它工作正常,但需要更多的时间来加载。我曾尝试在代码的某些部分使用多线程。但加载时间没有缩短

以下是
onCreate()
方法:

protected void onCreate(Bundle savedInstanceState) {
 super.onCreate(savedInstanceState);
 setContentView(R.layout.activity_main);

 lvDetail = (ListView) findViewById(R.id.listView1);

 fetchcontacts();

 lvDetail.setAdapter(new MyBaseAdapter(context, myList));
 }
以下是获取联系人的代码:

  private void fetchcontacts() {

        // TODO Auto-generated method stub
        Cursor cursor = getContentResolver().query(ContactsContract.Contacts.CONTENT_URI, null,
                null, null, ContactsContract.Contacts.DISPLAY_NAME + " ASC");
                int count = cursor.getCount();
                if (count > 0) {
                     Toast.makeText(context, "count >0", Toast.LENGTH_SHORT).show();
                    while (cursor.moveToNext()) {
                        String columnId = ContactsContract.Contacts._ID;
                        int cursorIndex = cursor.getColumnIndex(columnId);
                        String id = cursor.getString(cursorIndex);

                      name = cursor.getString(cursor
                .getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));


                      Toast.makeText(context, "Toast 1", Toast.LENGTH_SHORT).show();




                        int numCount = Integer.parseInt(cursor.getString(cursor
                            .getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER)));
                        if (numCount > 0) {
                             Toast.makeText(context, "Toast 2", Toast.LENGTH_SHORT).show();
                            Cursor phoneCursor = getContentResolver().query(
                ContactsContract.CommonDataKinds.Phone.CONTENT_URI,null,
                                CommonDataKinds.Phone.CONTACT_ID+" = ?", new String[] { id
                }, ContactsContract.Contacts.DISPLAY_NAME + " ASC");

                                while (phoneCursor.moveToNext()) {
                                     Toast.makeText(context, "Toast 3", Toast.LENGTH_SHORT).show();
                              phoneNo = phoneCursor.getString(phoneCursor
                .getColumnIndex(ContactsContract.CommonDataKinds.
                Phone.NUMBER));


                                String image_uri = phoneCursor
                                         .getString(phoneCursor
                                         .getColumnIndex(ContactsContract.CommonDataKinds.Phone.PHOTO_URI));

                             if (image_uri != null) {
                                 Toast.makeText(context, "Toast 4", Toast.LENGTH_SHORT).show();
                                 System.out.println(Uri.parse(image_uri));
                                 try {
                              bitmap = MediaStore.Images.Media
                                 .getBitmap(this.getContentResolver(),
                                 Uri.parse(image_uri));
                                // sb.append("\n Image in Bitmap:" + bitmap);
                                // System.out.println(bitmap);

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

                                 }
                             Toast.makeText(context, name, Toast.LENGTH_SHORT).show();

                                    getDataInList(name,phoneNo,bitmap);
                                 name=null;
                                 phoneNo=null;
                                 Drawable myDrawable = getResources().getDrawable(R.drawable.star1);
                                 bitmap = ((BitmapDrawable) myDrawable).getBitmap();



                                    }
                                    phoneCursor.close();
                                }

                            }


                        }

在这里,listview的setAdapter()函数在将所有联系人提取到ArrayList后工作。有人知道如何在获取联系人时显示联系人吗?有任何示例代码吗?

1.从
光标
中读取,您只需要根据您的要求\u ID,有电话号码,显示姓名,因此更改光标读数

Cursor cursor = getContentResolver().query(
            ContactsContract.Contacts.CONTENT_URI,
            new String[] { ContactsContract.Contacts._ID,
                    ContactsContract.Contacts.HAS_PHONE_NUMBER,
                    ContactsContract.Contacts.DISPLAY_NAME }, null, null,
            ContactsContract.Contacts.DISPLAY_NAME + " ASC");
2.不要在UI线程中执行耗时的过程。请改用
AsyncTask


注意:这两个步骤将在一定程度上解决..但不完全解决回退任务中使用的larse大小的联系人。 Uri=Uri.withAppendedPath(ContactsContract.PhoneLookup.CONTENT\u FILTER\u Uri,Uri.encode(数字[i])


对我来说,最快的方式就是这么远

ContentResolver cr = mContext.getContentResolver(); Cursor cursor= mContext.getContentResolver().query(ContactsContract.Contacts.CONTENT_URI, PROJECTION, "HAS_PHONE_NUMBER <> 0", null, null); if (cursor!= null) { final int displayNameIndex = cursor.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME); final int numberIndex = cursor.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER); final int idIndex= cursor.getColumnIndex(ContactsContract.Contacts._ID); String displayName, number = null, idValue; while (cursor.moveToNext()) {
   displayName = cursor.getString(displayNameIndex);
   idValue= cursor.getString(idIndex);
   Cursor phones  = mContext.getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null, "contact_id = '" + idValue + "'", null, null);
   phones.moveToFirst();
   try {
   number = phones.getString(phones.getColumnIndex("data1"));
   }
   catch (CursorIndexOutOfBoundsException e)
   {`
   }
   phones.close();
   userList.add(new ContactModel(displayName , number , null , }
ContentResolver cr=mContext.getContentResolver();Cursor Cursor=mContext.getContentResolver().query(ContactsContract.Contacts.CONTENT\u URI,投影,“HAS\u PHONE\u NUMBER 0”,null,null);if(cursor!=null){final int displayNameIndex=cursor.getColumnIndex(ContactsContract.Contacts.DISPLAY\u NAME);final int numberIndex=cursor.getColumnIndex(ContactsContract.Contacts.DISPLAY\u NAME);final int numberIndex=cursor.getColumnIndex(Contacts.Contacts.ID);String displayName=null,idValue;while(cursor.moveToNext()){
displayName=cursor.getString(displayNameIndex);
idValue=cursor.getString(idIndex);
Cursor phones=mContext.getContentResolver().query(ContactsContract.CommonDataTypes.Phone.CONTENT_URI,null,“contact_id='”+idValue+“”,null,null);
moveToFirst();
试一试{
number=phones.getString(phones.getColumnIndex(“data1”);
}
捕获(游标索引自动边界异常e)
{`
}
电话。关闭();
添加(新的ContactModel(displayName,number,null,}

我用reduce repeated query做的,它很昂贵。我最好的解决方案是,该方法找到每个联系人的所有手机和电子邮件,并插入到每个联系人的列表中。现在速度很快:)

//联系人实体
公共级MobileContact{
公共字符串名称;
公众联络;
公共类型;
公共MobileContact(字符串触点,类型){
name=“”;
this.contact=contact;
this.type=type;
}
public MobileContact(字符串名称、字符串联系人、类型){
this.name=名称;
this.contact=contact;
this.type=type;
}
公共枚举类型{
电子邮件、电话
}
@凌驾
公共字符串toString(){
返回“MobileContact{”+
“name=”+name+“\”+
“,contact='”+contact+'\''+
“,type=“+type”+
'}';
}
}
//收集联系人的方法
公共列表getAllContacts(){
调试(“获取所有联系人”);
List mobileContacts=new ArrayList();
ContentResolver ContentResolver=context.getContentResolver();
//添加所有手机联系人
游标phonesCursor=contentResolver.query(ContactsContact.CommonDataTypes.Phone.CONTENT\u URI,新字符串[]{ContactsContact.CommonDataTypes.Phone.NUMBER,ContactsContact.CommonDataTypes.Phone.CONTACT\u ID},null,null,null);
while(phonesCursor!=null&&phonesCursor.moveToNext(){
String contactId=phonesCursor.getString(phonesCursor.getColumnIndex(ContactsContract.CommonDataTypes.Phone.CONTACT_ID));
String phoneNumber=phonesCursor.getString(phonesCursor.getColumnIndex(ContactsContract.CommonDataTypes.Phone.NUMBER)).replace(“,”);
添加(新的MobileContact(联系人ID、电话号码、MobileContact.Type.PHONE));
}
if(phonesCursor!=null){
phonesCursor.close();
}
//添加所有电子邮件联系人
Cursor emailCursor=contentResolver.query(ContactsContract.CommonDataTypes.Email.CONTENT\u URI,新字符串[]{ContactsContract.CommonDataTypes.Email.DATA,ContactsContract.CommonDataTypes.Email.CONTACT\u ID},null,null,null);
while(emailCursor!=null&&emailCursor.moveToNext(){
String contactId=emailCursor.getString(emailCursor.getColumnIndex(ContactsContract.CommonDataTypes.Email.CONTACT_ID));
String email=emailCursor.getString(emailCursor.getColumnIndex(ContactsContract.CommonDataTypes.email.DATA));
添加(新的MobileContact(联系人ID、电子邮件、MobileContact.Type.email));
}
如果(emailCursor!=null){
emailCursor.close();
}
//获取联系人姓名映射
Map contactMap=newhashmap();
Cursor contactsCursor=contentResolver.query(ContactsContract.Contacts.CONTENT\u URI,新字符串[]{ContactsContract.Contacts.\u ID,ContactsContract.Contacts.DISPLAY\u名称,ContactsContract.Contacts.HAS\u PHONE\u NUMBER},null,null,ContactsContract.Contacts.DISPLAY\u名称);
while(contactsCursor!=null&&contactsCursor.moveToNext(){
String contactId=contactsCursor.getString(contactsCursor.getColumnIndex(ContactsContract.Contacts.\u ID));
String contactName=contactsCursor.getString(contactsCursor.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
contactMap.put(contactId、contactName);
}
if(phonesCursor!=null){
phonesCursor.close();
}
//替换contactId以显示名称
用于(MobileContact MobileContact:mobileContacts){
String displayName=contactMap.get(mobileContact.name);
美孚利
ContentResolver cr = mContext.getContentResolver(); Cursor cursor= mContext.getContentResolver().query(ContactsContract.Contacts.CONTENT_URI, PROJECTION, "HAS_PHONE_NUMBER <> 0", null, null); if (cursor!= null) { final int displayNameIndex = cursor.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME); final int numberIndex = cursor.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER); final int idIndex= cursor.getColumnIndex(ContactsContract.Contacts._ID); String displayName, number = null, idValue; while (cursor.moveToNext()) {
   displayName = cursor.getString(displayNameIndex);
   idValue= cursor.getString(idIndex);
   Cursor phones  = mContext.getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null, "contact_id = '" + idValue + "'", null, null);
   phones.moveToFirst();
   try {
   number = phones.getString(phones.getColumnIndex("data1"));
   }
   catch (CursorIndexOutOfBoundsException e)
   {`
   }
   phones.close();
   userList.add(new ContactModel(displayName , number , null , }
//contact entity
public class MobileContact {
    public String name;
    public String contact;
    public Type type;

    public MobileContact(String contact, Type type) {
        name = "";
        this.contact = contact;
        this.type = type;
    }

    public MobileContact(String name, String contact, Type type) {
        this.name = name;
        this.contact = contact;
        this.type = type;
    }

    public enum Type {
        EMAIL, PHONE
    }

    @Override
    public String toString() {
        return "MobileContact{" +
                "name='" + name + '\'' +
                ", contact='" + contact + '\'' +
                ", type=" + type +
                '}';
    }
}

// method for collect contacts
public List<MobileContact> getAllContacts() {
        log.debug("get all contacts");
        List<MobileContact> mobileContacts = new ArrayList<>();
        ContentResolver contentResolver = context.getContentResolver();

        // add all mobiles contact
        Cursor phonesCursor = contentResolver.query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, new String[]{ContactsContract.CommonDataKinds.Phone.NUMBER, ContactsContract.CommonDataKinds.Phone.CONTACT_ID}, null, null, null);
        while (phonesCursor != null && phonesCursor.moveToNext()) {
            String contactId = phonesCursor.getString(phonesCursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.CONTACT_ID));
            String phoneNumber = phonesCursor.getString(phonesCursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER)).replace(" ", "");
            mobileContacts.add(new MobileContact(contactId, phoneNumber, MobileContact.Type.PHONE));
        }
        if (phonesCursor != null) {
            phonesCursor.close();
        }

        // add all email contact
        Cursor emailCursor = contentResolver.query(ContactsContract.CommonDataKinds.Email.CONTENT_URI, new String[]{ContactsContract.CommonDataKinds.Email.DATA, ContactsContract.CommonDataKinds.Email.CONTACT_ID}, null, null, null);
        while (emailCursor != null && emailCursor.moveToNext()) {
            String contactId = emailCursor.getString(emailCursor.getColumnIndex(ContactsContract.CommonDataKinds.Email.CONTACT_ID));
            String email = emailCursor.getString(emailCursor.getColumnIndex(ContactsContract.CommonDataKinds.Email.DATA));
            mobileContacts.add(new MobileContact(contactId, email, MobileContact.Type.EMAIL));
        }
        if (emailCursor != null) {
            emailCursor.close();
        }

        // get contact name map
        Map<String, String> contactMap = new HashMap<>();
        Cursor contactsCursor = contentResolver.query(ContactsContract.Contacts.CONTENT_URI, new String[]{ContactsContract.Contacts._ID, ContactsContract.Contacts.DISPLAY_NAME, ContactsContract.Contacts.HAS_PHONE_NUMBER}, null, null, ContactsContract.Contacts.DISPLAY_NAME);
        while (contactsCursor != null && contactsCursor.moveToNext()) {
            String contactId = contactsCursor.getString(contactsCursor.getColumnIndex(ContactsContract.Contacts._ID));
            String contactName = contactsCursor.getString(contactsCursor.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
            contactMap.put(contactId, contactName);
        }
        if (phonesCursor != null) {
            phonesCursor.close();
        }


        // replace contactId to display name
        for (MobileContact mobileContact : mobileContacts) {
            String displayName = contactMap.get(mobileContact.name);
            mobileContact.name = displayName != null ? displayName : "";
        }

        // sort list by name
        Collections.sort(mobileContacts, new Comparator<MobileContact>() {
            @Override
            public int compare(MobileContact c1, MobileContact c2) {
                return c1.name.compareTo(c2.name);
            }
        });

        return mobileContacts;
    }