这是关于获取手机通讯录闪退的bug,出现的问题,如果不是可以忽略。
然后我在网上找了蛮多帖子发现是Android11的问题。但是很神奇,只有部分机型会出现,期间也找了很多出现类似的问题,下面整理了解决方案,方便自己记忆、方便他人。不啰嗦直接上代码。
ContentResolver cr = context.getContentResolver();
Uri uri = CallLog.Calls.CONTENT_URI;
String[] projection = new String[]{CallLog.Calls.NUMBER, CallLog.Calls.CACHED_NAME};
try {
Cursor cursor = cr.query(uri, projection, null, null, sortOrder);
if (cursor != null) {
while (cursor.moveToNext()) {
String name = cursor.getString(cursor.getColumnIndex(CallLog.Calls.CACHED_NAME)); //姓名
String number = cursor.getString(cursor.getColumnIndex(CallLog.Calls.NUMBER)); //号码
ContactsInfo contactsInfo = new ContactsInfo();
contactsInfo.number = number;
contactsInfo.name = name;
list.add(contactsInfo);
}
cursor.close();
}
} catch (Exception e) {
Uri limitedCallLogUri;
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
limitedCallLogUri = CallLog.Calls.CONTENT_URI.buildUpon()
.appendQueryParameter(CallLog.Calls.LIMIT_PARAM_KEY, String.valueOf(size)).appendQueryParameter(ContentResolver.QUERY_ARG_OFFSET, String.valueOf(offset)).appendQueryParameter("limit", String.valueOf(size)).build();
}else {
limitedCallLogUri = CallLog.Calls.CONTENT_URI.buildUpon()
.appendQueryParameter(CallLog.Calls.LIMIT_PARAM_KEY, String.valueOf(size)).appendQueryParameter("limit", String.valueOf(size)).build();
}
Cursor cursor = cr.query(limitedCallLogUri, projection, null, null, CallLog.Calls.DEFAULT_SORT_ORDER);
if (cursor != null) {
while (cursor.moveToNext()) {
String name = cursor.getString(cursor.getColumnIndex(CallLog.Calls.CACHED_NAME)); //姓名
String number = cursor.getString(cursor.getColumnIndex(CallLog.Calls.NUMBER)); //号码
ContactsInfo contactsInfo = new ContactsInfo();
contactsInfo.number = number;
contactsInfo.name = name;
list.add(contactsInfo);
}
cursor.close();
}
}
注意事项:
limit后面的值是获取的列表的值。可以写活的,也可以写死的100。之前我就是给他写死1了,还一直纳闷为什么只有一条数据。
然后之前我找到相关的文章的链接也发一下,方便大家能够找到类似的问题,少走弯路。
错误提示:java.lang.IllegalArgumentException:Invalid token LIMIT的解决方法_limeng的博客-CSDN博客
深海游弋的鱼 – 默默的点滴
android - ContentResolver.query() method throws "Invalid token limit" error - Stack Overflow
https://github.com/donkingliang/ImageSelector/issues/69
|