I am building an Android app using Kotlin. What I am trying to do is that I am trying to list down all the devices connected via USB. But the device list is always empty.
First I put in the following declaration in the AndroidManifest.xml
file:
<uses-feature android:name="android.hardware.usb.host" />
When the activity is open, within the onCreate method, I called the following function to get the list of USB connected devices:
private fun getDeviceList(): ArrayList<UsbDevice> {
var deviceList: ArrayList<UsbDevice> = ArrayList()
var usbManager: UsbManager = activity?.getSystemService(Context.USB_SERVICE) as UsbManager
for (device in usbManager.deviceList.values) {
deviceList.add(
UsbDevice(
id = device.deviceId.toString(),
name = device.deviceName,
model = "device"
)
)
}
if (usbManager.accessoryList != null) {
for (accessory in usbManager.accessoryList) {
deviceList.add(
UsbDevice(
id = accessory.serial.toString(),
name = accessory.description.toString(),
model = "accessory"
)
)
}
}
return deviceList
}
I have connected my device to my laptop. But when I opened the app, the device list is always empty. What is wrong with code and how can I fix it?