服务器之家

服务器之家 > 正文

android实现读取、搜索联系人的代码

时间:2021-03-14 16:33     来源/作者:Android开发网

代码很简单,就不多废话了

 

复制代码 代码如下:

//读取联系人
public static Uri CONTACTSURI = ContactsContract.Contacts.CONTENT_URI;//联系人
    public static void getContactsInfo(Context context,String tag){
        String[] projections = new String[]{ContactsContract.Contacts._ID,ContactsContract.Contacts.DISPLAY_NAME};
        Cursor cursor = context.getContentResolver().query(CONTACTSURI, projections, null, null, null);
        int albumIndex = cursor.getColumnIndexOrThrow(projections[0]);
        int titleIndex = cursor.getColumnIndexOrThrow(projections[1]);
        Log.d(tag, cursor.getCount()+"");
        while(cursor.moveToNext()){
            String album = cursor.getString(albumIndex);
            String title = cursor.getString(titleIndex);
            Log.d(tag, album+":"+title);
        }
        cursor.close();
    }
    
    //根据联系人搜索联系人信息
    public static void searchContacts(Context context,String tag){
        String searchName = "Wang";
        Uri uri = Uri.withAppendedPath(ContactsContract.Contacts.CONTENT_FILTER_URI, searchName);
        
    //  Uri uri2 = Uri.withAppendedPath(ContactsContract.PhoneLookup.CONTENT_FILTER_URI, phoneNumber); 根据电话号码查找联系人
        
        String[] projection = new String[]{ContactsContract.Contacts._ID};
        Cursor cursor = context.getContentResolver().query(uri, projection, null, null, null);
        String id = null;
        if (cursor.moveToFirst()) {
            id = cursor.getString(cursor.getColumnIndexOrThrow(ContactsContract.Contacts._ID));
        }
        cursor.close();
        if (id!=null) {
            String where = ContactsContract.Data._ID+"="+id;
            projection = new String[]{ContactsContract.Data.DISPLAY_NAME,ContactsContract.CommonDataKinds.Phone.NUMBER};
            Cursor searchcCursor = context.getContentResolver().query(ContactsContract.Data.CONTENT_URI, projection, where, null, null);
            Log.d(tag, searchcCursor.getCount()+"");
            int nameIndex = searchcCursor.getColumnIndex(projection[0]);
            int numberIndex = searchcCursor.getColumnIndex(projection[1]);
            while(searchcCursor.moveToNext()){
                String name = searchcCursor.getString(nameIndex);
                String number = searchcCursor.getString(numberIndex);
                Log.d(tag, number+":"+name);
            }
            searchcCursor.close();
        }
    }

 

以上就是本文给大家分享的代码的全部内容了,希望大家能够喜欢。

标签:

相关文章

热门资讯

2020微信伤感网名听哭了 让对方看到心疼的伤感网名大全
2020微信伤感网名听哭了 让对方看到心疼的伤感网名大全 2019-12-26
yue是什么意思 网络流行语yue了是什么梗
yue是什么意思 网络流行语yue了是什么梗 2020-10-11
背刺什么意思 网络词语背刺是什么梗
背刺什么意思 网络词语背刺是什么梗 2020-05-22
Intellij idea2020永久破解,亲测可用!!!
Intellij idea2020永久破解,亲测可用!!! 2020-07-29
苹果12mini价格表官网报价 iPhone12mini全版本价格汇总
苹果12mini价格表官网报价 iPhone12mini全版本价格汇总 2020-11-13
返回顶部