Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲
 Android教程網 >> Android技術 >> 關於Android編程 >> android實現讀取、搜索聯系人的代碼

android實現讀取、搜索聯系人的代碼

編輯:關於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();
        }
    }

以上就是本文給大家分享的代碼的全部內容了,希望大家能夠喜歡。

  1. 上一頁:
  2. 下一頁:
熱門文章
閱讀排行版
Copyright © Android教程網 All Rights Reserved