UsbHid
UsbHid copied to clipboard
how do i know when the usb device detach/attach with mobile
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