We use a combination of two different things. The first is we detect if the device is in desktop mode using the following code snippet :
fun isDesktopMode() : Boolean {
var hasMouse = false
val hasKeyboard = resources.configuration.keyboard == KEYBOARD_QWERTY
val isKeyboardUseable = resources.configuration.hardKeyboardHidden == HARDKEYBOARDHIDDEN_NO
// Check each input device to see if it is a mouse
val inputManager = getSystemService(Context.INPUT_SERVICE) as InputManager
for (deviceId in inputManager.inputDeviceIds) {
val sourceMask = inputManager.getInputDevice(deviceId).sources
if ((sourceMask or SOURCE_MOUSE == sourceMask) ||
(sourceMask or SOURCE_TOUCHPAD == sourceMask) ||
(sourceMask or SOURCE_TRACKBALL == sourceMask)) {
hasMouse = true
}
}
return hasMouse && hasKeyboard && isKeyboardUseable
}
To detect if a keyboard is plugged in and/or available we use the following listener for listening to whether or not a keyboard has become active:
val inputManager = getSystemService(Context.INPUT_SERVICE) as InputManager
val inputDeviceListener = object: InputManager.InputDeviceListener {
override fun onInputDeviceRemoved(deviceId: Int) {
// Be careful checking device here as it is no longer attached to the system
}
override fun onInputDeviceAdded(deviceId: Int) {
// If you want to learn more about what has been attached, check the InputDevice
// using the id.
val sourceMask = inputManager.getInputDevice(deviceId).sources
if (sourceMask or SOURCE_KEYBOARD == sourceMask) {
//Keyboard has been Added
append_to_log("A keyboard has been added.")
}
}
override fun onInputDeviceChanged(deviceId: Int) {
// Best practice is to check for what you care about when things change (ie. are
// there any keyboards/mice still attached and usable. Users may have multiple
// devices attached (integrated keyboard a and bluetooth keyboard) and
// removing one does not mean the other is no longer available.
isInDesktopMode = isDesktopMode()
}
}
inputManager.registerInputDeviceListener(inputDeviceListener, null)
This post is licensed under Apache 2.0.
https://developers.google.com/open-source/devplat