android Contacts 联系人分析


前言: 转

Android Contact分析(一):Data, RawContact, Contact之间的关系


http://blog.csdn.net/qingye_love/article/details/9028503


常见的搜索方法:

	/**
	 * 查询所有联系人姓名及电话号码
	 */
	private void readContacts() {
		StringBuilder sb = new StringBuilder();
		ContentResolver cr = getContentResolver();

		// select * from contacts
		Cursor cursor = cr.query(ContactsContract.Contacts.CONTENT_URI, null,
				null, null, null);
		while (cursor.moveToNext()) {
			String id = cursor.getString(cursor
					.getColumnIndex(ContactsContract.Contacts._ID));
			String name = cursor.getString(cursor
					.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
			int iHasPhoneNum = Integer
					.parseInt(cursor.getString(cursor
							.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER)));
			sb.append(name + " (");

			if (iHasPhoneNum > 0) {
				Cursor numCursor = cr.query(
						ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
						null, ContactsContract.CommonDataKinds.Phone.CONTACT_ID
								+ "=" + id, null, null);
				while (numCursor.moveToNext()) {
					String number = numCursor
							.getString(numCursor
									.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
					sb.append(number + ")");
				}
				numCursor.close();
			}
			sb.append("\r\n");
		}
		cursor.close();

		if (!TextUtils.isEmpty(sb.toString())) {
			Log.d(TAG, "所有联系人:\r\n" + sb.toString());
		}
	}

	/**
	 * 根据名字中的某一个字进行模糊查询
	 * 
	 * @param key
	 */
	private void getFuzzyQueryByName(String key) {

		StringBuilder sb = new StringBuilder();
		ContentResolver cr = getContentResolver();
		String[] projection = { ContactsContract.PhoneLookup.DISPLAY_NAME,
				ContactsContract.CommonDataKinds.Phone.NUMBER };
		Cursor cursor = cr.query(
				ContactsContract.CommonDataKinds.Phone.CONTENT_URI, projection,
				ContactsContract.Contacts.DISPLAY_NAME + " like " + "'%" + key
						+ "%'", null, null);
		while (cursor.moveToNext()) {
			String name = cursor.getString(cursor
					.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
			String number = cursor
					.getString(cursor
							.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
			sb.append(name + " (").append(number + ")").append("\r\n");
		}
		cursor.close();

		if (!TextUtils.isEmpty(sb.toString())) {
			Log.d(TAG, "根据名字查联系人:\r\n" + sb.toString());
		}
	}

	/**
	 * 根据电话号码进行模糊查询
	 * 
	 * @param key
	 */
	public void getPeople(String key) {
		String[] projection = { ContactsContract.PhoneLookup.DISPLAY_NAME,
				ContactsContract.CommonDataKinds.Phone.NUMBER };

		Log.d(TAG, "getPeople ---------");

		// 将自己添加到 msPeers 中
		Cursor cursor = this.getContentResolver().query(
				ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
				projection, // Which columns to return.
				ContactsContract.CommonDataKinds.Phone.NUMBER + " like " + "'%"
						+ key + "%'", // WHERE clause.
				null, // WHERE clause value substitution
				null); // Sort order.

		if (cursor == null) {
			Log.d(TAG, "getPeople null");
			return;
			// return;
		}
		Log.d(TAG, "getPeople cursor.getCount() = " + cursor.getCount());
		for (int i = 0; i < cursor.getCount(); i++) {
			cursor.moveToPosition(i);
			
			String name = cursor.getString(cursor
					.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
			String number = cursor
					.getString(cursor
							.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
			Log.i(TAG, "根据号码查联系人 name: " + name + "----" + "  number:" + number + " \n"); // 这里提示
			
		}
	}

    /**
     * 通过汉字返回拼音, 可用于排序
     * 
     * @param name
     */
private void getPinyinByHanzi(String name) {
        ContentValues values = new ContentValues();
        ContentResolver cr = getContentResolver();

        Uri rawContactUri = cr.insert(ContactsContract.RawContacts.CONTENT_URI,
                values);
        long rawContactId = ContentUris.parseId(rawContactUri);

        if (name.length() > 0) {
            values.clear();
            values.put(Data.RAW_CONTACT_ID, rawContactId);
            values.put(
                    Data.MIMETYPE,
                    ContactsContract.CommonDataKinds.StructuredName.CONTENT_ITEM_TYPE);
            values.put(
                    ContactsContract.CommonDataKinds.StructuredName.GIVEN_NAME,
                    name);
            cr.insert(ContactsContract.Data.CONTENT_URI, values);

            String[] projection = { "sort_key" };
            String where = ContactsContract.RawContacts.CONTACT_ID + "="
                    + rawContactId;
            Cursor cursor = cr.query(ContactsContract.RawContacts.CONTENT_URI,
                    projection, where, null, null);
            if (cursor != null) {
                cursor.moveToFirst();
                String pinyin = cursor.getString(cursor
                        .getColumnIndex("sort_key"));
                Log.d(TAG, pinyin);

                String res = "";
                for (int i = 0; i < pinyin.length(); i++) {
                    String temp = pinyin.substring(i, i + 1);
                    if (temp.matches("[a-zA-Z ]")) {
                        res += temp;
                    }
                }
                res = res.substring(0, res.length() - 1);
                Log.d(TAG,
                        name + " translate = \""
                                + res.toLowerCase(Locale.getDefault()) + "\"");
            }
        }

        cr.delete(ContentUris.withAppendedId(
                ContactsContract.RawContacts.CONTENT_URI, rawContactId), null,
                null);
    }

调用方式:

        readContacts();
        getFuzzyQueryByName("av");
        getPeople("138");




------------------------------------------------------------------------------------------------------------------------------------

以下方法可以称是万能查询,  如联系人有“张三”,“张4”,“郑源”,“zhong wei”,  

输入“张”, 可以查询出 {“张三”, “张4”}

输入“z”, 可以查询出{“张三”,“张4”,“郑源”,“zhong wei”}

输入"zy" , 可以查询出{"郑源"}

输入电话号码, 也可以正确查出结果。

		
Cursor cursor = searchContact(this, "zy");
		while(cursor.moveToNext()){
		
			Log.i(TAG, "name: " + cursor.getString(0));
			Log.i(TAG, "NUMBER: " + cursor.getString(1));
			Log.i(TAG, "TYPE: " + cursor.getString(2));
			Log.i(TAG, "LABEL: " + cursor.getString(3));
			Log.i(TAG, "CONTACT_ID: " + cursor.getString(4));
			Log.i(TAG, "_ID: " + cursor.getString(5));
			Log.i(TAG, "PHOTO_THUMBNAIL_URI: " + cursor.getString(6));
			Log.i(TAG, "DISPLAY_NAME_SOURCE: " + cursor.getString(7));
			Log.i(TAG, "-------------------------------");
		}
		
		cursor.close();
		
	}
	
	public Cursor searchContact(Context ctxt, CharSequence constraint) {
		Uri uri = Uri.withAppendedPath(ContactsContract.CommonDataKinds.Phone.CONTENT_FILTER_URI, Uri.encode(constraint.toString()));
		return ctxt.getContentResolver().query(uri,
				projection,
		  null, //selection,
		  null,
		  null);
		}
	
    String[] projection = new String[] {
            Contacts.DISPLAY_NAME,       // 0
            Phone.NUMBER,                // 1
            Phone.TYPE,                  // 2
            Phone.LABEL,                 // 3
            Phone.CONTACT_ID,            // 4
            Phone._ID,                   // 5
            Contacts.PHOTO_THUMBNAIL_URI,// 6
            Contacts.DISPLAY_NAME_SOURCE // 7
        };


评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值