android 兼容各个版本 读取通讯录 androidBuild.VERSION.SDK_INT兼容通讯录
程序员文章站
2022-06-09 19:44:41
...
众所周知,android平台的向下的兼容性并不好,很多新版本的android系统的api与低版本的并不一样,但是我们遇到的情况是android的app一般只有一个,不可能针对每一个版本开发一套app,好在谷歌公司还算人性化的提供了 Build.VERSION.SDK_INT这个常亮,会根据不同android版本有不同的值。以下为兼容安卓各个版本读取通讯录的demo
Uri contentUri;
String id_field;
String name_field;
String number_field;
boolean newapi = Build.VERSION.SDK_INT >= 5;//代表版本至少是2.0
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();
}
Uri contentUri;
String id_field;
String name_field;
String number_field;
boolean newapi = Build.VERSION.SDK_INT >= 5;//代表版本至少是2.0
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();
}
上一篇: IOS开发之路--C语言指针