title: Overriding the power button in Android
body: <p>I'm developing an app in which I need to do an action when the power button is pressed but unfortunately I cant handel the action of power button when it is pressed. I tried using the onKeyDown() and dispatchKeyEvent() methods but nothing seems to be working. Can anyone suggest me any other method or solution for this problem.</p>
  
  <pre><code>public boolean onKeyDown(int keyCode, KeyEvent event) {
  if (event.getKeyCode() == KeyEvent.KEYCODE_POWER) {
      // The action I want to perform when power button is pressed.
      return true;
  }
  return super.onKeyDown(keyCode, event);
  }
  </code></pre>
  
  <p>and</p>
  
  <pre><code>@Override
  public boolean dispatchKeyEvent(KeyEvent event) {
  if (event.getKeyCode() == KeyEvent.KEYCODE_POWER) {
      Intent i = new Intent(this, NewActivity.class);
      startActivity(i);
      return true;
  }
  return super.dispatchKeyEvent(event);
  }
  </code></pre>