我想通过 Xamarin.Contacts.AddressBook
加载多个联系人,目前我有类似的内容:
var loookupIDs = /* load 10 saved contact IDs */
var addressBook = new AddressBook(context) { PreferContactAggregation = true };
foreach(var id in loookupIDs)
{
var contact = addressBook.Load(id);
names.Add(contact.DisplayName);
}
但是,这真的很慢(在 Android 设备上测试过)——即使只是加载 10 个联系人。有没有办法批量加载以使其更快?或者是使用平台特定 API 而不是 Xamarin 包装器的唯一选择。
最佳答案
是的,Xamarin.Mobile 有点慢。它结合了所有可能的联系人(电话、邮件等)和所有可能的字段,这是 Android 引用手册不推荐的。
我建议您使用原生方式通过 Cursor 查询您的联系人并根据您的需要对其进行过滤。遗憾的是,Xamarin dev 混淆了所有常量,因此这不是一项简单的任务。
这里是完整的例子
public class PhoneContactInfo
{
public string PhoneContactID { get; set; }
public string ContactName { get; set; }
public string ContactNumber { get; set; }
}
public IEnumerable<PhoneContactInfo> GetAllPhoneContacts(IEnumerable<int> filterIds = null)
{
Log.Debug("GetAllPhoneContacts", "Getting all Contacts");
var arrContacts = new System.Collections.Generic.List<PhoneContactInfo>();
PhoneContactInfo phoneContactInfo = null;
var uri = ContactsContract.CommonDataKinds.Phone.ContentUri;
string[] projection = { ContactsContract.Contacts.InterfaceConsts.Id,
ContactsContract.Contacts.InterfaceConsts.DisplayName,
ContactsContract.CommonDataKinds.Phone.Number
};
//String[] strings = filterIds.Select(k => Convert.ToString(k)).ToArray();
//string whereClause = ContactsContract.Contacts.InterfaceConsts.Id + " = ? ";
var cursor = MainActivity.ContextHolder.ContentResolver.Query(uri, projection,
null,
null,
null);
cursor.MoveToFirst();
while (cursor.IsAfterLast == false)
{
int phoneContactID = cursor.GetInt(cursor.GetColumnIndex(ContactsContract.Contacts.InterfaceConsts.Id));
if (filterIds.Contains(phoneContactID))
{
String contactNumber = cursor.GetString(cursor.GetColumnIndex(ContactsContract.CommonDataKinds.Phone.Number));
String contactName = cursor.GetString(cursor.GetColumnIndex(ContactsContract.Contacts.InterfaceConsts.DisplayName));
phoneContactInfo = new PhoneContactInfo()
{
PhoneContactID = Convert.ToString(phoneContactID),
ContactName = contactName,
ContactNumber = contactNumber
};
arrContacts.Add(phoneContactInfo);
}
cursor.MoveToNext();
}
cursor.Close();
cursor = null;
Log.Debug("GetAllPhoneContacts", "Got all Contacts");
return arrContacts;
}
如果你想添加一些花哨的异步
public Task<IEnumerable<PhoneContactInfo>> GetAllPhoneContactsAsync(IEnumerable<int> filterIds)
{
return Task.FromResult(GetAllPhoneContacts(filterIds));
}
另请查看注释的 whereClause
。您可以构建“类似 SQL”的 where 子句来使该查询更快。只需用几个 '=' 和 'or' 构建一个字符串
附言 我没有衡量性能差异,如果有人有不错的统计数据我将不胜感激
关于android - 使用 Xamarin.Contacts.AddressBook 加载多个联系人,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24962220/