如何在Android平台上的.NET Maui中获得从USB串行端口打开和读取权限的授予结果?

r9f1avp5  于 2023-07-01  发布在  .NET
关注(0)|答案(1)|浏览(465)

我正在尝试创建一个.NET Maui应用程序,该应用程序可以从通过USB(RS-232仿真)连接的设备(条形码阅读器)读取数据。我获取设备,强制权限请求,但应用程序继续,而不等待授予权限的结果。请不要有你的成功的解决方案可用?不幸的是,我在.NET Maui文档中找不到任何东西。
这是我的代码,基于[https://stackoverflow.com/questions/73534644/how-to-write-raw-data-to-usb-connected-device-using-net-maui]中的示例:

Activity act = Platform.CurrentActivity;
UsbManager manager = (UsbManager)act.GetSystemService(Context.UsbService);
IDictionary<string, UsbDevice> devicesDictionary = manager.DeviceList;
UsbDevice dvc = _usbDevice; // I find _usbDevice successfully

string ACTION_USB_PERMISSION = "com.MauiAndroidSerialPort.USB_PERMISSION";
var interf = dvc.GetInterface(1);
var outEndpoint = interf.GetEndpoint(1);
PendingIntent mPermissionIntent = PendingIntent.GetBroadcast(act, 0, new Intent(ACTION_USB_PERMISSION), PendingIntentFlags.Immutable);

IntentFilter filter = new IntentFilter(ACTION_USB_PERMISSION);
if (manager.HasPermission(dvc) == false)
    manager.RequestPermission(dvc, mPermissionIntent);
//Here I would need the result of enabling permissions

var deviceConnection = manager.OpenDevice(dvc);

if (deviceConnection != null)
    deviceConnection.ClaimInterface(interf, true).ToString();
niknxzdl

niknxzdl1#

没有一个这样的API可以在权限对话框出现时获得授予权限的结果。但是您可以创建一个新线程来检查循环中的权限状态(manager.HasPermission(dvc))。比如这个关于How to handle the Usb Permission Dialog Event on android when using the "device filter" solution?的类似线程。
或者你可以尝试为下面的代码添加一个判断。例如:

if(manager.HasPermission(dvc))
{
   // do something
}else{
   // do something
}

相关问题