title: Detect power button long press
body: <p>I've been reading some posts here on Stackoverflow, and I didn't find a good solution, I'm wondering if it's possible to detect when the user long press the power button when trying to power off the device, I'd like to know if you can detect that event, and let or not show that dialog where appears (Restart, Shut Down, etc...)</p>
  
  <p>I've tried this:</p>
  
  <pre><code>@Override
  public boolean dispatchKeyEvent(KeyEvent event) {
          Toast.makeText(MainActivity.this, event.getKeyCode(), Toast.LENGTH_SHORT).show();
      return true;
  }
  </code></pre>
  
  <p>but it doesn't show up, also it should work as a service, I mean that the app can or not be opened to show that toast.</p>
  
  <h2>EDIT</h2>
  
  <p>This is how I put the <code>onCloseSystemDialog</code></p>
  
  <pre><code>//home or recent button
  public void onCloseSystemDialogs(String reason) {
      if ("globalactions".equals(reason)) {
          Toast.makeText(PowerButtonService.this, "yaps", Toast.LENGTH_SHORT).show();
          Intent i= new Intent(getBaseContext(), Demo.class);
          i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
          getApplication().startActivity(i);
      //} else if ("homekey".equals(reason)) {
          //home key pressed
      //} else if ("recentapss".equals(reason)) {
          // recent apps button clicked
      }
  }
  </code></pre>
  
  <p>It works fine, but only when the device is unlocked, when the device is locked isn't showing anything.</p>
  
  <p>Also I'm trying to figure out how to remove the dialog when the user click powerbutton I tried this : </p>
  
  <pre><code>getWindow().addFlags(WindowManager.LayoutParams.FLAG_DISMISS_KEYGUARD);
  </code></pre>
  
  <p>But if I want to show it again, how can I do it?</p>