Search code examples
javaandroidlinuxandroid-hardware

Android/Linux: Log (power) key usage on lower system level


I'm not searching for a particular piece of code rather than a hint where to start my research. What I want to do might be an easy task for an experienced android developer.

I simply want to log all hardware button interactions on a lower level than the Dalvik engine. I'm very new to Android development and I've never developed on a Linux/Unix base but I have some minimal experience in C.

I often found people asking how they could use the power button in their Apps and what I found out was that in general thats not possible or at least not meant to be done since the system itself captures a press of the power button and doesn't hand it to applications or services running in the Java VM (unlike presses of the volume control buttons, for whose key events you can register a listener).

I, however, would like to write a simple process or whatever would fit the bill to log all presses of buttons (volume control, power button or whatever hardware buttons are available on a device).

Now since I'm very new to this topic and my knowledge is limited at this very moment, my first ideas were to either have a linux process or a kernel extension to do the job. Later I might want to populate my own messages, events or whatever which I then could receive in an App or a background service via JNI (if I understood it correctly) later.

So heres my question: what would I have to do to capture hardware button interactions and use them for my own purpose (logging a text message) without interfering with the default system functionality? A library, a process, a kernel extension or something completely different I haven't thought of yet? Any ideas or hints are highly appreciated.

Kind regards Jan Thielemann


Solution

  • After I did more research, I found out that Androids PhoneWindowManager.java method interceptKeyBeforeDispatching is a place where I can hook myself into.

    Now you either have to change this class and compile your own version of the system or you can use the xposed framework (on rooted devices) and it's method hooks to also get notified of the events.

    I used the method hooks beforeHookedMethod() method to check for KeyEvent events I'm interested in. As far as I can tell by now, I can intercept the KeyEvent (e. g. KeyEvent.KEYCODE_POWER) and execute my own code but still let the system decide what to do with the event.

    I even can check for patterns (e. g. a press between 3 and 5 seconds followed by a short press less than 1 second) to execute my code. By holding down power for 5 seconds, the system still offers me to shut down or restart the device but my code is also executed.