如何检测android设备是否具有otg兼容性
我使用的代码如下:
context.getPackageManager().hasSystemFeature(PackageManager.FEATURE_USB_HOST);
对于非otg android设备,总是返回true
发布于 2016-10-26 19:08:12
是的,它并不总是有效的,某种bug。
通过动态口令连接usb设备,然后在应用程序中使用UsbManager系统服务,通过连接的USB设备进行枚举:
mUsbManager = (UsbManager) mApplicationContext.getSystemService(Context.USB_SERVICE);
HashMap<String, UsbDevice> devlist = mUsbManager.getDeviceList();
if(!devlist.isEmpty()){
// Supports usb host...
} else {
// Does not supports usb host...
}不幸的是,这种方法需要硬件usb设备,我还没有找到任何其他可靠的软件检查来证实这一点。
希望它能帮上忙!
发布于 2019-11-22 19:17:46
此解决方案始终适用于API级别24及以上:
步骤1 -询问使用辅助存储的权限:
StorageManager storageManager = (StorageManager) getSystemService(Context.STORAGE_SERVICE);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
StorageVolume primaryVolume = storageManager.getPrimaryStorageVolume(); // This will gives primary storage like internal storage
List<StorageVolume> lstStorages = storageManager.getStorageVolumes(); // it will gives all secondary storage like SDCrad and USb device list
for (int i = 0; i < lstStorages.size(); i++) {
Intent intent = lstStorages.get(i).createAccessIntent(null); // null pass for get full access of storage
startActivityForResult(intent, 6000);
}
}Step 2 -授予权限后:
protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == 6000 && resultCode == RESULT_OK) {
Uri treeUri = data.getData();
DocumentFile documentFile = DocumentFile.fromTreeUri(this, treeUri); //List of all documents files of secondary storage
List<DocumentFile> lstChildren = Arrays.asList(documentFile.listFiles());
getContentResolver().takePersistableUriPermission(treeUri, FLAG_GRANT_READ_URI_PERMISSION | FLAG_GRANT_WRITE_URI_PERMISSION); // It will not ask permission for every time
for (DocumentFile documentFile1 : lstChildren) {
getAllFiles(documentFile1);
}
}
}步骤3 -获取所有文件:
private void getAllFiles(DocumentFile documentFile) {
DocumentFile[] files;
files = documentFile.listFiles();
for (DocumentFile file : files) {
if (file.isDirectory()) {
getAllFiles(file);
} else {
lstFiles.add(new UsbFileModel(documentFile, file.getUri()));
}
}
}https://stackoverflow.com/questions/40260552
复制相似问题