Xamarin - USB Host - Android - Request Permission to connect to device (Crash)

Liberado Selso 21 Reputation points

I'm trying to resolve a crash when my application ask for permission to connect to a detected device.
I'm handling in the Android part using the usbManager.
It appears the the RequestPermission() from the usbManager does not wait for user input, so App continue exécution and crash.
After restart if permission was given everything works fine.

At first I added a broadcast receiver in the android interface to handle the event, but the Xamarin.forms part is not award that the process is async.

So I started to add Xamarin.Essential support like shown in the Xamarin doc.

I did add the code for Activity startup to init Xamarin Essential and the overrided function :

protected override void OnCreate(Bundle savedInstanceState)
Xamarin.Essentials.Platform.Init(this, savedInstanceState);
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);

I then create a Platform interface as advised in the Xamarin Guide. In that function a call the platform interface the request permission.

async Task<PermissionStatus> IUsbPermissions.RequestAsync()
PermissionStatus status;
status = await _iusbManager.RequestPermAsync(_szDevName);
await base.RequestAsync();
return status;

The problem is that the request permission just call the usbmanager request, so that I never fall in the override function : OnRequestPermissionsResult().

How can make it wait for the permission event ?
Does the fact that I define a custom permission interface disable the override OnRequestPermissionsResult() ?

A Microsoft open-source app platform for building Android and iOS apps with .NET and C#.
5,301 questions
0 comments No comments
{count} votes

Accepted answer
  1. Leon Lu (Shanghai Wicresoft Co,.Ltd.) 69,386 Reputation points Microsoft Vendor


    Welcome to our Microsoft Q&A platform!

    To grant the permission of opening the usb device, you have to use the grantPermission() method. The following code shows how to use the method and BroadcastReceiver to pop up a dialog asking the user to let the usb usage. For details, you can refer to the following link.


    And I check the Available Permissions for essemtials that do not contains USB permission.


    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.

0 additional answers

Sort by: Most helpful