Disable the power button in activity

Talib picture Talib · Feb 18, 2015 · Viewed 10.3k times · Source

I'm developing an app in which there is a requirement to not let the user to lock the screen or turn off the android device using power button,so I have to disable the power button and over ride the power button functionality, I have searched alot on internet as well but can't find anything.I have used these two pieces of code but still it did not work for me.

 @Override
      public boolean dispatchKeyEvent(KeyEvent event) {
              if (event.getKeyCode() == KeyEvent.KEYCODE_POWER) {
                      Log.i("", "Dispath event power");
                      Intent closeDialog = new Intent(Intent.ACTION_CLOSE_SYSTEM_DIALOGS);
                      sendBroadcast(closeDialog);
                      return true;
              }

              return super.dispatchKeyEvent(event);
      }
      public boolean onKeyDown(int keyCode, KeyEvent event)
      {
          if (keyCode == KeyEvent.KEYCODE_POWER) {
                // Back
                moveTaskToBack(true);
                return true;
            }

            else {
                // Return

Please help me thanks in advance.

Answer

SilentKnight picture SilentKnight · Apr 2, 2015

You can't deal with the Power event in any Android Apps. Events ofPower Buttonare handled in Framework level in Android architecture. You can't stop framework to dispatch events but accept its dispatch. You can receive the result of event dispatch from framework but not block the process.