On an Android device, where the only buttons are the volume buttons and a power button, I want to make the app react to presses on the power button (long and short). How is this done?
To remap your Android power button, download Button Remapper app from the developer's website. Then go to Settings > Security and enable Unknown Sources before installing the app. You'll need to enable this feature; otherwise, you won't be able to install apps that were not downloaded from Google Play Store.
Hold down the volume down key and connect your phone via USB cable to your PC. Keep the volume button held down until you see a boot menu. Select the 'Start' option using your volume keys, and your phone will power on.
The existing answers don't completely answer the question and leave out enough details that they won't work without more investigation. I'll share what I've learned solving this.
First you need to add the following permission to your manifest file:
<uses-permission android:name="android.permission.PREVENT_POWER_KEY" />
To handle short and long presses add the following overrides to your activity class:
@Override public boolean onKeyDown(int keyCode, KeyEvent event) { if (keyCode == KeyEvent.KEYCODE_POWER) { // Do something here... event.startTracking(); // Needed to track long presses return true; } return super.onKeyDown(keyCode, event); } @Override public boolean onKeyLongPress(int keyCode, KeyEvent event) { if (keyCode == KeyEvent.KEYCODE_POWER) { // Do something here... return true; } return super.onKeyLongPress(keyCode, event); }
Note: It is worth noting that onKeyDown() will fire multiple times before onKeyLongPress does so you may want to trigger on onKeyUp() instead or other logic to prevent acting upon a series of onKeyDown() calls when the user is really holding it down.
I think this next part is for Cyanogenmod only. If the PREVENT_POWER_KEY constant is undefined then you should not need it.
To start intercepting the power key you need to set the following flag from your activity:
getWindow().addFlags(WindowManager.LayoutParams.PREVENT_POWER_KEY);
To stop intercepting the power key (allowing standard functionality):
getWindow().clearFlags(WindowManager.LayoutParams.PREVENT_POWER_KEY);
You can switch back and forth between the two modes repeatedly in your program if you wish.
Solution:
@Override public boolean dispatchKeyEvent(KeyEvent event) { if (event.getKeyCode() == KeyEvent.KEYCODE_POWER) { Intent i = new Intent(this, ActivitySetupMenu.class); startActivity(i); return true; } return super.dispatchKeyEvent(event); }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With