Android中联系人以及ContactsContract类

1.加入读写权限

(1).  <uses-permissionandroid:name="android.permission.READ_CONTACTS" />

(2).  <uses-permissionandroid:name="android.permission.WRITE_CONTACTS" />

联系人信息Uri

content://com.android.contacts/contacts

联系人电话Uri

content://com.android.contacts/data/phones

联系人Email Uri

content://com.android.contacts/data/emails

(推荐)也可以这样获取联系人信息Uri:Uri uri = ContactsContract.Contacts.CONTENT_URI;

 

2.查询与添加联系人的操作(单元测试用例)

1.  public class ContactTest extends AndroidTestCase

2.  {

3.  private static final String TAG = "ContactTest";

4.  public void testGetAllContact() throws Throwable

5.  {

6.  //获取联系人信息的Uri

7.  Uri uri = ContactsContract.Contacts.CONTENT_URI;

8.  //获取ContentResolver

9.  ContentResolver contentResolver = this.getContext().getContentResolver();

10.   //查询数据,返回Cursor

11.   Cursor cursor = contentResolver.query(uri, null, null, null, null);

12.   while(cursor.moveToNext())

13.   {

14.   StringBuilder sb = new StringBuilder();

15.   //获取联系人的ID

16.   String contactId =cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts._ID));

17.   //获取联系人的姓名

18.   String name =cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));

19.   //构造联系人信息

20.   sb.append("contactId=").append(contactId).append(",Name=").append(name);

21.   //查询电话类型的数据操作

22.   Cursor phones =contentResolver.query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI,

23.   null,

24.   ContactsContract.CommonDataKinds.Phone.CONTACT_ID +" = "+ contactId,

25.   null, null);

26.   while(phones.moveToNext())

27.   {

28.   String phoneNumber = phones.getString(phones.getColumnIndex(

29.   ContactsContract.CommonDataKinds.Phone.NUMBER));

30.   //添加Phone的信息

31.   sb.append(",Phone=").append(phoneNumber);

32.    

33.   }

34.   phones.close();

35.   //查询Email类型的数据操作

36.   Cursor emails =contentResolver.query(ContactsContract.CommonDataKinds.Email.CONTENT_URI,

37.   null,

38.   ContactsContract.CommonDataKinds.Email.CONTACT_ID + " = " +contactId,

39.   null, null);

40.   while (emails.moveToNext())

41.   {

42.   String emailAddress = emails.getString(emails.getColumnIndex(

43.   ContactsContract.CommonDataKinds.Email.DATA));

44.   //添加Email的信息

45.   sb.append(",Email=").append(emailAddress);

46.   }

47.   emails.close();

48.   Log.i(TAG, sb.toString());

49.   }

50.   cursor.close();

51.   }

52.   public void testInsert()

53.   {

54.   ContentValues values = new ContentValues();

55.   //首先向RawContacts.CONTENT_URI执行一个空值插入,目的是获取系统返回的rawContactId

56.   Uri rawContactUri =this.getContext().getContentResolver().insert(RawContacts.CONTENT_URI, values);

57.   //获取id

58.   long rawContactId = ContentUris.parseId(rawContactUri);

59.   //data表入姓名数据

60.   values.clear();

61.   values.put(Data.RAW_CONTACT_ID, rawContactId); //添加id

62.   values.put(Data.MIMETYPE, StructuredName.CONTENT_ITEM_TYPE);//添加内容类型(MIMETYPE

63.   values.put(StructuredName.GIVEN_NAME, "凯风自南");//添加名字,添加到first name位置

64.   this.getContext().getContentResolver().insert(android.provider.ContactsContract.Data.CONTENT_URI,values);

65.   //data表入电话数据

66.   values.clear();

67.   values.put(Data.RAW_CONTACT_ID, rawContactId);

68.   values.put(Data.MIMETYPE, Phone.CONTENT_ITEM_TYPE);

69.   values.put(Phone.NUMBER, "13921009789");

70.   values.put(Phone.TYPE, Phone.TYPE_MOBILE);

71.   this.getContext().getContentResolver().insert(android.provider.ContactsContract.Data.CONTENT_URI,values);

72.   //data表入Email数据

73.   values.clear();

74.   values.put(Data.RAW_CONTACT_ID, rawContactId);

75.   values.put(Data.MIMETYPE, Email.CONTENT_ITEM_TYPE);

76.   values.put(Email.DATA, "kesenhoo@gmail.com");

77.   values.put(Email.TYPE, Email.TYPE_WORK);

78.   this.getContext().getContentResolver().insert(android.provider.ContactsContract.Data.CONTENT_URI,values);

79.   }

80.   public void testSave() throws Throwable

81.   {

82.   //官方文档位置:http://developer.android.com/reference/android/provider/ContactsContract.RawContacts.html

83.   //建立一个ArrayList存放批量的参数

84.   ArrayList<ContentProviderOperation> ops = newArrayList<ContentProviderOperation>();

85.   int rawContactInsertIndex = ops.size();

86.   ops.add(ContentProviderOperation.newInsert(RawContacts.CONTENT_URI)

87.   .withValue(RawContacts.ACCOUNT_TYPE, null)

88.   .withValue(RawContacts.ACCOUNT_NAME, null)

89.   .build());

90.   //官方文档位置:http://developer.android.com/reference/android/provider/ContactsContract.Data.html

91.   //withValueBackReference后退引用前面联系人的id

92.   ops.add(ContentProviderOperation.newInsert(android.provider.ContactsContract.Data.CONTENT_URI)

93.   .withValueBackReference(Data.RAW_CONTACT_ID, rawContactInsertIndex)

94.   .withValue(Data.MIMETYPE, StructuredName.CONTENT_ITEM_TYPE)

95.   .withValue(StructuredName.GIVEN_NAME, "小明")

96.   .build());

97.   ops.add(ContentProviderOperation.newInsert(android.provider.ContactsContract.Data.CONTENT_URI)

98.   .withValueBackReference(Data.RAW_CONTACT_ID, rawContactInsertIndex)

99.   .withValue(Data.MIMETYPE, Phone.CONTENT_ITEM_TYPE)

100.            .withValue(Phone.NUMBER,"13671323809")

101.            .withValue(Phone.TYPE,Phone.TYPE_MOBILE)

102.            .withValue(Phone.LABEL, "手机号")

103.            .build());

104.            ops.add(ContentProviderOperation.newInsert(android.provider.ContactsContract.Data.CONTENT_URI)

105.            .withValueBackReference(Data.RAW_CONTACT_ID,rawContactInsertIndex)

106.            .withValue(Data.MIMETYPE,Email.CONTENT_ITEM_TYPE)

107.            .withValue(Email.DATA,"kesen@gmail.com")

108.            .withValue(Email.TYPE, Email.TYPE_WORK)

109.            .build());

110.            ContentProviderResult[] results =this.getContext().getContentResolver()

111.            .applyBatch(ContactsContract.AUTHORITY,ops);

112.            for(ContentProviderResult result :results)

113.            {

114.            Log.i(TAG, result.uri.toString());

115.            }

116.            }

117.            }

*******************************************************************************************************

这里主要使用的是ContactsContract类

从Android 2.0 SDK开始有关联系人provider的类变成了ContactsContract,虽然老的android.provider.Contacts能用,但是在SDK中标记为为deprecated将被放弃不推荐的方法,而从Android 2.0及API Level为5开始新增了android.provider.ContactsContract来代替原来的方法。不过Android123表示大家做两手准备,毕竟目前70%的设备以及Ophone 1.0和1.5均不支持ContactsContract。

ContactsContract.Contacts中的所有字段

ContactsContract.Contracts实现了4个接口,并从4个接口中,继承了不同的字段,一共有23个如下:

1.ContactsContract.Contacts.TIMES_CONTACTED ="times_contacted"

The number of times a contact has beencontacted

2.ContactsContract.Contacts.CONTACT_STATUS ="contact_status"

Contact's latest status update.

3.ContactsContract.Contacts.CUSTOM_RINGTONE ="custom_ringtone"

URI for a custom ringtone associatedwith the contact. Ifnull or missing, the default ringtone is used.

4.ContactsContract.Contacts.HAS_PHONE_NUMBER="has_phone_number"

An indicator of whether this contact hasat least one phonenumber. "1" if there is at least one phone number,"0"otherwise.

5.ContactsContract.Contacts.PHONETIC_NAME = "phonetic_name"

Pronunciation of the full name in thephonetic alphabetspecified by PHONETIC_NAME_STYLE.

6.ContactsContract.Contacts.PHONETIC_NAME_STYLE ="phonetic_name_style"

The phonetic alphabet used to representthe PHONETIC_NAME.See PhoneticNameStyle.

7.ContactsContract.Contacts.CONTACT_STATUS_LABEL="contact_status_label"

The resource ID of the label describingthe source ofcontact status, e.g. "Google Talk". This resource isscoped by theCONTACT_STATUS_RES_PACKAGE.

8.ContactsContract.Contacts.LOOKUP_KEY = "lookup"

An opaque value that contains hints onhow to find thecontact if its row id changed as a result of a sync oraggregation.

9.ContactsContract.Contacts.CONTACT_STATUS_ICON="contact_status_icon"

The resource ID of the icon for thesource of contactstatus. This resource is scoped by the

CONTACT_STATUS_RES_PACKAGE.

10.ContactsContract.Contacts.LAST_TIME_CONTACTED="last_time_contacted"

The last time a contact was contacted.

11.ContactsContract.Contacts.DISPLAY_NAME= "display_name"

The display name for the contact.

12.ContactsContract.Contacts.SORT_KEY_ALTERNATIVE="sort_key_alt"

Sort key based on the alternativerepresentation of thefull name, DISPLAY_NAME_ALTERNATIVE. Thus for Westernnames, it is the oneusing the "family name first" format.

13.ContactsContract.Contacts.IN_VISIBLE_GROUP="in_visible_group"

Lookup value that reflects theGROUP_VISIBLE state of anyContactsContract.CommonDataKinds.GroupMembership forthis contact.

14.ContactsContract.Contacts._ID= "_id"

The unique ID for a row.

15.ContactsContract.Contacts.STARRED= "starred"

Is the contact starred?

16.ContactsContract.Contacts.SORT_KEY_PRIMARY= "sort_key"

Sort key that takes into accountlocale-based traditionsfor sorting names in address books.

17.ContactsContract.Contacts.DISPLAY_NAME_ALTERNATIVE="display_name_alt"

An alternative representation of thedisplay name, such as"family name first" instead of "given namefirst" forWestern names. If an alternative is not available, the valuesshould be thesame as DISPLAY_NAME_PRIMARY

18.ContactsContract.Contacts.CONTACT_PRESENCE="contact_presence"

Contact presence status. SeeContactsContract.StatusUpdatesfor individual status definitions.

19.ContactsContract.Contacts.DISPLAY_NAME_SOURCE="display_name_source"

The kind of data that is used as thedisplay name for thecontact, such as structured name or email address. SeeDisplayNameSources.TODO: convert DisplayNameSources to a link after it isun-hidden

20.ContactsContract.Contacts.CONTACT_STATUS_RES_PACKAGE="contact_status_res_package"

The package containing resources forthis status: label andicon.

21.ContactsContract.Contacts.CONTACT_STATUS_TIMESTAMP= "contact_status_ts"

The absolute time in milliseconds whenthe latest statuswas inserted/updated.

22.ContactsContract.Contacts.PHOTO_ID= "photo_id"

Reference to the row in the data tableholding the photo.

23.ContactsContract.Contacts.SEND_TO_VOICEMAIL= "send_to_voicemail"

Whether the contact should always besent to voicemail. Ifmissing, defaults to false.

 

可以用以下方法,列出ContactsContract.Contacts中的所有字段:

private void listColumnNames()

{

private Uri contactUri=ContactsContract.Contacts.CONTENT_URI;

ContentResolverresolver = this.getContentResolver();

Cursor cursor=resolver.query(contactUri,null,null,null,null);

int columnNumber =cursor.getColumnCount();

for(int i = 0; i<columnNumber; i++)

{

String temp=cursor.getColumnName(i);

Log.e("listColumnNames","" + i +"\t" + temp);

}

cursor.close();

}

 

转载自新浪 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值