在Android 14上请求USB权限失败,xamarin

0h4hbjxa  于 9个月前  发布在  Android
关注(0)|答案(1)|浏览(128)

我试图在Android 14和Xamarin项目上获得USB设备的权限。我使用USBSerialForAndroid(https://github.com/anotherlab/UsbSerialForAndroid/
以下是我工作的地方。

public static Task<bool> RequestPermissionAsync(this UsbManager manager, UsbDevice device, Context context)
        {
            var completionSource = new TaskCompletionSource<bool>();

            var usbPermissionReceiver = new UsbPermissionReceiver(completionSource);

            if (Build.VERSION.SdkInt >= BuildVersionCodes.Tiramisu)
                context.RegisterReceiver(usbPermissionReceiver, new IntentFilter(ACTION_USB_PERMISSION), (ActivityFlags)ReceiverFlags.Exported);
            else
                context.RegisterReceiver(usbPermissionReceiver, new IntentFilter(ACTION_USB_PERMISSION));
            

            // Targeting S+ (version 31 and above) requires that one of FLAG_IMMUTABLE or FLAG_MUTABLE be specified when creating a PendingIntent.
            PendingIntentFlags pendingIntentFlags = Build.VERSION.SdkInt >= BuildVersionCodes.S && Build.VERSION.SdkInt < BuildVersionCodes.Tiramisu ? PendingIntentFlags.Mutable  : 0;

            var intent = PendingIntent.GetBroadcast(context, 0, new Intent(ACTION_USB_PERMISSION), pendingIntentFlags);

            manager.RequestPermission(device, intent);  

            return completionSource.Task;
        }

字符串
但是当我将PendingIntentFlags设置为Mutable,Getting error时,
第一个月
我把它改了,但我得不到许可。
我该如何解决这个问题?
解决

public static Task<bool> RequestPermissionAsync_Another(this UsbManager manager, UsbDevice device, Context context)
    {
        TaskCompletionSource<bool> taskCompletionSource = new TaskCompletionSource<bool>();
        UsbPermissionReceiver receiver = new UsbPermissionReceiver(taskCompletionSource);
        if (Build.VERSION.SdkInt >= BuildVersionCodes.Tiramisu)
            context.RegisterReceiver(receiver, new IntentFilter(ACTION_USB_PERMISSION), ReceiverFlags.Exported);
        else
            context.RegisterReceiver(receiver, new IntentFilter(ACTION_USB_PERMISSION));

        Intent intent = new Intent(ACTION_USB_PERMISSION);
        intent.SetPackage(context.PackageName);

        PendingIntent broadcast = PendingIntent.GetBroadcast(context, 0, intent, PendingIntentFlags.Mutable);
        manager.RequestPermission(device, broadcast);
        return taskCompletionSource.Task;
    }

62o28rlo

62o28rlo1#

尝试使用可变标志的显式意图。

Intent intent = new Intent(ACTION_USB_PERMISSION);
intent.setPackage(getPackageName());
pendingIntent = PendingIntent.getBroadcast(this, 0, intent, PendingIntent.FLAG_MUTABLE);

字符串
https://developer.android.com/about/versions/14/behavior-changes-14#safer-intents

相关问题