首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Android usb主机- otg检测

Android usb主机- otg检测
EN

Stack Overflow用户
提问于 2016-10-26 19:01:11
回答 2查看 394关注 0票数 1

如何检测android设备是否具有otg兼容性

我使用的代码如下:

context.getPackageManager().hasSystemFeature(PackageManager.FEATURE_USB_HOST);

对于非otg android设备,总是返回true

EN

回答 2

Stack Overflow用户

发布于 2016-10-26 19:08:12

是的,它并不总是有效的,某种bug。

通过动态口令连接usb设备,然后在应用程序中使用UsbManager系统服务,通过连接的USB设备进行枚举:

代码语言:javascript
复制
 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
EN

Stack Overflow用户

发布于 2019-11-22 19:17:46

此解决方案始终适用于API级别24及以上:

步骤1 -询问使用辅助存储的权限:

代码语言:javascript
复制
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 -授予权限后:

代码语言:javascript
复制
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 -获取所有文件:

代码语言:javascript
复制
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()));
        }
    }
}
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/40260552

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档