Hello,
Welcome to our Microsoft Q&A platform!
Because android 10 do not use Android.Support.V4.Content.ContextCompat
to request permission, so please use Xamarin.Essentials: Permissions
to request runtime permission.
Please open the ContactsViewModel.cs
, add CheckAndContactsReadPermission()
method in LoadContacts
method like following code.
async Task LoadContacts()
{
try
{
await CheckAndContactsReadPermission();
await _contactService.RetrieveContactsAsync();
}
catch (TaskCanceledException)
{
Console.WriteLine("Task was cancelled");
}
}
public async Task<PermissionStatus> CheckAndContactsReadPermission()
{
var status = await Permissions.CheckStatusAsync<Permissions.ContactsRead>();
if (status == PermissionStatus.Granted)
return status;
if (status == PermissionStatus.Denied && DeviceInfo.Platform == DevicePlatform.iOS)
{
// Prompt the user to turn on in settings
// On iOS once a permission has been denied it may not be requested again from the application
return status;
}
status = await Permissions.RequestAsync<Permissions.ContactsRead>();
return status;
}
Then open ContactsService.cs
, please change the LoadContactsAsync
method like following code.
async Task<IList<Contact>> LoadContactsAsync()
{
IList<Contact> contacts = new List<Contact>();
//var hasPermission = await RequestPermissionAsync();
//if (hasPermission)
//{
var uri = ContactsContract.Contacts.ContentUri;
var ctx = Application.Context;
await Task.Run(() =>
{
var cursor = ctx.ApplicationContext.ContentResolver.Query(uri, new string[]
{
ContactsContract.Contacts.InterfaceConsts.Id,
ContactsContract.Contacts.InterfaceConsts.DisplayName,
ContactsContract.Contacts.InterfaceConsts.PhotoThumbnailUri
}, null, null, $"{ContactsContract.Contacts.InterfaceConsts.DisplayName} ASC");
if (cursor.Count > 0)
{
while (cursor.MoveToNext())
{
var contact = CreateContact(cursor, ctx);
if (!string.IsNullOrWhiteSpace(contact.Name))
{
OnContactLoaded?.Invoke(this, new ContactEventArgs(contact));
contacts.Add(contact);
}
if (stopLoad)
break;
}
}
});
// }
return contacts;
}
Here is running screenshot.
Best Regards,
Leon Lu
If the response is helpful, please click "Accept Answer" and upvote it.
Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.