Android联系人4--联系人查询



在第二篇博客中 http://blog.csdn.net/cmdkmd/article/details/8731217

按照那种方式查询,虽说效率高了些,但是在有些机型上,并不能按照系统联系人那样显示,没有办法只能采用官方的给出的办法

1 我的做法是预读取,在应用启动的时候就将读取联系人数据,然后放到application中,这样在内存中读取的非常快

2 遍历中嵌套遍历,频繁开关cursor,导致很慢,求大能指点


package com.xzq.contacttest;

import java.util.ArrayList;

import android.app.ListActivity;
import android.content.AsyncQueryHandler;
import android.content.ContentResolver;
import android.database.Cursor;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.provider.ContactsContract.CommonDataKinds.Phone;
import android.view.Window;
import android.widget.ListView;

public class MainAty extends ListActivity {

    private ListView listView;
    private ContactAdapter contactAdapter;
    private AsyncQueryHandler asyncQuery;// 异步查询框架

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        setContentView(R.layout.main);
        listView = getListView();

        asyncQuery = new MyAsyncQueryHandler(getContentResolver());
        String[] projection = { ContactsContract.Contacts._ID, ContactsContract.Contacts.DISPLAY_NAME, };
        asyncQuery.startQuery(0, null, ContactsContract.Contacts.CONTENT_URI, projection, null, null, null);
    }

    private class MyAsyncQueryHandler extends AsyncQueryHandler {

        public MyAsyncQueryHandler(ContentResolver cr) {
            super(cr);
        }

        @Override
        protected void onQueryComplete(int token, Object cookie, Cursor cursor) {
            switch (token) {
            case 0:// 查询联系人
                if (cursor != null && cursor.getCount() > 0) {
                    ArrayList<Contact> list = new ArrayList<Contact>();
                    while (cursor.moveToNext()) {
                        Contact cb = new Contact();
                        cb.contactId = cursor.getString(0);
                        cb.name = cursor.getString(1);// 联系人姓名
                        String[] projection = { Phone.DATA1 }; // 查询的列
                        Cursor phones = getContentResolver().query(Phone.CONTENT_URI, projection,
                                Phone.CONTACT_ID + " = " + cb.contactId, null, null);
                        while (phones.moveToNext()) {
                            cb.number = phones.getString(0);
                            cb.listNumber.add(cb.number);
                        }
                        phones.close();
                        list.add(cb);
                    }
                    contactAdapter = new ContactAdapter(MainAty.this, list);
                    listView.setAdapter(contactAdapter);
                }
                break;
            }
            cursor.close();
        }
    }
}

源码 : http://download.csdn.net/detail/cmdkmd/5219513


你可能感兴趣的:(android,性能,android,联系人)