2012-06-01 34 views
14

Trong dự án của tôi, việc liên hệ mất nhiều thời gian để tải.Cách tải tất cả các địa chỉ liên lạc với thời gian tối thiểu trong Android

  • cách để giảm thời gian nhận được địa chỉ liên lạc
  • Giả sử có 1.000 địa chỉ liên lạc trong điện thoại của tôi là gì.
  • Ngay bây giờ nó được tham gia nhiều hơn 2 phút để tải tất cả các điểm tiếp xúc

Làm thế nào tôi có thể làm giảm thời gian để tải danh bạ? Bất kỳ suy nghĩ nào?

Tôi đã gọi liên kết sau khi lập trình phương pháp ban đầu.

http://www.coderzheaven.com/2011/06/13/get-all-details-from-contacts-in-android/

Trả lời

6

Tổng thời gian sẽ tùy thuộc vào trường bạn đang cố gắng truy cập từ bảng Danh bạ. Truy cập trường ít hơn có nghĩa là ít lặp hơn, ít xử lý hơn và do đó có kết quả nhanh hơn.

Ngoài ra để tăng tốc hoạt động tìm nạp danh bạ, bạn có thể sử dụng ContentProvideClient thay vì gọi truy vấn trên ContentResolver mỗi lần. Điều này sẽ làm cho bạn truy vấn bảng cụ thể hơn là truy vấn đầu tiên cho ContentProvider được yêu cầu và sau đó đến bảng.

Tạo một thể hiện của ContentProviderClient

ContentResolver cResolver=context.getContextResolver(); 
ContentProviderClient mCProviderClient = cResolver.acquireContentProviderClient(ContactsContract.Contacts.CONTENT_URI); 

Sau đó tái sử dụng mCProviderClient này để có được hệ (dữ liệu từ bất kỳ ContentProvider) dữ liệu theo yêu cầu của bạn. Ví dụ trong phương pháp sau, tôi chỉ truy cập một trường.

private ArrayList<String> fetchContactsCProviderClient() 
    { 
     ArrayList<String> mContactList = null; 
     try 
     { 
      Cursor mCursor = mCProviderClient.query(ContactsContract.Contacts.CONTENT_URI, null, null, null, null); 
      if (mCursor != null && mCursor.getCount() > 0) 
      { 
       mContactList = new ArrayList<String>(); 
       mCursor.moveToFirst(); 
       while (!mCursor.isLast()) 
       { 
        String displayName = mCursor.getString(mCursor.getColumnIndexOrThrow(ContactsContract.Contacts.DISPLAY_NAME)); 
        mContactList.add(displayName); 
        mCursor.moveToNext(); 
       } 
       if (mCursor.isLast()) 
       { 
        String displayName = mCursor.getString(mCursor.getColumnIndexOrThrow(ContactsContract.Contacts.DISPLAY_NAME)); 
        mContactList.add(displayName); 
       } 
      } 

      mCursor.close(); 
     } 
     catch (RemoteException e) 
     { 
      e.printStackTrace(); 
      mContactList = null; 
     } 
     catch (Exception e) 
     { 
      e.printStackTrace(); 
      mContactList = null; 
     } 

     return mContactList; 
    } 
8

GIẢI PHÁP TỐT HƠN TẠI ĐÂY .....

private static final String[] PROJECTION = new String[] { 
     ContactsContract.CommonDataKinds.Phone.CONTACT_ID, 
     ContactsContract.Contacts.DISPLAY_NAME, 
     ContactsContract.CommonDataKinds.Phone.NUMBER 
    }; 
. 
. 
. 

ContentResolver cr = getContentResolver(); 
     Cursor cursor = cr.query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, PROJECTION, null, null, null); 
     if (cursor != null) { 
      try { 
       final int nameIndex = cursor.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME); 
       final int numberIndex = cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER); 

       String name, number; 
       while (cursor.moveToNext()) { 
        name = cursor.getString(nameIndex); 
        number = cursor.getString(numberIndex); 
       } 
      } finally { 
       cursor.close(); 
      } 
     } 

CHÚC MỪNG ... :)

+1

đây là một giải pháp thông minh, nhưng những gì nếu liên hệ có nhiều số điện thoại? –

+0

@Melbourne Lopes- bạn chỉ đọc số điện thoại, làm thế nào tôi có thể đọc id email cùng với điều đó. –

+0

Tại sao đây là giải pháp tốt hơn? – Relm

3

Đối tải các điểm tiếp xúc với thời gian mininum giải pháp tối ưu là sử dụng các khái niệm về dự báo và đối số lựa chọn trong khi truy vấn con trỏ cho các liên hệ.

này có thể được thực hiện trong sau cách

void getAllContacts() { 
    long startnow; 
    long endnow; 

    startnow = android.os.SystemClock.uptimeMillis(); 
    ArrayList arrContacts = new ArrayList(); 

    Uri uri = ContactsContract.CommonDataKinds.Phone.CONTENT_URI; 
    String selection = ContactsContract.Contacts.HAS_PHONE_NUMBER; 
    Cursor cursor = ctx.getContentResolver().query(uri, new String[]{ContactsContract.CommonDataKinds.Phone.NUMBER, ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME, ContactsContract.CommonDataKinds.Phone._ID, ContactsContract.Contacts._ID}, selection, null, ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME + " ASC"); 

    cursor.moveToFirst(); 
    while (cursor.isAfterLast() == false) { 

     String contactNumber = cursor.getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER)); 
     String contactName = cursor.getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME)); 
     int phoneContactID = cursor.getInt(cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone._ID)); 
     int contactID = cursor.getInt(cursor.getColumnIndex(ContactsContract.Contacts._ID)); 
     Log.d("con ", "name " + contactName + " " + " PhoeContactID " + phoneContactID + " ContactID " + contactID) 

     cursor.moveToNext(); 
    } 
    cursor.close(); 
    cursor = null; 

    endnow = android.os.SystemClock.uptimeMillis(); 
    Log.d("END", "TimeForContacts " + (endnow - startnow) + " ms"); 
} 

Với phương pháp trên phải mất 400ms (nhỏ hơn giây) để tải danh bạ nơi như trong cách normall nó đã được dùng 10-12 giây.

Để biết chi tiết Trao bài này có thể giúp như tôi mất sự giúp đỡ từ nó http://www.blazin.in/2016/02/loading-contacts-fast-from-android.html

+0

Nên thực sự là câu trả lời được chấp nhận. Wayyyyy hiệu quả hơn –

0

Tôi nghĩ rằng đây là một giải pháp tốt hơn:

public ContentValues getAllContacts() { 
    ContentValues contacts = new ContentValues(); 
    ContentResolver cr = getContentResolver(); 
    Cursor cur = cr.query(ContactsContract.Contacts.CONTENT_URI, null, null, null, null); 

    if (cur != null && cur.getCount() > 0) { 
     while (cur.moveToNext()) { 
      String id = cur.getString(cur.getColumnIndex(ContactsContract.Contacts._ID)); 
      String name = cur.getString(cur.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME)); 

      if (cur.getInt(cur.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER)) > 0) { 
       Cursor pCur = cr.query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null, 
         ContactsContract.CommonDataKinds.Phone.CONTACT_ID + " = ?", new String[]{id}, null); 
       if (pCur != null) { 
        while (pCur.moveToNext()) { 
         String phoneNo = pCur.getString(pCur.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER)); 
         contacts.put(phoneNo, name); 
        } 
        pCur.close(); 
       } 
      } 
     } 
     cur.close(); 
    } 
    return contacts; 
} 

để sử dụng nó, bạn cần phải gọi dòng này lần :

ContentValues contacts = new ContentValues(); 
contacts = getAllContacts(); 

và khi bạn muốn nhận được tên liên hệ theo số, chỉ cần sử dụng:

String number = "12345"; 
String name = (String) G.contacts.get(number); 

thuật toán này là một chút nhanh hơn ...

2

tải nhanh hơn như app.I khác Liên đã thử nghiệm mã này nó làm việc tốt hơn và nhanh hơn như các ứng dụng khác trong vòng 500 ms (trong vòng nửa giây) Tôi có thể tải hơn 1000 địa chỉ liên hệ.

Tổng thời gian sẽ tùy thuộc vào trường nào bạn đang cố gắng truy cập từ bảng Danh bạ Mange truy vấn của bạn theo yêu cầu của bạn không truy cập vào các trường không mong muốn. Truy cập trường ít hơn có nghĩa là ít lặp, xử lý ít hơn và do đó kết quả nhanh hơn.

Truy cập bảng bên phải khi liên hệ với nó cũng giúp giảm thời gian tải liên hệ.

Query Tối ưu hóa để tải tiếp xúc nhiều hơn nhanh hơn sử dụng projection

String[] projection = { 
      ContactsContract.Data.MIMETYPE, 
      ContactsContract.Data.CONTACT_ID, 
      ContactsContract.Contacts.DISPLAY_NAME, 
      ContactsContract.Contacts.PHOTO_URI, 
      ContactsContract.Contacts.STARRED, 
      ContactsContract.RawContacts.ACCOUNT_TYPE, 
      ContactsContract.CommonDataKinds.Contactables.DATA, 
      ContactsContract.CommonDataKinds.Contactables.TYPE 
    }; 

Lựa chọn và lựa chọn tham số

String selection = ContactsContract.Data.MIMETYPE + " in (?, ?)" + " AND " /*+ ContactsContract.Contacts.IN_VISIBLE_GROUP + " = '" + 1 + "' AND "*/ + 
      ContactsContract.Data.HAS_PHONE_NUMBER + " = '" + 1 + "'"; 

    String[] selectionArgs = { 
      ContactsContract.CommonDataKinds.Email.CONTENT_ITEM_TYPE, 
      ContactsContract.CommonDataKinds.Phone.CONTENT_ITEM_TYPE, 
    }; 

Để đặt danh bạ theo thứ tự abc sử dụng đoạn mã sau

try { 
     Collections.sort(listview_address, new Comparator<ContactBook>() { 
      @Override 
      public int compare(ContactBook lhs, ContactBook rhs) { 
       return lhs.name.toUpperCase().compareTo(rhs.name.toUpperCase()); 
      } 
     }); 
    } catch (Exception e) { 
     e.printStackTrace(); 
    } 

Sau đây là toàn bộ mã nguồn

public void initeContacts() { 
    List<ContactBook> listview_address = new LinkedList<ContactBook>(); 
    SparseArray<ContactBook> addressbook_array = null; 
    { 
     addressbook_array = new SparseArray<ContactBook>(); 

     long start = System.currentTimeMillis(); 

     String[] projection = { 
       ContactsContract.Data.MIMETYPE, 
       ContactsContract.Data.CONTACT_ID, 
       ContactsContract.Contacts.DISPLAY_NAME, 
       ContactsContract.Contacts.PHOTO_URI, 
       ContactsContract.Contacts.STARRED, 
       ContactsContract.RawContacts.ACCOUNT_TYPE, 
       ContactsContract.CommonDataKinds.Contactables.DATA, 
       ContactsContract.CommonDataKinds.Contactables.TYPE 
     }; 

     String selection = ContactsContract.Data.MIMETYPE + " in (?, ?)" + " AND " /*+ ContactsContract.Contacts.IN_VISIBLE_GROUP + " = '" + 1 + "' AND "*/ + 
       ContactsContract.Data.HAS_PHONE_NUMBER + " = '" + 1 + "'"; 

     String[] selectionArgs = { 
       ContactsContract.CommonDataKinds.Email.CONTENT_ITEM_TYPE, 
       ContactsContract.CommonDataKinds.Phone.CONTENT_ITEM_TYPE, 
     }; 

     String sortOrder = ContactsContract.Contacts.SORT_KEY_ALTERNATIVE; 

     Uri uri = null; 
     if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.JELLY_BEAN_MR2) { 
      uri = ContactsContract.CommonDataKinds.Contactables.CONTENT_URI; 
     } else { 
      uri = ContactsContract.Data.CONTENT_URI; 

     } 
     // we could also use Uri uri = ContactsContract.Data.CONTENT_URI; 
     // we could also use Uri uri = ContactsContract.Contact.CONTENT_URI; 

     Cursor cursor = getActivity().getContentResolver().query(uri, projection, selection, selectionArgs, sortOrder); 


     final int mimeTypeIdx = cursor.getColumnIndex(ContactsContract.Data.MIMETYPE); 
     final int idIdx = cursor.getColumnIndex(ContactsContract.Data.CONTACT_ID); 
     final int nameIdx = cursor.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME); 
     final int dataIdx = cursor.getColumnIndex(ContactsContract.CommonDataKinds.Contactables.DATA); 
     final int photo = cursor.getColumnIndex(ContactsContract.CommonDataKinds.Contactables.PHOTO_URI); 
     final int typeIdx = cursor.getColumnIndex(ContactsContract.CommonDataKinds.Contactables.TYPE); 
     final int account_type = cursor.getColumnIndex(ContactsContract.RawContacts.ACCOUNT_TYPE); 
     while (cursor.moveToNext()) { 
      int contact_id = cursor.getInt(idIdx); 
      String photo_uri = cursor.getString(photo); 
      String contact_name = cursor.getString(nameIdx); 
      String contact_acc_type = cursor.getString(account_type); 
      int contact_type = cursor.getInt(typeIdx); 
      String contact_data = cursor.getString(dataIdx); 
      ContactBook contactBook = addressbook_array.get(contact_id); 

      /* if (contactBook == null) { 
       //list contact add to avoid duplication 
       //load All contacts fro device 
       //to add contacts number with name add one extra veriable in ContactBook as number and pass contact_data this give number to you (contact_data is PHONE NUMBER) 
       contactBook = new ContactBook(contact_id, contact_name, getResources(), photo_uri, contact_acc_type, "phone number"); 
       addressbook_array.put(contact_id, contactBook); 
       listview_address.add(contactBook); 

      }*/ 

      String Contact_mimeType = cursor.getString(mimeTypeIdx); 
      //here am checking Contact_mimeType to get mobile number asociated with perticular contact and email adderess asociated 
      if (Contact_mimeType.equals(ContactsContract.CommonDataKinds.Email.CONTENT_ITEM_TYPE)) { 

       if (contactBook != null) { 
        contactBook.addEmail(contact_type, contact_data); 
       } 

      } else { 
       if (contactBook == null) { 
        //list contact add to avoid duplication 
        //load All contacts fro device 
        //to add contacts number with name add one extra veriable in ContactBook as number and pass contact_data this give number to you (contact_data is PHONE NUMBER) 
        contactBook = new ContactBook(contact_id, contact_name, getResources(), photo_uri, contact_acc_type, "phone number"); 
        addressbook_array.put(contact_id, contactBook); 
        listview_address.add(contactBook); 

       } 
       // contactBook.addPhone(contact_type, contact_data); 


      } 


     } 

     cursor.close(); 


     try { 
      Collections.sort(listview_address, new Comparator<ContactBook>() { 
       @Override 
       public int compare(ContactBook lhs, ContactBook rhs) { 
        return lhs.name.toUpperCase().compareTo(rhs.name.toUpperCase()); 
       } 
      }); 
     } catch (Exception e) { 
      e.printStackTrace(); 
     } 

    } 

Bạn có thể sử dụng mã sau trong mã ở trên mà tôi đã nhận xét .Đó là câu lạc bộ liên hệ duy nhất với nhiều số của nó.Để nhận được tất cả các số liên quan đến mảng sử dụng liên hệ duy nhất trong lớp Đối tượng.

if (contactBook == null) { 
      //irst contact add to avoid duplication 
      //load All contacts fro device 
      contactBook = new ContactBook(contact_id, contact_name, getResources(), photo_uri, contact_acc_type, ""); 
      addressbook_array.put(contact_id, contactBook); 
      listview_address.add(contactBook); 
     } 

     String Contact_mimeType = cursor.getString(mimeTypeIdx); 
     //here am checking Contact_mimeType to get mobile number asociated with perticular contact and email adderess asociated 
     if (Contact_mimeType.equals(ContactsContract.CommonDataKinds.Email.CONTENT_ITEM_TYPE)) { 

      contactBook.addEmail(contact_type, contact_data); 

     } else { 

      contactBook.addPhone(contact_type, contact_data); 

     } 

lớp Object

public class ContactBook { 
public int id; 
public Resources res; 
public String name; 
public String photo; 
public String contact_acc_type; 
public SparseArray<String> emails; 
public SparseArray<String> phones; 
/* public LongSparseArray<String> emails; 
public LongSparseArray<String> phones;*/ 
public String header = ""; 


public ContactBook(int id, String name, Resources res, String photo, String contact_acc_type, String header) { 
    this.id = id; 
    this.name = name; 
    this.res = res; 
    this.photo = photo; 
    this.contact_acc_type = contact_acc_type; 
    this.header = header; 
} 

@Override 
public String toString() { 
    return toString(false); 
} 

public String toString(boolean rich) { 

    //testing method to check ddata 
    SpannableStringBuilder builder = new SpannableStringBuilder(); 
    if (rich) { 
     builder.append("id: ").append(Long.toString(id)) 
       .append(", name: ").append("\u001b[1m").append(name).append("\u001b[0m"); 
    } else { 
     builder.append(name); 
    } 

    if (phones != null) { 
     builder.append("\n\tphones: "); 
     for (int i = 0; i < phones.size(); i++) { 
      int type = (int) phones.keyAt(i); 
      builder.append(ContactsContract.CommonDataKinds.Phone.getTypeLabel(res, type, "")) 
        .append(": ") 
        .append(phones.valueAt(i)); 
      if (i + 1 < phones.size()) { 
       builder.append(", "); 
      } 
     } 
    } 

    if (emails != null) { 
     builder.append("\n\temails: "); 
     for (int i = 0; i < emails.size(); i++) { 
      int type = (int) emails.keyAt(i); 
      builder.append(ContactsContract.CommonDataKinds.Email.getTypeLabel(res, type, "")) 
        .append(": ") 
        .append(emails.valueAt(i)); 
      if (i + 1 < emails.size()) { 
       builder.append(", "); 
      } 
     } 
    } 
    return builder.toString(); 
} 

public void addEmail(int type, String address) { 
    //this is the array in object class where i am storing contact all emails of perticular contact (single) 
    if (emails == null) { 
     // if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) { 
     emails = new SparseArray<String>(); 
     emails.put(type, address); 
     /*} else { 
      //add emails to array below Jelly bean //use single array list 
     }*/ 
    } 
} 

public void addPhone(int type, String number) { 
    //this is the array in object class where i am storing contact numbers of perticular contact 
    if (phones == null) { 
     // if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) { 
     phones = new SparseArray<String>(); 
     phones.put(type, number); 
     /* } else { 
      //add emails to array below Jelly bean //use single array list 
     }*/ 
    } 
}} 
Các vấn đề liên quan