android 兼容各个版本 读取通讯录

本文介绍了一种适用于不同版本Android系统的通讯录读取方法,通过使用Build.VERSION.SDK_INT判断版本并选择合适的Uri来实现兼容性。重点在于如何在Android应用中根据系统版本灵活地获取联系人的信息。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

众所周知,android平台的向下的兼容性并不好,很多新版本的android系统的api与低版本的并不一样,但是我们遇到的情况是android的app一般只有一个,不可能针对每一个版本开发一套app,好在谷歌公司还算人性化的提供了 Build.VERSION.SDK_INT这个常亮,会根据不同android版本有不同的值。以下为兼容安卓各个版本读取通讯录的demo
Uri contentUri;
String id_field;
String name_field;
String number_field;

[color=red]boolean newapi = Build.VERSION.SDK_INT >= 5;//代表版本至少是2.0[/color]
if (newapi) {
contentUri = CommonDataKinds.Phone.CONTENT_URI;
id_field = CommonDataKinds.Phone.CONTACT_ID;
name_field = CommonDataKinds.Phone.DISPLAY_NAME;
number_field = CommonDataKinds.Phone.NUMBER;
} else {
contentUri = Contacts.People.CONTENT_URI;
id_field = Contacts.People._ID;
name_field = Contacts.People.DISPLAY_NAME;
number_field = Contacts.People.NUMBER;
}

ContentResolver cr = ReadMultipleSMSActivity.this.getContentResolver();
Cursor phone = cr.query(contentUri, new String[] { id_field,
name_field, number_field}, null, null, "sort_key");//按姓名升序排列

while (phone.moveToNext()) {
String contactId = phone.getString(phone
.getColumnIndex(id_field));
String displayName = phone.getString(phone
.getColumnIndex(name_field));
String PhoneNumber = CommTool.phoneNumberDeal(phone.getString(phone
.getColumnIndex(number_field)));
if (PhoneNumber!=null) {
contactsList.add(displayName+"\n"+showText+
PhoneNumber);
}
}
if (phone != null){
phone.close();
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值