How to use the power button on your phone?

Asked

Viewed 1,616 times

0

I wonder if it is possible to use the power button (on and off) of the phone in an application. Example: Performing some function if pressed the button three times in a row. If possible I would like some example. Thanks in advance!

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 the click events, put the following code:

Identifying the 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 the 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);
}

Obs.:

Browser other questions tagged

You are not signed in. Login or sign up in order to post.