Is there a way to detect USB devices in an Android application on ChromeOS?

748 views Asked by At

The device must be in USB Host mode to use the UsbManager class. However, when checking if the app is in USB Host mode using packagemanager.hasSystemFeature(PackageManager.FEATURE_USB_HOST), it always returns false. Apparently, USB Host is an unsupported feature on Chromebooks. Is there another way to detect when a USB is inserted on Android on Chromebooks?

We're transitioning from Chrome App to Android and this documentation says to use a "Temporary* private USB host API" in place of the chrome.usb feature. But the link is broken and I can't find more information on it.

I've also tried the USB Web API with no results (the app is contained within a webview, so thought it might work).

1

There are 1 answers

0
Gavin Wright On

The solution is to use the state property of the StorageVolume. A StorageMediaState value of MOUNTED will indicate a mounted USB drive. You also need to filter out non-USB drives by using the various properties of the attached StorageVolumes.

fun getStorageMediaStateFromVolume(volume: StorageVolume?): StorageMediaState {
    val volumeState = volume?.state
    return if (volume == null || volumeState == null) StorageMediaState.UNKNOWN
    else StorageMediaState.values().find { it.stringValue == volumeState } ?: StorageMediaState.UNKNOWN
}
enum class StorageMediaState(val stringValue: String, val isDriveInserted: Boolean) {
    // Unknown storage state, such as when a path isn't backed by known storage media.
    // This is the value when no drive is inserted.
    UNKNOWN(Environment.MEDIA_UNKNOWN, false),

    // Media is present but not mounted. Usually this state occurs after an ejection has completed
    // but the user has not yet removed the drive.
    UNMOUNTED(Environment.MEDIA_UNMOUNTED, true),

    // Media is present and being disk-checked.
    CHECKING(Environment.MEDIA_CHECKING, true),

    // Media is present but is blank or is using an unsupported filesystem.
    NOFS(Environment.MEDIA_NOFS, true),

    // Media is present and mounted at its mount point with read/write access.
    MOUNTED(Environment.MEDIA_MOUNTED, true),

    // Media is present and mounted at its mount point with read-only access.
    MOUNTED_READ_ONLY(Environment.MEDIA_MOUNTED_READ_ONLY, true),

    // Media is present not mounted, and shared via USB mass storage.
    SHARED(Environment.MEDIA_SHARED, true),

    // Media is present but cannot be mounted, typically because the media's file system is corrupted.
    UNMOUNTABLE(Environment.MEDIA_UNMOUNTABLE, true),

    // Media is in the process of being ejected.
    EJECTING(Environment.MEDIA_EJECTING, true),

    // Media is not present.
    REMOVED(Environment.MEDIA_REMOVED, false),

    // Media was removed before it was unmounted.
    BAD_REMOVAL(Environment.MEDIA_BAD_REMOVAL, false)
}