在Android 10及以上版本中,应用程序需要动态请求权限才能访问设备的USB功能。如果您遇到了“Android 10 USB主机 - 无法连接设备,权限未授予(但应该已授予)”的问题,可以按照以下步骤解决:
private static final String ACTION_USB_PERMISSION = "com.example.USB_PERMISSION";
private UsbManager usbManager;
private PendingIntent permissionIntent;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
usbManager = (UsbManager) getSystemService(Context.USB_SERVICE);
permissionIntent = PendingIntent.getBroadcast(this, 0, new Intent(ACTION_USB_PERMISSION), 0);
IntentFilter filter = new IntentFilter(ACTION_USB_PERMISSION);
registerReceiver(usbReceiver, filter);
// 检查是否已经授予USB权限
if (usbManager.hasPermission(device)) {
// 已经授予USB权限,进行设备连接操作
connectDevice(device);
} else {
// 请求USB权限
usbManager.requestPermission(device, permissionIntent);
}
}
private final BroadcastReceiver usbReceiver = new BroadcastReceiver() {
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (ACTION_USB_PERMISSION.equals(action)) {
synchronized (this) {
UsbDevice device = (UsbDevice) intent.getParcelableExtra(UsbManager.EXTRA_DEVICE);
if (intent.getBooleanExtra(UsbManager.EXTRA_PERMISSION_GRANTED, false)) {
if (device != null) {
// USB权限已经授予,进行设备连接操作
connectDevice(device);
}
} else {
// USB权限被拒绝
Log.d("USB", "Permission denied for device " + device);
}
}
}
}
};
private void connectDevice(UsbDevice device) {
// 连接设备的代码
}
请注意,上述代码中的device
变量是指您要连接的USB设备。您需要根据您的具体情况来获取和设置这个变量。
通过以上步骤,您应该能够解决“Android 10 USB主机 - 无法连接设备,权限未授予(但应该已授予)”的问题,并成功连接USB设备。