1

My app has a long running background service. I registered my service with a broadcastreceiver which handles SCREEN_ON and SCREEN_OFF actions. However, the problem with using this approach is that while it does work, whenever the phone was woken up by incoming phone calls, power cable plugin events or alarmmanager etc, SCREEN_ON action also triggers and I don't want that.

Is it possible to "physically" capture the power button click events when only my background service is running? I'm not trying to override power button.

Jean Vitor
  • 893
  • 1
  • 18
  • 24
hal0360
  • 81
  • 1
  • 7

1 Answers1

-1

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.

reference : https://stackoverflow.com/a/10365166/2724418

Community
  • 1
  • 1
YFeizi
  • 1,498
  • 3
  • 28
  • 50
  • Thanks for your response. But your answer only works when there is an activity running. My requirement is for when there's only background service running. – hal0360 Aug 06 '16 at 23:46
  • 1
    Does not work for me at all. Base Android doesn't even have that permission. – John61590 Jul 25 '18 at 23:06