Java – Lets the Android service listen for hardware key press events

Lets the Android service listen for hardware key press events… here is a solution to the problem.

Lets the Android service listen for hardware key press events

I’m building a Panic Alert app on Android where I want its services to run in the background and am getting a partial wakelock to run when the screen is off. I want this service to listen for volume keys (or a combination of power and volume keys) pressed for 3 seconds or more to start the service to send urgent messages.

Is it possible to listen for critical events by binding my service to any other system service? Or, are there other ways to achieve my goals?

Solution

In order to listen for the power button press, you need to register listeners for SCREEN_ON and SCREEN_OFF events.

Android doesn’t record any of the ways in which such services listen for volume buttons, but you might want to take a look at this:
Listen to volume buttons in background service?

Related Problems and Solutions