Java – Android’s InputManager::registerInputDeviceListener didn’t call my listener

Android’s InputManager::registerInputDeviceListener didn’t call my listener… here is a solution to the problem.

Android’s InputManager::registerInputDeviceListener didn’t call my listener

I’m trying to get notified when an input device is added/removed, and as far as I can tell, this is what registerInputDeviceListener is supposed to do… But my listener is not being called!

Here is my code fragment :

InputManager im = (InputManager) getSystemService(Context.INPUT_SERVICE);
im.registerInputDeviceListener(new InputManager.InputDeviceListener() {
    @Override
    public void onInputDeviceAdded(int deviceId) {
        Log.d("Input", "InputDeviceAdded: " + deviceId);
    }

@Override
    public void onInputDeviceRemoved(int deviceId) {
            Log.d("Input", "InputDeviceRemoved: " + deviceId);
    }

@Override
    public void onInputDeviceChanged(int deviceId) {
        Log.d("Input", "InputDeviceChanged: " + deviceId);
    }
}, null);

This is what I see in logcat when I unplug the USB mouse :

01-15 19:19:04.025: INFO/EventHub(5935): Removing device '/dev/input/event0' due to inotify event
01-15 19:19:04.025: INFO/EventHub(5935): Removed device: path=/dev/input/event0 name=Primax USB OPTICAL MOUSE id=11 fd=245 classes=0x80000008
01-15 19:19:04.045: INFO/InputReader(5935): Device removed: id=11, name='Primax USB OPTICAL MOUSE', sources=0x00002002

But my listener has never been called….

Solution

It turns out that InputManager does not register itself for device changes unless getInputDevice or getInputDeviceByDescriptor was previously called.

Calling getInputDevice first (and ignoring the result) invokes my callback.

Related Problems and Solutions