androidkotlinandroid-usb

Unable to list the USB connected devices in Android Kotlin


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?


Solution

  • According to the documentation the feature android.hardware.usb.host does the following:

    When your Android-powered device is in USB host mode, it acts as the USB host, powers the bus, and enumerates connected USB devices. USB host mode is supported in Android 3.1 and higher.

    So in other words this feature is designed to enumerate USB OTG devices like USB flash drives, webcams, or other USB client devices).

    When you connect laptop and phone via USB the laptop usually becomes the USB host (master) and the phone is the client. Therefore this feature is not designed to work with such a connection and thus you are getting no device.

    The only way to make it work would be to select in the USB notification menu that the Android phone should work as USB host. But as most PC are not able to act as USB client this will also not get any result.