How to use the power button on the mobile phone?

0

I wonder if you can use the power button on an app in your phone. Example: Performing some function if pressed the button three times in a row. If possible I would like some example. Thank you!

    
asked by anonymous 30.04.2016 / 18:36

1 answer

3

First, add the following to your Android Manifest

<uses-permission android:name="android.permission.PREVENT_POWER_KEY" />

Then in your activity that will capture click events, put the following code:

Identifying Simple Click

@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
    if (keyCode == KeyEvent.KEYCODE_POWER) {

        // Faça alguma coisa ...

        event.startTracking(); // Necessário para identificar cliques longos

        return true;
   }

   return super.onKeyDown(keyCode, event);
}

Identifying Long Click

@Override
public boolean onKeyLongPress(int keyCode, KeyEvent event) {
    if (keyCode == KeyEvent.KEYCODE_POWER) {

        // Faça alguma coisa...

        return true;
    }

    return super.onKeyLongPress(keyCode, event);
}

Note:

  • Response copied and adapted from: link

  • Original response author : JT

30.04.2016 / 23:13