Modern day smart-phones have already begun to migrate from the traditional "a-button-for-every-need" approach to the "huge-display-cum-touchscreen" form-factors. Android phones are no exception. But, traditional buttons are still required for a few oft-used functions (power,back,home,menu etc.) and smart-phones continue to have them alongwith the primary touch-based-UI.
Android-OS provides a very easy method to simulate key/button press/release events via software. You might ask why do we need a software to generate the events when a hardware button is already present on the device. Here's why:
During development/testing of the button-drivers itself.
To implement automated rigorous tests. (
To implement/interface additional custom software keyboards.
Just because we can!
Now, the basic goal of this exercise is extremely simple:
Q. How to generate a hardware-button-press event
WITHOUT actually pressing any key on the device?
Let us first understand what happens when a hardware button is pressed. Here is what happens when you press a button on an Android device:
The h/w button triggers an interrupt.
The ISR of the corresponding driver gets called (in kernel).
In the ISR, the driver generates an input-event.
Android-framework (in userspace) gets the notification of the event.
Android reads the input-event code & type.
Compares it with the proper "keymap/keylayout" file.
The proper button is identified.
To simulate button presses we enter this procedure at STEP3.
Instead of the regular driver generating the input-event, we generate an input-event ourselves using a pre-built userspace binary. This will then be notified to the Android-framework and the rest continues as above.
So now all depends on the the pre-built userspace binary ("command" for the non-geek community), which is...
[ drum-roll... ]
...input. (How convenient!)
The syntax of input is as follows:
input keyevent <event_code>
Now, before we try to send any keyevent, we need to find out the event-code that maps to the h/w key we want to simulate. The following table summarizes all the supported keycodes in Android:
Additionally we can look up the keylayout (.kl) file on the device. Personally, I find keylayout a misnomer, as we are not talking about different keyboards here, but different mappings of an input-event-value to its functionality.
Anyways you can always find the file in
For each device, the android.keylayout.<device-name> system property must be set. If a keylayout file is not specified, Android will default to
Now to generate a event of a specific keycode, we simply execute this on the terminal/serial console:
input keyevent <keycode>
The value of keycode can be any of the integer values from the above table. In case a serial-console is NOT available on your device, you can always run the command via
adb as follows:
adb shell input keyevent <keycode>
That's how a hardware-button-press is simulated in software!!