问题
Android使用UVC软件库连接USB摄像头,不显示图像也没有其他反应,在Logcat中发现无法正常获取USB权限,并且提示“failed to open USB device(has no permission)”错误。
当前targetSdkVersion为30,比较高,调低到26,程序就正常了,可以正常显示图像。
因为当前应用使用的Jetpack库用的比较新,调低targetSdkVersion版本会有影响,还得对应修改Jetpack库的版本。所以就找了一下根本原因,发现UsbManager的hasPermission方法的注释中,提到Android P(API 28)之后,UVC设备还需要“android.Manifest.permission#CAMERA”权限。
/**
* Returns true if the caller has permission to access the device.
* Permission might have been granted temporarily via
* {@link #requestPermission(UsbDevice, PendingIntent)} or
* by the user choosing the caller as the default application for the device.
* Permission for USB devices of class {@link UsbConstants#USB_CLASS_VIDEO} for clients that
* target SDK {@link android.os.Build.VERSION_CODES#P} and above can be granted only if they
* have additionally the {@link android.Manifest.permission#CAMERA} permission.
*
* @param device to check permissions for
* @return true if caller has permission
*/
@RequiresFeature(PackageManager.FEATURE_USB_HOST)
public boolean hasPermission(UsbDevice device) {
if (mService == null) {
return false;
}
try {
return mService.hasDevicePermission(device, mContext.getPackageName());
} catch (RemoteException e) {
throw e.rethrowFromSystemServer();
}
}
解决办法
第一步:清单文件中,添加如下权限:
<uses-permission android:name="android.permission.CAMERA" />
第二步:Activity或者Fragment中,动态请求“android.permission.CAMERA”权限。