title: Android: Listen for power key press
body: <p>I am currently trying to listen for when the power button is pressed. Ultimately I would like to have some code run when the power button is pressed twice, to check whether the screen is locked or unlocked. I currently have this:</p>
  
  <pre><code>  @Override
  public void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      setContentView(R.layout.main);
      getWindow().addFlags(WindowManager.LayoutParams.FLAG_DISMISS_KEYGUARD);//prevent phone from being locked
  }
  
  @Override 
  public boolean onKeyDown(int keyCode, KeyEvent event) {
  
      switch (keyCode) {
          case KeyEvent.KEYCODE_POWER:
          {
              Toast.makeText(getBaseContext(), "Power button pressed", Toast.LENGTH_LONG).show();
  
              return true;
          }
          case KeyEvent.KEYCODE_MENU:
              Toast.makeText(getBaseContext(), "Menu Button Pressed", Toast.LENGTH_LONG).show();
  
              return true;
      }
      return super.onKeyDown(keyCode, event);
  }
  </code></pre>
  
  <p>The code works fine to toast for the menu keyevent but doesn't do anything for the power key event. Any ideas?</p>