android通讯录浅谈

 关于Android通讯录,因为各个android版本的不同,大大小小的坑实在太多了。。。

有误代码如下:

if (android.os.Build.VERSION.SDK_INT >= 19) {
            PHONES_PROJECTION

[PHONES_SORT_KEY_ALTERNATIVE] = "phonebook_label";
        }
		
		

Cursor cur = context.getContentResolver().query(Phone.CONTENT_URI, PHONES_PROJECTION, 

null, null, null);  
		
	
		
       
		if(cur!=null)
		

{
	
			while(cur.moveToNext())
			{
			

	String number = cur.getString(PHONES_NUMBER_INDEX);
				

if (TextUtils.isEmpty(number))  
			        continue;
			

	
				String contactName = cur.getString

(cur.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
				

String sortKey = cur.getString(PHONES_SORT_KEY_ALTERNATIVE);
				

addContact(Contact,contactName,"Mobile","Today","0",number,sortKey.trim

().charAt(0)+"");
}
联系人姓名,如果有#¥@%……&*之类的符号,那就Crash....不加后面的 sortKey.trim().charAt(); 方法的话,确实没问题,一般情况,要进行对通讯录的排序。这个很有必要! 

这种方式,还是有点问题,比如,个别手机遍历出来的只有中文。那就还要中转英再进行排序了。

代码如下,但是,遇到上面我所说的,并没有进行中英文处理。。。排序要判断得到的sortKey是否有英文开头。中英转换。

private String getSortKeyString(long rawContactId) {
		String Where = ContactsContract.RawContacts.CONTACT_ID + " ="
				+ rawContactId;
		String[] projection = { "sort_key" };
		Cursor cur = context.getContentResolver().query(
				ContactsContract.RawContacts.CONTENT_URI, projection, Where,
				null, null);
		int sortIndex = cur.getColumnIndex("sort_key");
		cur.moveToFirst();
		String sortValue = cur.getString(sortIndex);
		cur.close();
		return sortValue;
	}

	if (android.os.Build.VERSION.SDK_INT >= 19) {
            PHONES_PROJECTION[PHONES_SORT_KEY_ALTERNATIVE] = "phonebook_label";
        }
		
		Cursor cur = context.getContentResolver().query(Phone.CONTENT_URI, PHONES_PROJECTION, null, null, null);

       
		if(cur!=null)
		{	
			while(cur.moveToNext())
			{
				int phoneNumberIndex = cur.getColumnIndex(Phone.NUMBER);
				String number = cur.getString(phoneNumberIndex);
				if (TextUtils.isEmpty(number))
					continue;
				int contactNameIndex = cur
						.getColumnIndex(Phone.DISPLAY_NAME);
				String contactName = cur.getString(contactNameIndex);
				int rawContactIdIndex = cur
						.getColumnIndex(Phone.CONTACT_ID);
				Long rawContactId = cur.getLong(rawContactIdIndex);
				String sortKey = getSortKeyString(rawContactId);
				Log.e("sortKey",""+sortKey);
				addContact(Contact,contactName,"Mobile","Today","0",number,sortKey.trim().charAt(0)+"");
			}

		}

就写这么多了    欢迎各种补充,或者有更好方式的  可以留言给我

马上不知不觉一年马上就要过去了。。。20161125

猜你喜欢

转载自blog.csdn.net/mapeifan/article/details/53333795