如何检测具有otg兼容性的Android设备
我正在使用以下代码:
context.getPackageManager().hasSystemFeature(PackageManager.FEATURE_USB_HOST);
对于非otg安卓设备
总是返回true答案 0 :(得分:0)
是的,它并不总是有效,某种错误。
通过otp连接USB设备,然后在app中使用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设备,我还没有找到任何其他可靠的软件检查来确认。
希望它有所帮助!
答案 1 :(得分:0)
此解决方案始终适用于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);
}
}
步骤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()));
}
}
}