1

I am trying to develop an app that would do something after clicking the power button.

I have a code that catches the onClick of Power button, but it don't seem to work. The screen would lock.

Now I am trying to catch the onLongPress of the Power Button, preventing the "Power Off" options from appearing. Any suggestions on how to do that?

thanks in advance.

emmandroid
  • 821
  • 1
  • 9
  • 19

3 Answers3

14

This will surely prevent long press button.

    @Override
    public void onWindowFocusChanged(boolean hasFocus) {
        super.onWindowFocusChanged(hasFocus);
        if(!hasFocus) {
           Intent closeDialog = new Intent(Intent.ACTION_CLOSE_SYSTEM_DIALOGS);
            sendBroadcast(closeDialog);
        }
    }
user1097940
  • 283
  • 3
  • 12
1

hi your just trying to get notifed of the event than as Kartik pointed out you just need play around with the onKeyDown Event.

but form what I understand of your question you actually want to prevent the behavior of the power button and that can't be done. just like the home button pressed some events in android can't be prevented to avoid people having apps they can't quit.

Jason Rogers
  • 19,194
  • 27
  • 79
  • 112
  • Thanks. After experimenting on this, I have shifted my focus from overriding the power button to overriding the menu button. It works perfectly now. – emmandroid Jul 28 '11 at 04:06
  • @emmandroid how did you overwrite the menu button...i also need to do it..plz answer – WISHY Oct 18 '13 at 06:54
  • i need this functionality too, can you tell how did you override power and home button please – Dimitri Dec 15 '14 at 07:49
0

You can force the screen to stay on, as described in http://developer.android.com/reference/android/os/PowerManager.html

This can drain CPU and mess with people's expectations of what happens when they hit the power button, so be careful with it.

Clueless
  • 3,984
  • 1
  • 20
  • 27
  • 2
    as you said yourself power management is dangerous to use, but more to the point your answer has nothing to do with the question: he is asking about the how to get the onkeypressed event and how to stop it, but powermanager only handels preventing the phone from putting on paue the app becaue its beens inactive too long. – Jason Rogers Jul 27 '11 at 07:10
  • From the link: "If you hold a partial wakelock, the CPU will continue to run, irrespective of any timers and even after the user presses the power button." So yes, it's not a direct answer, but I don't think you can actually intercept the power off button, only keep the CPU running and display whatever screen you want in response with the above API. – Clueless Jul 27 '11 at 07:23