Search code examples
androidxamarin.formsxamarin.essentials

How do i request permissions when not on the UI thread?


I'm currently using the latest version of Xamarin.Forms (4.5.0.617) and Xamarin.Essentials (1.5.2).

I have a dependency injected service which is responsible for getting access to phone contacts, it's effectively a wrapper around the Xamarin.Essentials permissions code. I need to guarantee that the code is executed on the UI thread to avoid exceptions. I've got as far as the below code, however, it isn't working as i'd expect. In my app, the permissions popup appears and offers me the choice allow/deny but then all code after RequestAsync fails to execute like a response is never officially returned. The next time I run the app, it works straight away (so presumably permission in the background has been correctly recorded).

public async Task<bool> RequestAccessPhoneContacts()
{
    PermissionStatus status = PermissionStatus.Denied;

    status = await MainThread.InvokeOnMainThreadAsync<PermissionStatus>(async () =>
    {
        return await Permissions.RequestAsync<Permissions.ContactsRead>();
    });

    return (status == PermissionStatus.Granted);
}

I'm not sure if i've caused an issue with the way i'm trying to force the code onto the UI thread or whether i'm using the async code incorrectly... or (least likely) whether it's a bug in the Xamarin.Essentials Permissions code. I've only seen this behaviour on Android at the moment, but I haven't tested it on any others.

Any help greatly appreciated :)

thanks!


Solution

  • Turns out I hadn't followed the documentation properly when setting this up.

    After adding this into my main activity, everything kicks back to life.

    public override void OnRequestPermissionsResult(int requestCode, string[] permissions, Android.Content.PM.Permission[] grantResults)
    {
        Xamarin.Essentials.Platform.OnRequestPermissionsResult(requestCode, permissions, grantResults);
    
        base.OnRequestPermissionsResult(requestCode, permissions, grantResults);
    }
    

    This information came out of me raising a bug on the Xamarin.Essentials github - https://github.com/xamarin/Essentials/issues/1227