UsbHid icon indicating copy to clipboard operation
UsbHid copied to clipboard

how do i know when the usb device detach/attach with mobile

Open evehal opened this issue 6 years ago • 1 comments

evehal avatar Apr 06 '18 09:04 evehal

To get notification about connected/disconnected devices register broadcast receiver.

var usbReceiver: BroadcastReceiver = object : BroadcastReceiver() {
    override fun onReceive(context: Context, intent: Intent) {
        if (UsbManager.ACTION_USB_DEVICE_ATTACHED == intent.action) {
            val device: UsbDevice? = intent.getParcelableExtra(UsbManager.EXTRA_DEVICE)
            device?.apply {
                // call your method that starts communication with the device
            }
        }
        else if (UsbManager.ACTION_USB_DEVICE_DETACHED == intent.action) {
            val device: UsbDevice? = intent.getParcelableExtra(UsbManager.EXTRA_DEVICE)
            device?.apply {
                // call your method that cleans up and closes communication with the device
            }
        }
    }
}

For more details please follow official documentation. https://developer.android.com/guide/topics/connectivity/usb/host

babcca avatar Sep 09 '19 13:09 babcca