Reputation: 53
How to detect that android device having otg compatibility or not
I am using below code :
context.getPackageManager().hasSystemFeature(PackageManager.FEATURE_USB_HOST);
It is always returning true for non-otg android devices
Upvotes: 1
Views: 546
Reputation: 1
This solution always work for API level 24 and above:
Step 1 - Ask permission for using the secondary storage:
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 - After permission is granted:
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);
}
}
}
Step 3 - Get all files:
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()));
}
}
}
Upvotes: 0
Reputation: 4284
Yes, it does not always work, some kind of a bug.
Connect a usb device through otp and then in app use the UsbManager system service and enumerate through attached USB devices :
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...
}
Unfortunately, hardware usb device is required for this approach, I haven't found any other reliable software check to confirm it.
Hope it helps !
Upvotes: 1