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

问题描述 投票:0回答:1

我尝试在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 时,出现错误,

Targeting U+ (version 34 and above) disallows creating or retrieving a PendingIntent with FLAG_MUTABLE, an implicit Intent within and without FLAG_NO_CREATE and FLAG_ALLOW_UNSAFE_IMPLICIT_INTENT for security reasons. To retrieve an already existing PendingIntent, use FLAG_NO_CREATE, however, to create a new PendingIntent with an implicit Intent use FLAG_IMMUTABLE.

我把它改成Immutable,但我无法获得许可。

如何解决这个问题?

xamarin android-pendingintent usbserial android-14
1个回答
0
投票

尝试使用可变标志来明确意图。

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

© www.soinside.com 2019 - 2024. All rights reserved.