detect power button press?

In my application I'd like to take action upon power button press. Ideally, the onset of power button press, so that if someone initiates a long press of the power button, I can take action instantly. Is there a way to register a handler for events related to the power button?

Answers

  • In my application I'd like to take action upon power button press. Ideally, the onset of power button press, so that if someone initiates a long press of the power button, I can take action instantly. Is there a way to register a handler for events related to the power button?

  • Sorry for the double post.

  • Answer ✓

    Greetings!

    Yes, this is possible. This code is a complete application that will trace to the console when the power button is pressed and released:

    application.behavior = new class extends Behavior { 
        onKeyDown(app, key, modifiers, repeat, ticks){
            if (key.charCodeAt(0) == Event.FunctionKeyPower){
                trace("power button pressed\n");
                return true;
            }
        }
        onKeyUp(app, key, modifiers, repeat, ticks){
            if (key.charCodeAt(0) == Event.FunctionKeyPower){
                trace("power button released\n");
                return true;
            }
        }
    }
    

    The return true bit tells the event system that the keypress has been handled in the application. If you want both your own custom behavior and the default "bring up the power menu" behavior to trigger, just don't return true.

    — Andy

  • Thanks, that gets me part of the way there. I see that a long-press on the button does trigger onKeyDown, but returning true does not prevent power-off. I assume the long-press is detected in hardware, and thus can't be defeated.

  • Yes, that is correct. The power button is connected to a microcontroller that handles the "hard" power off. That's there to give everyone a way to turn off the device if it becomes completely unresponsive, and cannot easily be disabled.

Sign In or Register to comment.