I've looked everywhere but can't find an answer specifically for hardware keyboards.
I've tried checking the devices list from UsbManager
but it comes up empty.
I am able to detect whether a hardware keyboard is detected or when it is connected/disconnected but I am not sure if it's possible to extract information about the device (serial number, name, etc.).
Is this even possible?
I ended up using the InputManager
to get the information I needed.
In onCreate
I would call a method to go over all the InputDevice
s and filter out the non-external, non-keyboard devices:
private fun checkForPhysicalKeyboards() =
viewModel.setPhysicalKeyboardDevices(inputManager.inputDeviceIds.toTypedArray()
.mapNotNull { inputManager.getInputDevice(it) }.filter { it.isExternalKeyboard() })
private fun InputDevice.isExternalKeyboard() =
isExternal && keyboardType == InputDevice.KEYBOARD_TYPE_ALPHABETIC
I then also registered an InputDeviceListener
with the InputManager
to monitor for changes as not every connection/disconnection of a keyboard would count as a configuration change that would cause the activity to be recreated:
private val inputDeviceListener = object : InputManager.InputDeviceListener {
override fun onInputDeviceAdded(deviceId: Int) {
inputManager.getInputDevice(deviceId)?.takeIf { it.isExternalKeyboard() }
?.let { viewModel.addPhysicalKeyboardDevice(it) }
}
override fun onInputDeviceRemoved(deviceId: Int) =
viewModel.removePhysicalKeyboardDevice(deviceId)
override fun onInputDeviceChanged(deviceId: Int) {
inputManager.getInputDevice(deviceId)
?.let { viewModel.updatePhysicalKeyboardDevice(it) }
}
}
The InputDevice
objects contained all the information I needed from the connected devices.