FileDocCategorySizeDatePackage
InputManager.javaAPI DocAndroid 5.1 API32773Thu Mar 12 22:22:10 GMT 2015android.hardware.input

InputManager

public final class InputManager extends Object
Provides information about input devices and available key layouts.

Get an instance of this class by calling {@link android.content.Context#getSystemService(java.lang.String) Context.getSystemService()} with the argument {@link android.content.Context#INPUT_SERVICE}.

Fields Summary
private static final String
TAG
private static final boolean
DEBUG
private static final int
MSG_DEVICE_ADDED
private static final int
MSG_DEVICE_REMOVED
private static final int
MSG_DEVICE_CHANGED
private static InputManager
sInstance
private final IInputManager
mIm
private final Object
mInputDevicesLock
private android.util.SparseArray
mInputDevices
private InputDevicesChangedListener
mInputDevicesChangedListener
private final ArrayList
mInputDeviceListeners
public static final String
ACTION_QUERY_KEYBOARD_LAYOUTS
Broadcast Action: Query available keyboard layouts.

The input manager service locates available keyboard layouts by querying broadcast receivers that are registered for this action. An application can offer additional keyboard layouts to the user by declaring a suitable broadcast receiver in its manifest.

Here is an example broadcast receiver declaration that an application might include in its AndroidManifest.xml to advertise keyboard layouts. The meta-data specifies a resource that contains a description of each keyboard layout that is provided by the application.


<receiver android:name=".InputDeviceReceiver"
android:label="@string/keyboard_layouts_label">
<intent-filter>
<action android:name="android.hardware.input.action.QUERY_KEYBOARD_LAYOUTS" />
</intent-filter>
<meta-data android:name="android.hardware.input.metadata.KEYBOARD_LAYOUTS"
android:resource="@xml/keyboard_layouts" />
</receiver>

In the above example, the @xml/keyboard_layouts resource refers to an XML resource whose root element is <keyboard-layouts> that contains zero or more <keyboard-layout> elements. Each <keyboard-layout> element specifies the name, label, and location of a key character map for a particular keyboard layout. The label on the receiver is used to name the collection of keyboard layouts provided by this receiver in the keyboard layout settings.


<?xml version="1.0" encoding="utf-8"?>
<keyboard-layouts xmlns:android="http://schemas.android.com/apk/res/android">
<keyboard-layout android:name="keyboard_layout_english_us"
android:label="@string/keyboard_layout_english_us_label"
android:keyboardLayout="@raw/keyboard_layout_english_us" />
</keyboard-layouts>

The android:name attribute specifies an identifier by which the keyboard layout will be known in the package. The android:label attributes specifies a human-readable descriptive label to describe the keyboard layout in the user interface, such as "English (US)". The android:keyboardLayout attribute refers to a key character map resource that defines the keyboard layout.

public static final String
META_DATA_KEYBOARD_LAYOUTS
Metadata Key: Keyboard layout metadata associated with {@link #ACTION_QUERY_KEYBOARD_LAYOUTS}.

Specifies the resource id of a XML resource that describes the keyboard layouts that are provided by the application.

public static final int
MIN_POINTER_SPEED
Pointer Speed: The minimum (slowest) pointer speed (-7).
public static final int
MAX_POINTER_SPEED
Pointer Speed: The maximum (fastest) pointer speed (7).
public static final int
DEFAULT_POINTER_SPEED
Pointer Speed: The default pointer speed (0).
public static final int
INJECT_INPUT_EVENT_MODE_ASYNC
Input Event Injection Synchronization Mode: None. Never blocks. Injection is asynchronous and is assumed always to be successful.
public static final int
INJECT_INPUT_EVENT_MODE_WAIT_FOR_RESULT
Input Event Injection Synchronization Mode: Wait for result. Waits for previous events to be dispatched so that the input dispatcher can determine whether input event injection will be permitted based on the current input focus. Does not wait for the input event to finish being handled by the application.
public static final int
INJECT_INPUT_EVENT_MODE_WAIT_FOR_FINISH
Input Event Injection Synchronization Mode: Wait for finish. Waits for the event to be delivered to the application and handled.
Constructors Summary
private InputManager(IInputManager im)

  // see InputDispatcher.h

       
        mIm = im;
    
Methods Summary
public voidaddKeyboardLayoutForInputDevice(InputDeviceIdentifier identifier, java.lang.String keyboardLayoutDescriptor)
Adds the keyboard layout descriptor for the specified input device.

This method may have the side-effect of causing the input device in question to be reconfigured.

param
identifier The identifier for the input device.
param
keyboardLayoutDescriptor The descriptor of the keyboard layout to add.
hide

        if (identifier == null) {
            throw new IllegalArgumentException("inputDeviceDescriptor must not be null");
        }
        if (keyboardLayoutDescriptor == null) {
            throw new IllegalArgumentException("keyboardLayoutDescriptor must not be null");
        }

        try {
            mIm.addKeyboardLayoutForInputDevice(identifier, keyboardLayoutDescriptor);
        } catch (RemoteException ex) {
            Log.w(TAG, "Could not add keyboard layout for input device.", ex);
        }
    
private static booleancontainsDeviceId(int[] deviceIdAndGeneration, int deviceId)

        for (int i = 0; i < deviceIdAndGeneration.length; i += 2) {
            if (deviceIdAndGeneration[i] == deviceId) {
                return true;
            }
        }
        return false;
    
public boolean[]deviceHasKeys(int[] keyCodes)
Queries the framework about whether any physical keys exist on the any keyboard attached to the device that are capable of producing the given array of key codes.

param
keyCodes The array of key codes to query.
return
A new array of the same size as the key codes array whose elements are set to true if at least one attached keyboard supports the corresponding key code at the same index in the key codes array.
hide

        return deviceHasKeys(-1, keyCodes);
    
public boolean[]deviceHasKeys(int id, int[] keyCodes)
Queries the framework about whether any physical keys exist on the any keyboard attached to the device that are capable of producing the given array of key codes.

param
id The id of the device to query.
param
keyCodes The array of key codes to query.
return
A new array of the same size as the key codes array whose elements are set to true if the given device could produce the corresponding key code at the same index in the key codes array.
hide

        boolean[] ret = new boolean[keyCodes.length];
        try {
            mIm.hasKeys(id, InputDevice.SOURCE_ANY, keyCodes, ret);
        } catch (RemoteException e) {
            // no fallback; just return the empty array
        }
        return ret;
    
private intfindInputDeviceListenerLocked(android.hardware.input.InputManager$InputDeviceListener listener)

        final int numListeners = mInputDeviceListeners.size();
        for (int i = 0; i < numListeners; i++) {
            if (mInputDeviceListeners.get(i).mListener == listener) {
                return i;
            }
        }
        return -1;
    
public java.lang.StringgetCurrentKeyboardLayoutForInputDevice(InputDeviceIdentifier identifier)
Gets the current keyboard layout descriptor for the specified input device.

param
identifier Identifier for the input device
return
The keyboard layout descriptor, or null if no keyboard layout has been set.
hide

        try {
            return mIm.getCurrentKeyboardLayoutForInputDevice(identifier);
        } catch (RemoteException ex) {
            Log.w(TAG, "Could not get current keyboard layout for input device.", ex);
            return null;
        }
    
public android.view.InputDevicegetInputDevice(int id)
Gets information about the input device with the specified id.

param
id The device id.
return
The input device or null if not found.

        synchronized (mInputDevicesLock) {
            populateInputDevicesLocked();

            int index = mInputDevices.indexOfKey(id);
            if (index < 0) {
                return null;
            }

            InputDevice inputDevice = mInputDevices.valueAt(index);
            if (inputDevice == null) {
                try {
                    inputDevice = mIm.getInputDevice(id);
                } catch (RemoteException ex) {
                    throw new RuntimeException("Could not get input device information.", ex);
                }
                if (inputDevice != null) {
                    mInputDevices.setValueAt(index, inputDevice);
                }
            }
            return inputDevice;
        }
    
public android.view.InputDevicegetInputDeviceByDescriptor(java.lang.String descriptor)
Gets information about the input device with the specified descriptor.

param
descriptor The input device descriptor.
return
The input device or null if not found.
hide

        if (descriptor == null) {
            throw new IllegalArgumentException("descriptor must not be null.");
        }

        synchronized (mInputDevicesLock) {
            populateInputDevicesLocked();

            int numDevices = mInputDevices.size();
            for (int i = 0; i < numDevices; i++) {
                InputDevice inputDevice = mInputDevices.valueAt(i);
                if (inputDevice == null) {
                    int id = mInputDevices.keyAt(i);
                    try {
                        inputDevice = mIm.getInputDevice(id);
                    } catch (RemoteException ex) {
                        // Ignore the problem for the purposes of this method.
                    }
                    if (inputDevice == null) {
                        continue;
                    }
                    mInputDevices.setValueAt(i, inputDevice);
                }
                if (descriptor.equals(inputDevice.getDescriptor())) {
                    return inputDevice;
                }
            }
            return null;
        }
    
public int[]getInputDeviceIds()
Gets the ids of all input devices in the system.

return
The input device ids.

        synchronized (mInputDevicesLock) {
            populateInputDevicesLocked();

            final int count = mInputDevices.size();
            final int[] ids = new int[count];
            for (int i = 0; i < count; i++) {
                ids[i] = mInputDevices.keyAt(i);
            }
            return ids;
        }
    
public android.os.VibratorgetInputDeviceVibrator(int deviceId)
Gets a vibrator service associated with an input device, assuming it has one.

return
The vibrator, never null.
hide

        return new InputDeviceVibrator(deviceId);
    
public static android.hardware.input.InputManagergetInstance()
Gets an instance of the input manager.

return
The input manager instance.
hide

        synchronized (InputManager.class) {
            if (sInstance == null) {
                IBinder b = ServiceManager.getService(Context.INPUT_SERVICE);
                sInstance = new InputManager(IInputManager.Stub.asInterface(b));
            }
            return sInstance;
        }
    
public KeyboardLayoutgetKeyboardLayout(java.lang.String keyboardLayoutDescriptor)
Gets the keyboard layout with the specified descriptor.

param
keyboardLayoutDescriptor The keyboard layout descriptor, as returned by {@link KeyboardLayout#getDescriptor()}.
return
The keyboard layout, or null if it could not be loaded.
hide

        if (keyboardLayoutDescriptor == null) {
            throw new IllegalArgumentException("keyboardLayoutDescriptor must not be null");
        }

        try {
            return mIm.getKeyboardLayout(keyboardLayoutDescriptor);
        } catch (RemoteException ex) {
            Log.w(TAG, "Could not get keyboard layout information.", ex);
            return null;
        }
    
public KeyboardLayout[]getKeyboardLayouts()
Gets information about all supported keyboard layouts.

The input manager consults the built-in keyboard layouts as well as all keyboard layouts advertised by applications using a {@link #ACTION_QUERY_KEYBOARD_LAYOUTS} broadcast receiver.

return
A list of all supported keyboard layouts.
hide

        try {
            return mIm.getKeyboardLayouts();
        } catch (RemoteException ex) {
            Log.w(TAG, "Could not get list of keyboard layout informations.", ex);
            return new KeyboardLayout[0];
        }
    
public java.lang.String[]getKeyboardLayoutsForInputDevice(InputDeviceIdentifier identifier)
Gets all keyboard layout descriptors that are enabled for the specified input device.

param
identifier The identifier for the input device.
return
The keyboard layout descriptors.
hide

        if (identifier == null) {
            throw new IllegalArgumentException("inputDeviceDescriptor must not be null");
        }

        try {
            return mIm.getKeyboardLayoutsForInputDevice(identifier);
        } catch (RemoteException ex) {
            Log.w(TAG, "Could not get keyboard layouts for input device.", ex);
            return ArrayUtils.emptyArray(String.class);
        }
    
public intgetPointerSpeed(android.content.Context context)
Gets the mouse pointer speed.

Only returns the permanent mouse pointer speed. Ignores any temporary pointer speed set by {@link #tryPointerSpeed}.

param
context The application context.
return
The pointer speed as a value between {@link #MIN_POINTER_SPEED} and {@link #MAX_POINTER_SPEED}, or the default value {@link #DEFAULT_POINTER_SPEED}.
hide

        int speed = DEFAULT_POINTER_SPEED;
        try {
            speed = Settings.System.getInt(context.getContentResolver(),
                    Settings.System.POINTER_SPEED);
        } catch (SettingNotFoundException snfe) {
        }
        return speed;
    
public TouchCalibrationgetTouchCalibration(java.lang.String inputDeviceDescriptor, int surfaceRotation)
Gets the TouchCalibration applied to the specified input device's coordinates.

param
inputDeviceDescriptor The input device descriptor.
return
The TouchCalibration currently assigned for use with the given input device. If none is set, an identity TouchCalibration is returned.
hide

        try {
            return mIm.getTouchCalibrationForInputDevice(inputDeviceDescriptor, surfaceRotation);
        } catch (RemoteException ex) {
            Log.w(TAG, "Could not get calibration matrix for input device.", ex);
            return TouchCalibration.IDENTITY;
        }
    
public booleaninjectInputEvent(android.view.InputEvent event, int mode)
Injects an input event into the event system on behalf of an application. The synchronization mode determines whether the method blocks while waiting for input injection to proceed.

Requires {@link android.Manifest.permission.INJECT_EVENTS} to inject into windows that are owned by other applications.

Make sure you correctly set the event time and input source of the event before calling this method.

param
event The event to inject.
param
mode The synchronization mode. One of: {@link #INJECT_INPUT_EVENT_MODE_ASYNC}, {@link #INJECT_INPUT_EVENT_MODE_WAIT_FOR_RESULT}, or {@link #INJECT_INPUT_EVENT_MODE_WAIT_FOR_FINISH}.
return
True if input event injection succeeded.
hide

        if (event == null) {
            throw new IllegalArgumentException("event must not be null");
        }
        if (mode != INJECT_INPUT_EVENT_MODE_ASYNC
                && mode != INJECT_INPUT_EVENT_MODE_WAIT_FOR_FINISH
                && mode != INJECT_INPUT_EVENT_MODE_WAIT_FOR_RESULT) {
            throw new IllegalArgumentException("mode is invalid");
        }

        try {
            return mIm.injectInputEvent(event, mode);
        } catch (RemoteException ex) {
            return false;
        }
    
private voidonInputDevicesChanged(int[] deviceIdAndGeneration)

        if (DEBUG) {
            Log.d(TAG, "Received input devices changed.");
        }

        synchronized (mInputDevicesLock) {
            for (int i = mInputDevices.size(); --i > 0; ) {
                final int deviceId = mInputDevices.keyAt(i);
                if (!containsDeviceId(deviceIdAndGeneration, deviceId)) {
                    if (DEBUG) {
                        Log.d(TAG, "Device removed: " + deviceId);
                    }
                    mInputDevices.removeAt(i);
                    sendMessageToInputDeviceListenersLocked(MSG_DEVICE_REMOVED, deviceId);
                }
            }

            for (int i = 0; i < deviceIdAndGeneration.length; i += 2) {
                final int deviceId = deviceIdAndGeneration[i];
                int index = mInputDevices.indexOfKey(deviceId);
                if (index >= 0) {
                    final InputDevice device = mInputDevices.valueAt(index);
                    if (device != null) {
                        final int generation = deviceIdAndGeneration[i + 1];
                        if (device.getGeneration() != generation) {
                            if (DEBUG) {
                                Log.d(TAG, "Device changed: " + deviceId);
                            }
                            mInputDevices.setValueAt(index, null);
                            sendMessageToInputDeviceListenersLocked(MSG_DEVICE_CHANGED, deviceId);
                        }
                    }
                } else {
                    if (DEBUG) {
                        Log.d(TAG, "Device added: " + deviceId);
                    }
                    mInputDevices.put(deviceId, null);
                    sendMessageToInputDeviceListenersLocked(MSG_DEVICE_ADDED, deviceId);
                }
            }
        }
    
private voidpopulateInputDevicesLocked()

        if (mInputDevicesChangedListener == null) {
            final InputDevicesChangedListener listener = new InputDevicesChangedListener();
            try {
                mIm.registerInputDevicesChangedListener(listener);
            } catch (RemoteException ex) {
                throw new RuntimeException(
                        "Could not get register input device changed listener", ex);
            }
            mInputDevicesChangedListener = listener;
        }

        if (mInputDevices == null) {
            final int[] ids;
            try {
                ids = mIm.getInputDeviceIds();
            } catch (RemoteException ex) {
                throw new RuntimeException("Could not get input device ids.", ex);
            }

            mInputDevices = new SparseArray<InputDevice>();
            for (int i = 0; i < ids.length; i++) {
                mInputDevices.put(ids[i], null);
            }
        }
    
public voidregisterInputDeviceListener(android.hardware.input.InputManager$InputDeviceListener listener, android.os.Handler handler)
Registers an input device listener to receive notifications about when input devices are added, removed or changed.

param
listener The listener to register.
param
handler The handler on which the listener should be invoked, or null if the listener should be invoked on the calling thread's looper.
see
#unregisterInputDeviceListener

        if (listener == null) {
            throw new IllegalArgumentException("listener must not be null");
        }

        synchronized (mInputDevicesLock) {
            int index = findInputDeviceListenerLocked(listener);
            if (index < 0) {
                mInputDeviceListeners.add(new InputDeviceListenerDelegate(listener, handler));
            }
        }
    
public voidremoveKeyboardLayoutForInputDevice(InputDeviceIdentifier identifier, java.lang.String keyboardLayoutDescriptor)
Removes the keyboard layout descriptor for the specified input device.

This method may have the side-effect of causing the input device in question to be reconfigured.

param
identifier The identifier for the input device.
param
keyboardLayoutDescriptor The descriptor of the keyboard layout to remove.
hide

        if (identifier == null) {
            throw new IllegalArgumentException("inputDeviceDescriptor must not be null");
        }
        if (keyboardLayoutDescriptor == null) {
            throw new IllegalArgumentException("keyboardLayoutDescriptor must not be null");
        }

        try {
            mIm.removeKeyboardLayoutForInputDevice(identifier, keyboardLayoutDescriptor);
        } catch (RemoteException ex) {
            Log.w(TAG, "Could not remove keyboard layout for input device.", ex);
        }
    
private voidsendMessageToInputDeviceListenersLocked(int what, int deviceId)

        final int numListeners = mInputDeviceListeners.size();
        for (int i = 0; i < numListeners; i++) {
            InputDeviceListenerDelegate listener = mInputDeviceListeners.get(i);
            listener.sendMessage(listener.obtainMessage(what, deviceId, 0));
        }
    
public voidsetCurrentKeyboardLayoutForInputDevice(InputDeviceIdentifier identifier, java.lang.String keyboardLayoutDescriptor)
Sets the current keyboard layout descriptor for the specified input device.

This method may have the side-effect of causing the input device in question to be reconfigured.

param
identifier The identifier for the input device.
param
keyboardLayoutDescriptor The keyboard layout descriptor to use, must not be null.
hide

        if (identifier == null) {
            throw new IllegalArgumentException("identifier must not be null");
        }
        if (keyboardLayoutDescriptor == null) {
            throw new IllegalArgumentException("keyboardLayoutDescriptor must not be null");
        }

        try {
            mIm.setCurrentKeyboardLayoutForInputDevice(identifier,
                    keyboardLayoutDescriptor);
        } catch (RemoteException ex) {
            Log.w(TAG, "Could not set current keyboard layout for input device.", ex);
        }
    
public voidsetPointerSpeed(android.content.Context context, int speed)
Sets the mouse pointer speed.

Requires {@link android.Manifest.permissions.WRITE_SETTINGS}.

param
context The application context.
param
speed The pointer speed as a value between {@link #MIN_POINTER_SPEED} and {@link #MAX_POINTER_SPEED}, or the default value {@link #DEFAULT_POINTER_SPEED}.
hide

        if (speed < MIN_POINTER_SPEED || speed > MAX_POINTER_SPEED) {
            throw new IllegalArgumentException("speed out of range");
        }

        Settings.System.putInt(context.getContentResolver(),
                Settings.System.POINTER_SPEED, speed);
    
public voidsetTouchCalibration(java.lang.String inputDeviceDescriptor, int surfaceRotation, TouchCalibration calibration)
Sets the TouchCalibration to apply to the specified input device's coordinates.

This method may have the side-effect of causing the input device in question to be reconfigured. Requires {@link android.Manifest.permissions.SET_INPUT_CALIBRATION}.

param
inputDeviceDescriptor The input device descriptor.
param
calibration The calibration to be applied
hide

        try {
            mIm.setTouchCalibrationForInputDevice(inputDeviceDescriptor, surfaceRotation, calibration);
        } catch (RemoteException ex) {
            Log.w(TAG, "Could not set calibration matrix for input device.", ex);
        }
    
public voidtryPointerSpeed(int speed)
Changes the mouse pointer speed temporarily, but does not save the setting.

Requires {@link android.Manifest.permission.SET_POINTER_SPEED}.

param
speed The pointer speed as a value between {@link #MIN_POINTER_SPEED} and {@link #MAX_POINTER_SPEED}, or the default value {@link #DEFAULT_POINTER_SPEED}.
hide

        if (speed < MIN_POINTER_SPEED || speed > MAX_POINTER_SPEED) {
            throw new IllegalArgumentException("speed out of range");
        }

        try {
            mIm.tryPointerSpeed(speed);
        } catch (RemoteException ex) {
            Log.w(TAG, "Could not set temporary pointer speed.", ex);
        }
    
public voidunregisterInputDeviceListener(android.hardware.input.InputManager$InputDeviceListener listener)
Unregisters an input device listener.

param
listener The listener to unregister.
see
#registerInputDeviceListener

        if (listener == null) {
            throw new IllegalArgumentException("listener must not be null");
        }

        synchronized (mInputDevicesLock) {
            int index = findInputDeviceListenerLocked(listener);
            if (index >= 0) {
                InputDeviceListenerDelegate d = mInputDeviceListeners.get(index);
                d.removeCallbacksAndMessages(null);
                mInputDeviceListeners.remove(index);
            }
        }